]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
MFV r323678: file 5.32
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaExpr.cpp
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73
74   return true;
75 }
76
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89
90 /// \brief Emit a note explaining that this function is deleted.
91 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
92   assert(Decl->isDeleted());
93
94   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
95
96   if (Method && Method->isDeleted() && Method->isDefaulted()) {
97     // If the method was explicitly defaulted, point at that declaration.
98     if (!Method->isImplicit())
99       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
100
101     // Try to diagnose why this special member function was implicitly
102     // deleted. This might fail, if that reason no longer applies.
103     CXXSpecialMember CSM = getSpecialMember(Method);
104     if (CSM != CXXInvalid)
105       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
106
107     return;
108   }
109
110   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
111   if (Ctor && Ctor->isInheritingConstructor())
112     return NoteDeletedInheritingConstructor(Ctor);
113
114   Diag(Decl->getLocation(), diag::note_availability_specified_here)
115     << Decl << true;
116 }
117
118 /// \brief Determine whether a FunctionDecl was ever declared with an
119 /// explicit storage class.
120 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
121   for (auto I : D->redecls()) {
122     if (I->getStorageClass() != SC_None)
123       return true;
124   }
125   return false;
126 }
127
128 /// \brief Check whether we're in an extern inline function and referring to a
129 /// variable or function with internal linkage (C11 6.7.4p3).
130 ///
131 /// This is only a warning because we used to silently accept this code, but
132 /// in many cases it will not behave correctly. This is not enabled in C++ mode
133 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
134 /// and so while there may still be user mistakes, most of the time we can't
135 /// prove that there are errors.
136 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
137                                                       const NamedDecl *D,
138                                                       SourceLocation Loc) {
139   // This is disabled under C++; there are too many ways for this to fire in
140   // contexts where the warning is a false positive, or where it is technically
141   // correct but benign.
142   if (S.getLangOpts().CPlusPlus)
143     return;
144
145   // Check if this is an inlined function or method.
146   FunctionDecl *Current = S.getCurFunctionDecl();
147   if (!Current)
148     return;
149   if (!Current->isInlined())
150     return;
151   if (!Current->isExternallyVisible())
152     return;
153
154   // Check if the decl has internal linkage.
155   if (D->getFormalLinkage() != InternalLinkage)
156     return;
157
158   // Downgrade from ExtWarn to Extension if
159   //  (1) the supposedly external inline function is in the main file,
160   //      and probably won't be included anywhere else.
161   //  (2) the thing we're referencing is a pure function.
162   //  (3) the thing we're referencing is another inline function.
163   // This last can give us false negatives, but it's better than warning on
164   // wrappers for simple C library functions.
165   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
166   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
167   if (!DowngradeWarning && UsedFn)
168     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
169
170   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
171                                : diag::ext_internal_in_extern_inline)
172     << /*IsVar=*/!UsedFn << D;
173
174   S.MaybeSuggestAddingStaticToDecl(Current);
175
176   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
177       << D;
178 }
179
180 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
181   const FunctionDecl *First = Cur->getFirstDecl();
182
183   // Suggest "static" on the function, if possible.
184   if (!hasAnyExplicitStorageClass(First)) {
185     SourceLocation DeclBegin = First->getSourceRange().getBegin();
186     Diag(DeclBegin, diag::note_convert_inline_to_static)
187       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
188   }
189 }
190
191 /// \brief Determine whether the use of this declaration is valid, and
192 /// emit any corresponding diagnostics.
193 ///
194 /// This routine diagnoses various problems with referencing
195 /// declarations that can occur when using a declaration. For example,
196 /// it might warn if a deprecated or unavailable declaration is being
197 /// used, or produce an error (and return true) if a C++0x deleted
198 /// function is being used.
199 ///
200 /// \returns true if there was an error (this declaration cannot be
201 /// referenced), false otherwise.
202 ///
203 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
204                              const ObjCInterfaceDecl *UnknownObjCClass,
205                              bool ObjCPropertyAccess,
206                              bool AvoidPartialAvailabilityChecks) {
207   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
208     // If there were any diagnostics suppressed by template argument deduction,
209     // emit them now.
210     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
211     if (Pos != SuppressedDiagnostics.end()) {
212       for (const PartialDiagnosticAt &Suppressed : Pos->second)
213         Diag(Suppressed.first, Suppressed.second);
214
215       // Clear out the list of suppressed diagnostics, so that we don't emit
216       // them again for this specialization. However, we don't obsolete this
217       // entry from the table, because we want to avoid ever emitting these
218       // diagnostics again.
219       Pos->second.clear();
220     }
221
222     // C++ [basic.start.main]p3:
223     //   The function 'main' shall not be used within a program.
224     if (cast<FunctionDecl>(D)->isMain())
225       Diag(Loc, diag::ext_main_used);
226   }
227
228   // See if this is an auto-typed variable whose initializer we are parsing.
229   if (ParsingInitForAutoVars.count(D)) {
230     if (isa<BindingDecl>(D)) {
231       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
232         << D->getDeclName();
233     } else {
234       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
235         << D->getDeclName() << cast<VarDecl>(D)->getType();
236     }
237     return true;
238   }
239
240   // See if this is a deleted function.
241   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
242     if (FD->isDeleted()) {
243       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
244       if (Ctor && Ctor->isInheritingConstructor())
245         Diag(Loc, diag::err_deleted_inherited_ctor_use)
246             << Ctor->getParent()
247             << Ctor->getInheritedConstructor().getConstructor()->getParent();
248       else 
249         Diag(Loc, diag::err_deleted_function_use);
250       NoteDeletedFunction(FD);
251       return true;
252     }
253
254     // If the function has a deduced return type, and we can't deduce it,
255     // then we can't use it either.
256     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
257         DeduceReturnType(FD, Loc))
258       return true;
259
260     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
261       return true;
262   }
263
264   auto getReferencedObjCProp = [](const NamedDecl *D) ->
265                                       const ObjCPropertyDecl * {
266     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
267       return MD->findPropertyDecl();
268     return nullptr;
269   };
270   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
271     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
272       return true;
273   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
274       return true;
275   }
276
277   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
278   // Only the variables omp_in and omp_out are allowed in the combiner.
279   // Only the variables omp_priv and omp_orig are allowed in the
280   // initializer-clause.
281   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
282   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
283       isa<VarDecl>(D)) {
284     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
285         << getCurFunction()->HasOMPDeclareReductionCombiner;
286     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
287     return true;
288   }
289
290   DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess,
291                              AvoidPartialAvailabilityChecks);
292
293   DiagnoseUnusedOfDecl(*this, D, Loc);
294
295   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
296
297   return false;
298 }
299
300 /// \brief Retrieve the message suffix that should be added to a
301 /// diagnostic complaining about the given function being deleted or
302 /// unavailable.
303 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
304   std::string Message;
305   if (FD->getAvailability(&Message))
306     return ": " + Message;
307
308   return std::string();
309 }
310
311 /// DiagnoseSentinelCalls - This routine checks whether a call or
312 /// message-send is to a declaration with the sentinel attribute, and
313 /// if so, it checks that the requirements of the sentinel are
314 /// satisfied.
315 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
316                                  ArrayRef<Expr *> Args) {
317   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
318   if (!attr)
319     return;
320
321   // The number of formal parameters of the declaration.
322   unsigned numFormalParams;
323
324   // The kind of declaration.  This is also an index into a %select in
325   // the diagnostic.
326   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
327
328   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
329     numFormalParams = MD->param_size();
330     calleeType = CT_Method;
331   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
332     numFormalParams = FD->param_size();
333     calleeType = CT_Function;
334   } else if (isa<VarDecl>(D)) {
335     QualType type = cast<ValueDecl>(D)->getType();
336     const FunctionType *fn = nullptr;
337     if (const PointerType *ptr = type->getAs<PointerType>()) {
338       fn = ptr->getPointeeType()->getAs<FunctionType>();
339       if (!fn) return;
340       calleeType = CT_Function;
341     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
342       fn = ptr->getPointeeType()->castAs<FunctionType>();
343       calleeType = CT_Block;
344     } else {
345       return;
346     }
347
348     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
349       numFormalParams = proto->getNumParams();
350     } else {
351       numFormalParams = 0;
352     }
353   } else {
354     return;
355   }
356
357   // "nullPos" is the number of formal parameters at the end which
358   // effectively count as part of the variadic arguments.  This is
359   // useful if you would prefer to not have *any* formal parameters,
360   // but the language forces you to have at least one.
361   unsigned nullPos = attr->getNullPos();
362   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
363   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
364
365   // The number of arguments which should follow the sentinel.
366   unsigned numArgsAfterSentinel = attr->getSentinel();
367
368   // If there aren't enough arguments for all the formal parameters,
369   // the sentinel, and the args after the sentinel, complain.
370   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
371     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
372     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
373     return;
374   }
375
376   // Otherwise, find the sentinel expression.
377   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
378   if (!sentinelExpr) return;
379   if (sentinelExpr->isValueDependent()) return;
380   if (Context.isSentinelNullExpr(sentinelExpr)) return;
381
382   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
383   // or 'NULL' if those are actually defined in the context.  Only use
384   // 'nil' for ObjC methods, where it's much more likely that the
385   // variadic arguments form a list of object pointers.
386   SourceLocation MissingNilLoc
387     = getLocForEndOfToken(sentinelExpr->getLocEnd());
388   std::string NullValue;
389   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
390     NullValue = "nil";
391   else if (getLangOpts().CPlusPlus11)
392     NullValue = "nullptr";
393   else if (PP.isMacroDefined("NULL"))
394     NullValue = "NULL";
395   else
396     NullValue = "(void*) 0";
397
398   if (MissingNilLoc.isInvalid())
399     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
400   else
401     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
402       << int(calleeType)
403       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
404   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
405 }
406
407 SourceRange Sema::getExprRange(Expr *E) const {
408   return E ? E->getSourceRange() : SourceRange();
409 }
410
411 //===----------------------------------------------------------------------===//
412 //  Standard Promotions and Conversions
413 //===----------------------------------------------------------------------===//
414
415 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
416 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
417   // Handle any placeholder expressions which made it here.
418   if (E->getType()->isPlaceholderType()) {
419     ExprResult result = CheckPlaceholderExpr(E);
420     if (result.isInvalid()) return ExprError();
421     E = result.get();
422   }
423   
424   QualType Ty = E->getType();
425   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
426
427   if (Ty->isFunctionType()) {
428     // If we are here, we are not calling a function but taking
429     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
430     if (getLangOpts().OpenCL) {
431       if (Diagnose)
432         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
433       return ExprError();
434     }
435
436     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
437       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
438         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
439           return ExprError();
440
441     E = ImpCastExprToType(E, Context.getPointerType(Ty),
442                           CK_FunctionToPointerDecay).get();
443   } else if (Ty->isArrayType()) {
444     // In C90 mode, arrays only promote to pointers if the array expression is
445     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
446     // type 'array of type' is converted to an expression that has type 'pointer
447     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
448     // that has type 'array of type' ...".  The relevant change is "an lvalue"
449     // (C90) to "an expression" (C99).
450     //
451     // C++ 4.2p1:
452     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
453     // T" can be converted to an rvalue of type "pointer to T".
454     //
455     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
456       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
457                             CK_ArrayToPointerDecay).get();
458   }
459   return E;
460 }
461
462 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
463   // Check to see if we are dereferencing a null pointer.  If so,
464   // and if not volatile-qualified, this is undefined behavior that the
465   // optimizer will delete, so warn about it.  People sometimes try to use this
466   // to get a deterministic trap and are surprised by clang's behavior.  This
467   // only handles the pattern "*null", which is a very syntactic check.
468   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
469     if (UO->getOpcode() == UO_Deref &&
470         UO->getSubExpr()->IgnoreParenCasts()->
471           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
472         !UO->getType().isVolatileQualified()) {
473     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
474                           S.PDiag(diag::warn_indirection_through_null)
475                             << UO->getSubExpr()->getSourceRange());
476     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
477                         S.PDiag(diag::note_indirection_through_null));
478   }
479 }
480
481 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
482                                     SourceLocation AssignLoc,
483                                     const Expr* RHS) {
484   const ObjCIvarDecl *IV = OIRE->getDecl();
485   if (!IV)
486     return;
487   
488   DeclarationName MemberName = IV->getDeclName();
489   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
490   if (!Member || !Member->isStr("isa"))
491     return;
492   
493   const Expr *Base = OIRE->getBase();
494   QualType BaseType = Base->getType();
495   if (OIRE->isArrow())
496     BaseType = BaseType->getPointeeType();
497   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
498     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
499       ObjCInterfaceDecl *ClassDeclared = nullptr;
500       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
501       if (!ClassDeclared->getSuperClass()
502           && (*ClassDeclared->ivar_begin()) == IV) {
503         if (RHS) {
504           NamedDecl *ObjectSetClass =
505             S.LookupSingleName(S.TUScope,
506                                &S.Context.Idents.get("object_setClass"),
507                                SourceLocation(), S.LookupOrdinaryName);
508           if (ObjectSetClass) {
509             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
510             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
511             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
512             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
513                                                      AssignLoc), ",") <<
514             FixItHint::CreateInsertion(RHSLocEnd, ")");
515           }
516           else
517             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
518         } else {
519           NamedDecl *ObjectGetClass =
520             S.LookupSingleName(S.TUScope,
521                                &S.Context.Idents.get("object_getClass"),
522                                SourceLocation(), S.LookupOrdinaryName);
523           if (ObjectGetClass)
524             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
525             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
526             FixItHint::CreateReplacement(
527                                          SourceRange(OIRE->getOpLoc(),
528                                                      OIRE->getLocEnd()), ")");
529           else
530             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
531         }
532         S.Diag(IV->getLocation(), diag::note_ivar_decl);
533       }
534     }
535 }
536
537 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
538   // Handle any placeholder expressions which made it here.
539   if (E->getType()->isPlaceholderType()) {
540     ExprResult result = CheckPlaceholderExpr(E);
541     if (result.isInvalid()) return ExprError();
542     E = result.get();
543   }
544   
545   // C++ [conv.lval]p1:
546   //   A glvalue of a non-function, non-array type T can be
547   //   converted to a prvalue.
548   if (!E->isGLValue()) return E;
549
550   QualType T = E->getType();
551   assert(!T.isNull() && "r-value conversion on typeless expression?");
552
553   // We don't want to throw lvalue-to-rvalue casts on top of
554   // expressions of certain types in C++.
555   if (getLangOpts().CPlusPlus &&
556       (E->getType() == Context.OverloadTy ||
557        T->isDependentType() ||
558        T->isRecordType()))
559     return E;
560
561   // The C standard is actually really unclear on this point, and
562   // DR106 tells us what the result should be but not why.  It's
563   // generally best to say that void types just doesn't undergo
564   // lvalue-to-rvalue at all.  Note that expressions of unqualified
565   // 'void' type are never l-values, but qualified void can be.
566   if (T->isVoidType())
567     return E;
568
569   // OpenCL usually rejects direct accesses to values of 'half' type.
570   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
571       T->isHalfType()) {
572     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
573       << 0 << T;
574     return ExprError();
575   }
576
577   CheckForNullPointerDereference(*this, E);
578   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
579     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
580                                      &Context.Idents.get("object_getClass"),
581                                      SourceLocation(), LookupOrdinaryName);
582     if (ObjectGetClass)
583       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
584         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
585         FixItHint::CreateReplacement(
586                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
587     else
588       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
589   }
590   else if (const ObjCIvarRefExpr *OIRE =
591             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
592     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
593
594   // C++ [conv.lval]p1:
595   //   [...] If T is a non-class type, the type of the prvalue is the
596   //   cv-unqualified version of T. Otherwise, the type of the
597   //   rvalue is T.
598   //
599   // C99 6.3.2.1p2:
600   //   If the lvalue has qualified type, the value has the unqualified
601   //   version of the type of the lvalue; otherwise, the value has the
602   //   type of the lvalue.
603   if (T.hasQualifiers())
604     T = T.getUnqualifiedType();
605
606   // Under the MS ABI, lock down the inheritance model now.
607   if (T->isMemberPointerType() &&
608       Context.getTargetInfo().getCXXABI().isMicrosoft())
609     (void)isCompleteType(E->getExprLoc(), T);
610
611   UpdateMarkingForLValueToRValue(E);
612   
613   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
614   // balance that.
615   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
616     Cleanup.setExprNeedsCleanups(true);
617
618   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
619                                             nullptr, VK_RValue);
620
621   // C11 6.3.2.1p2:
622   //   ... if the lvalue has atomic type, the value has the non-atomic version 
623   //   of the type of the lvalue ...
624   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
625     T = Atomic->getValueType().getUnqualifiedType();
626     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
627                                    nullptr, VK_RValue);
628   }
629   
630   return Res;
631 }
632
633 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
634   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
635   if (Res.isInvalid())
636     return ExprError();
637   Res = DefaultLvalueConversion(Res.get());
638   if (Res.isInvalid())
639     return ExprError();
640   return Res;
641 }
642
643 /// CallExprUnaryConversions - a special case of an unary conversion
644 /// performed on a function designator of a call expression.
645 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
646   QualType Ty = E->getType();
647   ExprResult Res = E;
648   // Only do implicit cast for a function type, but not for a pointer
649   // to function type.
650   if (Ty->isFunctionType()) {
651     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
652                             CK_FunctionToPointerDecay).get();
653     if (Res.isInvalid())
654       return ExprError();
655   }
656   Res = DefaultLvalueConversion(Res.get());
657   if (Res.isInvalid())
658     return ExprError();
659   return Res.get();
660 }
661
662 /// UsualUnaryConversions - Performs various conversions that are common to most
663 /// operators (C99 6.3). The conversions of array and function types are
664 /// sometimes suppressed. For example, the array->pointer conversion doesn't
665 /// apply if the array is an argument to the sizeof or address (&) operators.
666 /// In these instances, this routine should *not* be called.
667 ExprResult Sema::UsualUnaryConversions(Expr *E) {
668   // First, convert to an r-value.
669   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
670   if (Res.isInvalid())
671     return ExprError();
672   E = Res.get();
673
674   QualType Ty = E->getType();
675   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
676
677   // Half FP have to be promoted to float unless it is natively supported
678   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
679     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
680
681   // Try to perform integral promotions if the object has a theoretically
682   // promotable type.
683   if (Ty->isIntegralOrUnscopedEnumerationType()) {
684     // C99 6.3.1.1p2:
685     //
686     //   The following may be used in an expression wherever an int or
687     //   unsigned int may be used:
688     //     - an object or expression with an integer type whose integer
689     //       conversion rank is less than or equal to the rank of int
690     //       and unsigned int.
691     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
692     //
693     //   If an int can represent all values of the original type, the
694     //   value is converted to an int; otherwise, it is converted to an
695     //   unsigned int. These are called the integer promotions. All
696     //   other types are unchanged by the integer promotions.
697
698     QualType PTy = Context.isPromotableBitField(E);
699     if (!PTy.isNull()) {
700       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
701       return E;
702     }
703     if (Ty->isPromotableIntegerType()) {
704       QualType PT = Context.getPromotedIntegerType(Ty);
705       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
706       return E;
707     }
708   }
709   return E;
710 }
711
712 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
713 /// do not have a prototype. Arguments that have type float or __fp16
714 /// are promoted to double. All other argument types are converted by
715 /// UsualUnaryConversions().
716 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
717   QualType Ty = E->getType();
718   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
719
720   ExprResult Res = UsualUnaryConversions(E);
721   if (Res.isInvalid())
722     return ExprError();
723   E = Res.get();
724
725   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
726   // double.
727   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
728   if (BTy && (BTy->getKind() == BuiltinType::Half ||
729               BTy->getKind() == BuiltinType::Float)) {
730     if (getLangOpts().OpenCL &&
731         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
732         if (BTy->getKind() == BuiltinType::Half) {
733             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
734         }
735     } else {
736       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
737     }
738   }
739
740   // C++ performs lvalue-to-rvalue conversion as a default argument
741   // promotion, even on class types, but note:
742   //   C++11 [conv.lval]p2:
743   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
744   //     operand or a subexpression thereof the value contained in the
745   //     referenced object is not accessed. Otherwise, if the glvalue
746   //     has a class type, the conversion copy-initializes a temporary
747   //     of type T from the glvalue and the result of the conversion
748   //     is a prvalue for the temporary.
749   // FIXME: add some way to gate this entire thing for correctness in
750   // potentially potentially evaluated contexts.
751   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
752     ExprResult Temp = PerformCopyInitialization(
753                        InitializedEntity::InitializeTemporary(E->getType()),
754                                                 E->getExprLoc(), E);
755     if (Temp.isInvalid())
756       return ExprError();
757     E = Temp.get();
758   }
759
760   return E;
761 }
762
763 /// Determine the degree of POD-ness for an expression.
764 /// Incomplete types are considered POD, since this check can be performed
765 /// when we're in an unevaluated context.
766 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
767   if (Ty->isIncompleteType()) {
768     // C++11 [expr.call]p7:
769     //   After these conversions, if the argument does not have arithmetic,
770     //   enumeration, pointer, pointer to member, or class type, the program
771     //   is ill-formed.
772     //
773     // Since we've already performed array-to-pointer and function-to-pointer
774     // decay, the only such type in C++ is cv void. This also handles
775     // initializer lists as variadic arguments.
776     if (Ty->isVoidType())
777       return VAK_Invalid;
778
779     if (Ty->isObjCObjectType())
780       return VAK_Invalid;
781     return VAK_Valid;
782   }
783
784   if (Ty.isCXX98PODType(Context))
785     return VAK_Valid;
786
787   // C++11 [expr.call]p7:
788   //   Passing a potentially-evaluated argument of class type (Clause 9)
789   //   having a non-trivial copy constructor, a non-trivial move constructor,
790   //   or a non-trivial destructor, with no corresponding parameter,
791   //   is conditionally-supported with implementation-defined semantics.
792   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
793     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
794       if (!Record->hasNonTrivialCopyConstructor() &&
795           !Record->hasNonTrivialMoveConstructor() &&
796           !Record->hasNonTrivialDestructor())
797         return VAK_ValidInCXX11;
798
799   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
800     return VAK_Valid;
801
802   if (Ty->isObjCObjectType())
803     return VAK_Invalid;
804
805   if (getLangOpts().MSVCCompat)
806     return VAK_MSVCUndefined;
807
808   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
809   // permitted to reject them. We should consider doing so.
810   return VAK_Undefined;
811 }
812
813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
814   // Don't allow one to pass an Objective-C interface to a vararg.
815   const QualType &Ty = E->getType();
816   VarArgKind VAK = isValidVarArgType(Ty);
817
818   // Complain about passing non-POD types through varargs.
819   switch (VAK) {
820   case VAK_ValidInCXX11:
821     DiagRuntimeBehavior(
822         E->getLocStart(), nullptr,
823         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
824           << Ty << CT);
825     // Fall through.
826   case VAK_Valid:
827     if (Ty->isRecordType()) {
828       // This is unlikely to be what the user intended. If the class has a
829       // 'c_str' member function, the user probably meant to call that.
830       DiagRuntimeBehavior(E->getLocStart(), nullptr,
831                           PDiag(diag::warn_pass_class_arg_to_vararg)
832                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
833     }
834     break;
835
836   case VAK_Undefined:
837   case VAK_MSVCUndefined:
838     DiagRuntimeBehavior(
839         E->getLocStart(), nullptr,
840         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
841           << getLangOpts().CPlusPlus11 << Ty << CT);
842     break;
843
844   case VAK_Invalid:
845     if (Ty->isObjCObjectType())
846       DiagRuntimeBehavior(
847           E->getLocStart(), nullptr,
848           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
849             << Ty << CT);
850     else
851       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
852         << isa<InitListExpr>(E) << Ty << CT;
853     break;
854   }
855 }
856
857 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
858 /// will create a trap if the resulting type is not a POD type.
859 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
860                                                   FunctionDecl *FDecl) {
861   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
862     // Strip the unbridged-cast placeholder expression off, if applicable.
863     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
864         (CT == VariadicMethod ||
865          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
866       E = stripARCUnbridgedCast(E);
867
868     // Otherwise, do normal placeholder checking.
869     } else {
870       ExprResult ExprRes = CheckPlaceholderExpr(E);
871       if (ExprRes.isInvalid())
872         return ExprError();
873       E = ExprRes.get();
874     }
875   }
876   
877   ExprResult ExprRes = DefaultArgumentPromotion(E);
878   if (ExprRes.isInvalid())
879     return ExprError();
880   E = ExprRes.get();
881
882   // Diagnostics regarding non-POD argument types are
883   // emitted along with format string checking in Sema::CheckFunctionCall().
884   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
885     // Turn this into a trap.
886     CXXScopeSpec SS;
887     SourceLocation TemplateKWLoc;
888     UnqualifiedId Name;
889     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
890                        E->getLocStart());
891     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
892                                           Name, true, false);
893     if (TrapFn.isInvalid())
894       return ExprError();
895
896     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
897                                     E->getLocStart(), None,
898                                     E->getLocEnd());
899     if (Call.isInvalid())
900       return ExprError();
901
902     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
903                                   Call.get(), E);
904     if (Comma.isInvalid())
905       return ExprError();
906     return Comma.get();
907   }
908
909   if (!getLangOpts().CPlusPlus &&
910       RequireCompleteType(E->getExprLoc(), E->getType(),
911                           diag::err_call_incomplete_argument))
912     return ExprError();
913
914   return E;
915 }
916
917 /// \brief Converts an integer to complex float type.  Helper function of
918 /// UsualArithmeticConversions()
919 ///
920 /// \return false if the integer expression is an integer type and is
921 /// successfully converted to the complex type.
922 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
923                                                   ExprResult &ComplexExpr,
924                                                   QualType IntTy,
925                                                   QualType ComplexTy,
926                                                   bool SkipCast) {
927   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
928   if (SkipCast) return false;
929   if (IntTy->isIntegerType()) {
930     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
931     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
932     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
933                                   CK_FloatingRealToComplex);
934   } else {
935     assert(IntTy->isComplexIntegerType());
936     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
937                                   CK_IntegralComplexToFloatingComplex);
938   }
939   return false;
940 }
941
942 /// \brief Handle arithmetic conversion with complex types.  Helper function of
943 /// UsualArithmeticConversions()
944 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
945                                              ExprResult &RHS, QualType LHSType,
946                                              QualType RHSType,
947                                              bool IsCompAssign) {
948   // if we have an integer operand, the result is the complex type.
949   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
950                                              /*skipCast*/false))
951     return LHSType;
952   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
953                                              /*skipCast*/IsCompAssign))
954     return RHSType;
955
956   // This handles complex/complex, complex/float, or float/complex.
957   // When both operands are complex, the shorter operand is converted to the
958   // type of the longer, and that is the type of the result. This corresponds
959   // to what is done when combining two real floating-point operands.
960   // The fun begins when size promotion occur across type domains.
961   // From H&S 6.3.4: When one operand is complex and the other is a real
962   // floating-point type, the less precise type is converted, within it's
963   // real or complex domain, to the precision of the other type. For example,
964   // when combining a "long double" with a "double _Complex", the
965   // "double _Complex" is promoted to "long double _Complex".
966
967   // Compute the rank of the two types, regardless of whether they are complex.
968   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
969
970   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
971   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
972   QualType LHSElementType =
973       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
974   QualType RHSElementType =
975       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
976
977   QualType ResultType = S.Context.getComplexType(LHSElementType);
978   if (Order < 0) {
979     // Promote the precision of the LHS if not an assignment.
980     ResultType = S.Context.getComplexType(RHSElementType);
981     if (!IsCompAssign) {
982       if (LHSComplexType)
983         LHS =
984             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
985       else
986         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
987     }
988   } else if (Order > 0) {
989     // Promote the precision of the RHS.
990     if (RHSComplexType)
991       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
992     else
993       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
994   }
995   return ResultType;
996 }
997
998 /// \brief Hande arithmetic conversion from integer to float.  Helper function
999 /// of UsualArithmeticConversions()
1000 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1001                                            ExprResult &IntExpr,
1002                                            QualType FloatTy, QualType IntTy,
1003                                            bool ConvertFloat, bool ConvertInt) {
1004   if (IntTy->isIntegerType()) {
1005     if (ConvertInt)
1006       // Convert intExpr to the lhs floating point type.
1007       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1008                                     CK_IntegralToFloating);
1009     return FloatTy;
1010   }
1011      
1012   // Convert both sides to the appropriate complex float.
1013   assert(IntTy->isComplexIntegerType());
1014   QualType result = S.Context.getComplexType(FloatTy);
1015
1016   // _Complex int -> _Complex float
1017   if (ConvertInt)
1018     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1019                                   CK_IntegralComplexToFloatingComplex);
1020
1021   // float -> _Complex float
1022   if (ConvertFloat)
1023     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1024                                     CK_FloatingRealToComplex);
1025
1026   return result;
1027 }
1028
1029 /// \brief Handle arithmethic conversion with floating point types.  Helper
1030 /// function of UsualArithmeticConversions()
1031 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1032                                       ExprResult &RHS, QualType LHSType,
1033                                       QualType RHSType, bool IsCompAssign) {
1034   bool LHSFloat = LHSType->isRealFloatingType();
1035   bool RHSFloat = RHSType->isRealFloatingType();
1036
1037   // If we have two real floating types, convert the smaller operand
1038   // to the bigger result.
1039   if (LHSFloat && RHSFloat) {
1040     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1041     if (order > 0) {
1042       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1043       return LHSType;
1044     }
1045
1046     assert(order < 0 && "illegal float comparison");
1047     if (!IsCompAssign)
1048       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1049     return RHSType;
1050   }
1051
1052   if (LHSFloat) {
1053     // Half FP has to be promoted to float unless it is natively supported
1054     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1055       LHSType = S.Context.FloatTy;
1056
1057     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1058                                       /*convertFloat=*/!IsCompAssign,
1059                                       /*convertInt=*/ true);
1060   }
1061   assert(RHSFloat);
1062   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1063                                     /*convertInt=*/ true,
1064                                     /*convertFloat=*/!IsCompAssign);
1065 }
1066
1067 /// \brief Diagnose attempts to convert between __float128 and long double if
1068 /// there is no support for such conversion. Helper function of
1069 /// UsualArithmeticConversions().
1070 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1071                                       QualType RHSType) {
1072   /*  No issue converting if at least one of the types is not a floating point
1073       type or the two types have the same rank.
1074   */
1075   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1076       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1077     return false;
1078
1079   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1080          "The remaining types must be floating point types.");
1081
1082   auto *LHSComplex = LHSType->getAs<ComplexType>();
1083   auto *RHSComplex = RHSType->getAs<ComplexType>();
1084
1085   QualType LHSElemType = LHSComplex ?
1086     LHSComplex->getElementType() : LHSType;
1087   QualType RHSElemType = RHSComplex ?
1088     RHSComplex->getElementType() : RHSType;
1089
1090   // No issue if the two types have the same representation
1091   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1092       &S.Context.getFloatTypeSemantics(RHSElemType))
1093     return false;
1094
1095   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1096                                 RHSElemType == S.Context.LongDoubleTy);
1097   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1098                             RHSElemType == S.Context.Float128Ty);
1099
1100   /* We've handled the situation where __float128 and long double have the same
1101      representation. The only other allowable conversion is if long double is
1102      really just double.
1103   */
1104   return Float128AndLongDouble &&
1105     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1106      &llvm::APFloat::IEEEdouble());
1107 }
1108
1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1110
1111 namespace {
1112 /// These helper callbacks are placed in an anonymous namespace to
1113 /// permit their use as function template parameters.
1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1115   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1116 }
1117
1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1119   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1120                              CK_IntegralComplexCast);
1121 }
1122 }
1123
1124 /// \brief Handle integer arithmetic conversions.  Helper function of
1125 /// UsualArithmeticConversions()
1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1128                                         ExprResult &RHS, QualType LHSType,
1129                                         QualType RHSType, bool IsCompAssign) {
1130   // The rules for this case are in C99 6.3.1.8
1131   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1132   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1133   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1134   if (LHSSigned == RHSSigned) {
1135     // Same signedness; use the higher-ranked type
1136     if (order >= 0) {
1137       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1138       return LHSType;
1139     } else if (!IsCompAssign)
1140       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1141     return RHSType;
1142   } else if (order != (LHSSigned ? 1 : -1)) {
1143     // The unsigned type has greater than or equal rank to the
1144     // signed type, so use the unsigned type
1145     if (RHSSigned) {
1146       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1147       return LHSType;
1148     } else if (!IsCompAssign)
1149       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1150     return RHSType;
1151   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1152     // The two types are different widths; if we are here, that
1153     // means the signed type is larger than the unsigned type, so
1154     // use the signed type.
1155     if (LHSSigned) {
1156       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1157       return LHSType;
1158     } else if (!IsCompAssign)
1159       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1160     return RHSType;
1161   } else {
1162     // The signed type is higher-ranked than the unsigned type,
1163     // but isn't actually any bigger (like unsigned int and long
1164     // on most 32-bit systems).  Use the unsigned type corresponding
1165     // to the signed type.
1166     QualType result =
1167       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1168     RHS = (*doRHSCast)(S, RHS.get(), result);
1169     if (!IsCompAssign)
1170       LHS = (*doLHSCast)(S, LHS.get(), result);
1171     return result;
1172   }
1173 }
1174
1175 /// \brief Handle conversions with GCC complex int extension.  Helper function
1176 /// of UsualArithmeticConversions()
1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1178                                            ExprResult &RHS, QualType LHSType,
1179                                            QualType RHSType,
1180                                            bool IsCompAssign) {
1181   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1182   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1183
1184   if (LHSComplexInt && RHSComplexInt) {
1185     QualType LHSEltType = LHSComplexInt->getElementType();
1186     QualType RHSEltType = RHSComplexInt->getElementType();
1187     QualType ScalarType =
1188       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1189         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1190
1191     return S.Context.getComplexType(ScalarType);
1192   }
1193
1194   if (LHSComplexInt) {
1195     QualType LHSEltType = LHSComplexInt->getElementType();
1196     QualType ScalarType =
1197       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1198         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1199     QualType ComplexType = S.Context.getComplexType(ScalarType);
1200     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1201                               CK_IntegralRealToComplex);
1202  
1203     return ComplexType;
1204   }
1205
1206   assert(RHSComplexInt);
1207
1208   QualType RHSEltType = RHSComplexInt->getElementType();
1209   QualType ScalarType =
1210     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1211       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1212   QualType ComplexType = S.Context.getComplexType(ScalarType);
1213   
1214   if (!IsCompAssign)
1215     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1216                               CK_IntegralRealToComplex);
1217   return ComplexType;
1218 }
1219
1220 /// UsualArithmeticConversions - Performs various conversions that are common to
1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1222 /// routine returns the first non-arithmetic type found. The client is
1223 /// responsible for emitting appropriate error diagnostics.
1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1225                                           bool IsCompAssign) {
1226   if (!IsCompAssign) {
1227     LHS = UsualUnaryConversions(LHS.get());
1228     if (LHS.isInvalid())
1229       return QualType();
1230   }
1231
1232   RHS = UsualUnaryConversions(RHS.get());
1233   if (RHS.isInvalid())
1234     return QualType();
1235
1236   // For conversion purposes, we ignore any qualifiers.
1237   // For example, "const float" and "float" are equivalent.
1238   QualType LHSType =
1239     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1240   QualType RHSType =
1241     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1242
1243   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1244   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1245     LHSType = AtomicLHS->getValueType();
1246
1247   // If both types are identical, no conversion is needed.
1248   if (LHSType == RHSType)
1249     return LHSType;
1250
1251   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1252   // The caller can deal with this (e.g. pointer + int).
1253   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1254     return QualType();
1255
1256   // Apply unary and bitfield promotions to the LHS's type.
1257   QualType LHSUnpromotedType = LHSType;
1258   if (LHSType->isPromotableIntegerType())
1259     LHSType = Context.getPromotedIntegerType(LHSType);
1260   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1261   if (!LHSBitfieldPromoteTy.isNull())
1262     LHSType = LHSBitfieldPromoteTy;
1263   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1264     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1265
1266   // If both types are identical, no conversion is needed.
1267   if (LHSType == RHSType)
1268     return LHSType;
1269
1270   // At this point, we have two different arithmetic types.
1271
1272   // Diagnose attempts to convert between __float128 and long double where
1273   // such conversions currently can't be handled.
1274   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1275     return QualType();
1276
1277   // Handle complex types first (C99 6.3.1.8p1).
1278   if (LHSType->isComplexType() || RHSType->isComplexType())
1279     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1280                                         IsCompAssign);
1281
1282   // Now handle "real" floating types (i.e. float, double, long double).
1283   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1284     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1285                                  IsCompAssign);
1286
1287   // Handle GCC complex int extension.
1288   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1289     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1290                                       IsCompAssign);
1291
1292   // Finally, we have two differing integer types.
1293   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1294            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1295 }
1296
1297
1298 //===----------------------------------------------------------------------===//
1299 //  Semantic Analysis for various Expression Types
1300 //===----------------------------------------------------------------------===//
1301
1302
1303 ExprResult
1304 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1305                                 SourceLocation DefaultLoc,
1306                                 SourceLocation RParenLoc,
1307                                 Expr *ControllingExpr,
1308                                 ArrayRef<ParsedType> ArgTypes,
1309                                 ArrayRef<Expr *> ArgExprs) {
1310   unsigned NumAssocs = ArgTypes.size();
1311   assert(NumAssocs == ArgExprs.size());
1312
1313   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1314   for (unsigned i = 0; i < NumAssocs; ++i) {
1315     if (ArgTypes[i])
1316       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1317     else
1318       Types[i] = nullptr;
1319   }
1320
1321   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1322                                              ControllingExpr,
1323                                              llvm::makeArrayRef(Types, NumAssocs),
1324                                              ArgExprs);
1325   delete [] Types;
1326   return ER;
1327 }
1328
1329 ExprResult
1330 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1331                                  SourceLocation DefaultLoc,
1332                                  SourceLocation RParenLoc,
1333                                  Expr *ControllingExpr,
1334                                  ArrayRef<TypeSourceInfo *> Types,
1335                                  ArrayRef<Expr *> Exprs) {
1336   unsigned NumAssocs = Types.size();
1337   assert(NumAssocs == Exprs.size());
1338
1339   // Decay and strip qualifiers for the controlling expression type, and handle
1340   // placeholder type replacement. See committee discussion from WG14 DR423.
1341   {
1342     EnterExpressionEvaluationContext Unevaluated(
1343         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1344     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1345     if (R.isInvalid())
1346       return ExprError();
1347     ControllingExpr = R.get();
1348   }
1349
1350   // The controlling expression is an unevaluated operand, so side effects are
1351   // likely unintended.
1352   if (!inTemplateInstantiation() &&
1353       ControllingExpr->HasSideEffects(Context, false))
1354     Diag(ControllingExpr->getExprLoc(),
1355          diag::warn_side_effects_unevaluated_context);
1356
1357   bool TypeErrorFound = false,
1358        IsResultDependent = ControllingExpr->isTypeDependent(),
1359        ContainsUnexpandedParameterPack
1360          = ControllingExpr->containsUnexpandedParameterPack();
1361
1362   for (unsigned i = 0; i < NumAssocs; ++i) {
1363     if (Exprs[i]->containsUnexpandedParameterPack())
1364       ContainsUnexpandedParameterPack = true;
1365
1366     if (Types[i]) {
1367       if (Types[i]->getType()->containsUnexpandedParameterPack())
1368         ContainsUnexpandedParameterPack = true;
1369
1370       if (Types[i]->getType()->isDependentType()) {
1371         IsResultDependent = true;
1372       } else {
1373         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1374         // complete object type other than a variably modified type."
1375         unsigned D = 0;
1376         if (Types[i]->getType()->isIncompleteType())
1377           D = diag::err_assoc_type_incomplete;
1378         else if (!Types[i]->getType()->isObjectType())
1379           D = diag::err_assoc_type_nonobject;
1380         else if (Types[i]->getType()->isVariablyModifiedType())
1381           D = diag::err_assoc_type_variably_modified;
1382
1383         if (D != 0) {
1384           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1385             << Types[i]->getTypeLoc().getSourceRange()
1386             << Types[i]->getType();
1387           TypeErrorFound = true;
1388         }
1389
1390         // C11 6.5.1.1p2 "No two generic associations in the same generic
1391         // selection shall specify compatible types."
1392         for (unsigned j = i+1; j < NumAssocs; ++j)
1393           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1394               Context.typesAreCompatible(Types[i]->getType(),
1395                                          Types[j]->getType())) {
1396             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1397                  diag::err_assoc_compatible_types)
1398               << Types[j]->getTypeLoc().getSourceRange()
1399               << Types[j]->getType()
1400               << Types[i]->getType();
1401             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1402                  diag::note_compat_assoc)
1403               << Types[i]->getTypeLoc().getSourceRange()
1404               << Types[i]->getType();
1405             TypeErrorFound = true;
1406           }
1407       }
1408     }
1409   }
1410   if (TypeErrorFound)
1411     return ExprError();
1412
1413   // If we determined that the generic selection is result-dependent, don't
1414   // try to compute the result expression.
1415   if (IsResultDependent)
1416     return new (Context) GenericSelectionExpr(
1417         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1418         ContainsUnexpandedParameterPack);
1419
1420   SmallVector<unsigned, 1> CompatIndices;
1421   unsigned DefaultIndex = -1U;
1422   for (unsigned i = 0; i < NumAssocs; ++i) {
1423     if (!Types[i])
1424       DefaultIndex = i;
1425     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1426                                         Types[i]->getType()))
1427       CompatIndices.push_back(i);
1428   }
1429
1430   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1431   // type compatible with at most one of the types named in its generic
1432   // association list."
1433   if (CompatIndices.size() > 1) {
1434     // We strip parens here because the controlling expression is typically
1435     // parenthesized in macro definitions.
1436     ControllingExpr = ControllingExpr->IgnoreParens();
1437     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1438       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1439       << (unsigned) CompatIndices.size();
1440     for (unsigned I : CompatIndices) {
1441       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1442            diag::note_compat_assoc)
1443         << Types[I]->getTypeLoc().getSourceRange()
1444         << Types[I]->getType();
1445     }
1446     return ExprError();
1447   }
1448
1449   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1450   // its controlling expression shall have type compatible with exactly one of
1451   // the types named in its generic association list."
1452   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1453     // We strip parens here because the controlling expression is typically
1454     // parenthesized in macro definitions.
1455     ControllingExpr = ControllingExpr->IgnoreParens();
1456     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1457       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1458     return ExprError();
1459   }
1460
1461   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1462   // type name that is compatible with the type of the controlling expression,
1463   // then the result expression of the generic selection is the expression
1464   // in that generic association. Otherwise, the result expression of the
1465   // generic selection is the expression in the default generic association."
1466   unsigned ResultIndex =
1467     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1468
1469   return new (Context) GenericSelectionExpr(
1470       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1471       ContainsUnexpandedParameterPack, ResultIndex);
1472 }
1473
1474 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1475 /// location of the token and the offset of the ud-suffix within it.
1476 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1477                                      unsigned Offset) {
1478   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1479                                         S.getLangOpts());
1480 }
1481
1482 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1483 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1484 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1485                                                  IdentifierInfo *UDSuffix,
1486                                                  SourceLocation UDSuffixLoc,
1487                                                  ArrayRef<Expr*> Args,
1488                                                  SourceLocation LitEndLoc) {
1489   assert(Args.size() <= 2 && "too many arguments for literal operator");
1490
1491   QualType ArgTy[2];
1492   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1493     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1494     if (ArgTy[ArgIdx]->isArrayType())
1495       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1496   }
1497
1498   DeclarationName OpName =
1499     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1500   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1501   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1502
1503   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1504   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1505                               /*AllowRaw*/false, /*AllowTemplate*/false,
1506                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1507     return ExprError();
1508
1509   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1510 }
1511
1512 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1513 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1514 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1515 /// multiple tokens.  However, the common case is that StringToks points to one
1516 /// string.
1517 ///
1518 ExprResult
1519 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1520   assert(!StringToks.empty() && "Must have at least one string!");
1521
1522   StringLiteralParser Literal(StringToks, PP);
1523   if (Literal.hadError)
1524     return ExprError();
1525
1526   SmallVector<SourceLocation, 4> StringTokLocs;
1527   for (const Token &Tok : StringToks)
1528     StringTokLocs.push_back(Tok.getLocation());
1529
1530   QualType CharTy = Context.CharTy;
1531   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1532   if (Literal.isWide()) {
1533     CharTy = Context.getWideCharType();
1534     Kind = StringLiteral::Wide;
1535   } else if (Literal.isUTF8()) {
1536     Kind = StringLiteral::UTF8;
1537   } else if (Literal.isUTF16()) {
1538     CharTy = Context.Char16Ty;
1539     Kind = StringLiteral::UTF16;
1540   } else if (Literal.isUTF32()) {
1541     CharTy = Context.Char32Ty;
1542     Kind = StringLiteral::UTF32;
1543   } else if (Literal.isPascal()) {
1544     CharTy = Context.UnsignedCharTy;
1545   }
1546
1547   QualType CharTyConst = CharTy;
1548   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1549   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1550     CharTyConst.addConst();
1551
1552   // Get an array type for the string, according to C99 6.4.5.  This includes
1553   // the nul terminator character as well as the string length for pascal
1554   // strings.
1555   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1556                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1557                                  ArrayType::Normal, 0);
1558
1559   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1560   if (getLangOpts().OpenCL) {
1561     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1562   }
1563
1564   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1565   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1566                                              Kind, Literal.Pascal, StrTy,
1567                                              &StringTokLocs[0],
1568                                              StringTokLocs.size());
1569   if (Literal.getUDSuffix().empty())
1570     return Lit;
1571
1572   // We're building a user-defined literal.
1573   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1574   SourceLocation UDSuffixLoc =
1575     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1576                    Literal.getUDSuffixOffset());
1577
1578   // Make sure we're allowed user-defined literals here.
1579   if (!UDLScope)
1580     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1581
1582   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1583   //   operator "" X (str, len)
1584   QualType SizeType = Context.getSizeType();
1585
1586   DeclarationName OpName =
1587     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1588   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1589   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1590
1591   QualType ArgTy[] = {
1592     Context.getArrayDecayedType(StrTy), SizeType
1593   };
1594
1595   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1596   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1597                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1598                                 /*AllowStringTemplate*/true)) {
1599
1600   case LOLR_Cooked: {
1601     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1602     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1603                                                     StringTokLocs[0]);
1604     Expr *Args[] = { Lit, LenArg };
1605
1606     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1607   }
1608
1609   case LOLR_StringTemplate: {
1610     TemplateArgumentListInfo ExplicitArgs;
1611
1612     unsigned CharBits = Context.getIntWidth(CharTy);
1613     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1614     llvm::APSInt Value(CharBits, CharIsUnsigned);
1615
1616     TemplateArgument TypeArg(CharTy);
1617     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1618     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1619
1620     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1621       Value = Lit->getCodeUnit(I);
1622       TemplateArgument Arg(Context, Value, CharTy);
1623       TemplateArgumentLocInfo ArgInfo;
1624       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1625     }
1626     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1627                                     &ExplicitArgs);
1628   }
1629   case LOLR_Raw:
1630   case LOLR_Template:
1631     llvm_unreachable("unexpected literal operator lookup result");
1632   case LOLR_Error:
1633     return ExprError();
1634   }
1635   llvm_unreachable("unexpected literal operator lookup result");
1636 }
1637
1638 ExprResult
1639 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1640                        SourceLocation Loc,
1641                        const CXXScopeSpec *SS) {
1642   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1643   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1644 }
1645
1646 /// BuildDeclRefExpr - Build an expression that references a
1647 /// declaration that does not require a closure capture.
1648 ExprResult
1649 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1650                        const DeclarationNameInfo &NameInfo,
1651                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1652                        const TemplateArgumentListInfo *TemplateArgs) {
1653   bool RefersToCapturedVariable =
1654       isa<VarDecl>(D) &&
1655       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1656
1657   DeclRefExpr *E;
1658   if (isa<VarTemplateSpecializationDecl>(D)) {
1659     VarTemplateSpecializationDecl *VarSpec =
1660         cast<VarTemplateSpecializationDecl>(D);
1661
1662     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1663                                         : NestedNameSpecifierLoc(),
1664                             VarSpec->getTemplateKeywordLoc(), D,
1665                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1666                             FoundD, TemplateArgs);
1667   } else {
1668     assert(!TemplateArgs && "No template arguments for non-variable"
1669                             " template specialization references");
1670     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1671                                         : NestedNameSpecifierLoc(),
1672                             SourceLocation(), D, RefersToCapturedVariable,
1673                             NameInfo, Ty, VK, FoundD);
1674   }
1675
1676   MarkDeclRefReferenced(E);
1677
1678   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1679       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1680       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1681       recordUseOfEvaluatedWeak(E);
1682
1683   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1684   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1685     FD = IFD->getAnonField();
1686   if (FD) {
1687     UnusedPrivateFields.remove(FD);
1688     // Just in case we're building an illegal pointer-to-member.
1689     if (FD->isBitField())
1690       E->setObjectKind(OK_BitField);
1691   }
1692
1693   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1694   // designates a bit-field.
1695   if (auto *BD = dyn_cast<BindingDecl>(D))
1696     if (auto *BE = BD->getBinding())
1697       E->setObjectKind(BE->getObjectKind());
1698
1699   return E;
1700 }
1701
1702 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1703 /// possibly a list of template arguments.
1704 ///
1705 /// If this produces template arguments, it is permitted to call
1706 /// DecomposeTemplateName.
1707 ///
1708 /// This actually loses a lot of source location information for
1709 /// non-standard name kinds; we should consider preserving that in
1710 /// some way.
1711 void
1712 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1713                              TemplateArgumentListInfo &Buffer,
1714                              DeclarationNameInfo &NameInfo,
1715                              const TemplateArgumentListInfo *&TemplateArgs) {
1716   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1717     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1718     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1719
1720     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1721                                        Id.TemplateId->NumArgs);
1722     translateTemplateArguments(TemplateArgsPtr, Buffer);
1723
1724     TemplateName TName = Id.TemplateId->Template.get();
1725     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1726     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1727     TemplateArgs = &Buffer;
1728   } else {
1729     NameInfo = GetNameFromUnqualifiedId(Id);
1730     TemplateArgs = nullptr;
1731   }
1732 }
1733
1734 static void emitEmptyLookupTypoDiagnostic(
1735     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1736     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1737     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1738   DeclContext *Ctx =
1739       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1740   if (!TC) {
1741     // Emit a special diagnostic for failed member lookups.
1742     // FIXME: computing the declaration context might fail here (?)
1743     if (Ctx)
1744       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1745                                                  << SS.getRange();
1746     else
1747       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1748     return;
1749   }
1750
1751   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1752   bool DroppedSpecifier =
1753       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1754   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1755                         ? diag::note_implicit_param_decl
1756                         : diag::note_previous_decl;
1757   if (!Ctx)
1758     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1759                          SemaRef.PDiag(NoteID));
1760   else
1761     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1762                                  << Typo << Ctx << DroppedSpecifier
1763                                  << SS.getRange(),
1764                          SemaRef.PDiag(NoteID));
1765 }
1766
1767 /// Diagnose an empty lookup.
1768 ///
1769 /// \return false if new lookup candidates were found
1770 bool
1771 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1772                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1773                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1774                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1775   DeclarationName Name = R.getLookupName();
1776
1777   unsigned diagnostic = diag::err_undeclared_var_use;
1778   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1779   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1780       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1781       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1782     diagnostic = diag::err_undeclared_use;
1783     diagnostic_suggest = diag::err_undeclared_use_suggest;
1784   }
1785
1786   // If the original lookup was an unqualified lookup, fake an
1787   // unqualified lookup.  This is useful when (for example) the
1788   // original lookup would not have found something because it was a
1789   // dependent name.
1790   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1791   while (DC) {
1792     if (isa<CXXRecordDecl>(DC)) {
1793       LookupQualifiedName(R, DC);
1794
1795       if (!R.empty()) {
1796         // Don't give errors about ambiguities in this lookup.
1797         R.suppressDiagnostics();
1798
1799         // During a default argument instantiation the CurContext points
1800         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1801         // function parameter list, hence add an explicit check.
1802         bool isDefaultArgument =
1803             !CodeSynthesisContexts.empty() &&
1804             CodeSynthesisContexts.back().Kind ==
1805                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1806         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1807         bool isInstance = CurMethod &&
1808                           CurMethod->isInstance() &&
1809                           DC == CurMethod->getParent() && !isDefaultArgument;
1810
1811         // Give a code modification hint to insert 'this->'.
1812         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1813         // Actually quite difficult!
1814         if (getLangOpts().MSVCCompat)
1815           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1816         if (isInstance) {
1817           Diag(R.getNameLoc(), diagnostic) << Name
1818             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1819           CheckCXXThisCapture(R.getNameLoc());
1820         } else {
1821           Diag(R.getNameLoc(), diagnostic) << Name;
1822         }
1823
1824         // Do we really want to note all of these?
1825         for (NamedDecl *D : R)
1826           Diag(D->getLocation(), diag::note_dependent_var_use);
1827
1828         // Return true if we are inside a default argument instantiation
1829         // and the found name refers to an instance member function, otherwise
1830         // the function calling DiagnoseEmptyLookup will try to create an
1831         // implicit member call and this is wrong for default argument.
1832         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1833           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1834           return true;
1835         }
1836
1837         // Tell the callee to try to recover.
1838         return false;
1839       }
1840
1841       R.clear();
1842     }
1843
1844     // In Microsoft mode, if we are performing lookup from within a friend
1845     // function definition declared at class scope then we must set
1846     // DC to the lexical parent to be able to search into the parent
1847     // class.
1848     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1849         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1850         DC->getLexicalParent()->isRecord())
1851       DC = DC->getLexicalParent();
1852     else
1853       DC = DC->getParent();
1854   }
1855
1856   // We didn't find anything, so try to correct for a typo.
1857   TypoCorrection Corrected;
1858   if (S && Out) {
1859     SourceLocation TypoLoc = R.getNameLoc();
1860     assert(!ExplicitTemplateArgs &&
1861            "Diagnosing an empty lookup with explicit template args!");
1862     *Out = CorrectTypoDelayed(
1863         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1864         [=](const TypoCorrection &TC) {
1865           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1866                                         diagnostic, diagnostic_suggest);
1867         },
1868         nullptr, CTK_ErrorRecovery);
1869     if (*Out)
1870       return true;
1871   } else if (S && (Corrected =
1872                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1873                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1874     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1875     bool DroppedSpecifier =
1876         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1877     R.setLookupName(Corrected.getCorrection());
1878
1879     bool AcceptableWithRecovery = false;
1880     bool AcceptableWithoutRecovery = false;
1881     NamedDecl *ND = Corrected.getFoundDecl();
1882     if (ND) {
1883       if (Corrected.isOverloaded()) {
1884         OverloadCandidateSet OCS(R.getNameLoc(),
1885                                  OverloadCandidateSet::CSK_Normal);
1886         OverloadCandidateSet::iterator Best;
1887         for (NamedDecl *CD : Corrected) {
1888           if (FunctionTemplateDecl *FTD =
1889                    dyn_cast<FunctionTemplateDecl>(CD))
1890             AddTemplateOverloadCandidate(
1891                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1892                 Args, OCS);
1893           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1894             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1895               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1896                                    Args, OCS);
1897         }
1898         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1899         case OR_Success:
1900           ND = Best->FoundDecl;
1901           Corrected.setCorrectionDecl(ND);
1902           break;
1903         default:
1904           // FIXME: Arbitrarily pick the first declaration for the note.
1905           Corrected.setCorrectionDecl(ND);
1906           break;
1907         }
1908       }
1909       R.addDecl(ND);
1910       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1911         CXXRecordDecl *Record = nullptr;
1912         if (Corrected.getCorrectionSpecifier()) {
1913           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1914           Record = Ty->getAsCXXRecordDecl();
1915         }
1916         if (!Record)
1917           Record = cast<CXXRecordDecl>(
1918               ND->getDeclContext()->getRedeclContext());
1919         R.setNamingClass(Record);
1920       }
1921
1922       auto *UnderlyingND = ND->getUnderlyingDecl();
1923       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1924                                isa<FunctionTemplateDecl>(UnderlyingND);
1925       // FIXME: If we ended up with a typo for a type name or
1926       // Objective-C class name, we're in trouble because the parser
1927       // is in the wrong place to recover. Suggest the typo
1928       // correction, but don't make it a fix-it since we're not going
1929       // to recover well anyway.
1930       AcceptableWithoutRecovery =
1931           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1932     } else {
1933       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1934       // because we aren't able to recover.
1935       AcceptableWithoutRecovery = true;
1936     }
1937
1938     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1939       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1940                             ? diag::note_implicit_param_decl
1941                             : diag::note_previous_decl;
1942       if (SS.isEmpty())
1943         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1944                      PDiag(NoteID), AcceptableWithRecovery);
1945       else
1946         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1947                                   << Name << computeDeclContext(SS, false)
1948                                   << DroppedSpecifier << SS.getRange(),
1949                      PDiag(NoteID), AcceptableWithRecovery);
1950
1951       // Tell the callee whether to try to recover.
1952       return !AcceptableWithRecovery;
1953     }
1954   }
1955   R.clear();
1956
1957   // Emit a special diagnostic for failed member lookups.
1958   // FIXME: computing the declaration context might fail here (?)
1959   if (!SS.isEmpty()) {
1960     Diag(R.getNameLoc(), diag::err_no_member)
1961       << Name << computeDeclContext(SS, false)
1962       << SS.getRange();
1963     return true;
1964   }
1965
1966   // Give up, we can't recover.
1967   Diag(R.getNameLoc(), diagnostic) << Name;
1968   return true;
1969 }
1970
1971 /// In Microsoft mode, if we are inside a template class whose parent class has
1972 /// dependent base classes, and we can't resolve an unqualified identifier, then
1973 /// assume the identifier is a member of a dependent base class.  We can only
1974 /// recover successfully in static methods, instance methods, and other contexts
1975 /// where 'this' is available.  This doesn't precisely match MSVC's
1976 /// instantiation model, but it's close enough.
1977 static Expr *
1978 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1979                                DeclarationNameInfo &NameInfo,
1980                                SourceLocation TemplateKWLoc,
1981                                const TemplateArgumentListInfo *TemplateArgs) {
1982   // Only try to recover from lookup into dependent bases in static methods or
1983   // contexts where 'this' is available.
1984   QualType ThisType = S.getCurrentThisType();
1985   const CXXRecordDecl *RD = nullptr;
1986   if (!ThisType.isNull())
1987     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1988   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1989     RD = MD->getParent();
1990   if (!RD || !RD->hasAnyDependentBases())
1991     return nullptr;
1992
1993   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1994   // is available, suggest inserting 'this->' as a fixit.
1995   SourceLocation Loc = NameInfo.getLoc();
1996   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1997   DB << NameInfo.getName() << RD;
1998
1999   if (!ThisType.isNull()) {
2000     DB << FixItHint::CreateInsertion(Loc, "this->");
2001     return CXXDependentScopeMemberExpr::Create(
2002         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2003         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2004         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2005   }
2006
2007   // Synthesize a fake NNS that points to the derived class.  This will
2008   // perform name lookup during template instantiation.
2009   CXXScopeSpec SS;
2010   auto *NNS =
2011       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2012   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2013   return DependentScopeDeclRefExpr::Create(
2014       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2015       TemplateArgs);
2016 }
2017
2018 ExprResult
2019 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2020                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2021                         bool HasTrailingLParen, bool IsAddressOfOperand,
2022                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2023                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2024   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2025          "cannot be direct & operand and have a trailing lparen");
2026   if (SS.isInvalid())
2027     return ExprError();
2028
2029   TemplateArgumentListInfo TemplateArgsBuffer;
2030
2031   // Decompose the UnqualifiedId into the following data.
2032   DeclarationNameInfo NameInfo;
2033   const TemplateArgumentListInfo *TemplateArgs;
2034   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2035
2036   DeclarationName Name = NameInfo.getName();
2037   IdentifierInfo *II = Name.getAsIdentifierInfo();
2038   SourceLocation NameLoc = NameInfo.getLoc();
2039
2040   if (II && II->isEditorPlaceholder()) {
2041     // FIXME: When typed placeholders are supported we can create a typed
2042     // placeholder expression node.
2043     return ExprError();
2044   }
2045
2046   // C++ [temp.dep.expr]p3:
2047   //   An id-expression is type-dependent if it contains:
2048   //     -- an identifier that was declared with a dependent type,
2049   //        (note: handled after lookup)
2050   //     -- a template-id that is dependent,
2051   //        (note: handled in BuildTemplateIdExpr)
2052   //     -- a conversion-function-id that specifies a dependent type,
2053   //     -- a nested-name-specifier that contains a class-name that
2054   //        names a dependent type.
2055   // Determine whether this is a member of an unknown specialization;
2056   // we need to handle these differently.
2057   bool DependentID = false;
2058   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2059       Name.getCXXNameType()->isDependentType()) {
2060     DependentID = true;
2061   } else if (SS.isSet()) {
2062     if (DeclContext *DC = computeDeclContext(SS, false)) {
2063       if (RequireCompleteDeclContext(SS, DC))
2064         return ExprError();
2065     } else {
2066       DependentID = true;
2067     }
2068   }
2069
2070   if (DependentID)
2071     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2072                                       IsAddressOfOperand, TemplateArgs);
2073
2074   // Perform the required lookup.
2075   LookupResult R(*this, NameInfo, 
2076                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
2077                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2078   if (TemplateArgs) {
2079     // Lookup the template name again to correctly establish the context in
2080     // which it was found. This is really unfortunate as we already did the
2081     // lookup to determine that it was a template name in the first place. If
2082     // this becomes a performance hit, we can work harder to preserve those
2083     // results until we get here but it's likely not worth it.
2084     bool MemberOfUnknownSpecialization;
2085     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2086                        MemberOfUnknownSpecialization);
2087     
2088     if (MemberOfUnknownSpecialization ||
2089         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2090       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2091                                         IsAddressOfOperand, TemplateArgs);
2092   } else {
2093     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2094     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2095
2096     // If the result might be in a dependent base class, this is a dependent 
2097     // id-expression.
2098     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2099       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2100                                         IsAddressOfOperand, TemplateArgs);
2101
2102     // If this reference is in an Objective-C method, then we need to do
2103     // some special Objective-C lookup, too.
2104     if (IvarLookupFollowUp) {
2105       ExprResult E(LookupInObjCMethod(R, S, II, true));
2106       if (E.isInvalid())
2107         return ExprError();
2108
2109       if (Expr *Ex = E.getAs<Expr>())
2110         return Ex;
2111     }
2112   }
2113
2114   if (R.isAmbiguous())
2115     return ExprError();
2116
2117   // This could be an implicitly declared function reference (legal in C90,
2118   // extension in C99, forbidden in C++).
2119   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2120     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2121     if (D) R.addDecl(D);
2122   }
2123
2124   // Determine whether this name might be a candidate for
2125   // argument-dependent lookup.
2126   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2127
2128   if (R.empty() && !ADL) {
2129     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2130       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2131                                                    TemplateKWLoc, TemplateArgs))
2132         return E;
2133     }
2134
2135     // Don't diagnose an empty lookup for inline assembly.
2136     if (IsInlineAsmIdentifier)
2137       return ExprError();
2138
2139     // If this name wasn't predeclared and if this is not a function
2140     // call, diagnose the problem.
2141     TypoExpr *TE = nullptr;
2142     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2143         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2144     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2145     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2146            "Typo correction callback misconfigured");
2147     if (CCC) {
2148       // Make sure the callback knows what the typo being diagnosed is.
2149       CCC->setTypoName(II);
2150       if (SS.isValid())
2151         CCC->setTypoNNS(SS.getScopeRep());
2152     }
2153     if (DiagnoseEmptyLookup(S, SS, R,
2154                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2155                             nullptr, None, &TE)) {
2156       if (TE && KeywordReplacement) {
2157         auto &State = getTypoExprState(TE);
2158         auto BestTC = State.Consumer->getNextCorrection();
2159         if (BestTC.isKeyword()) {
2160           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2161           if (State.DiagHandler)
2162             State.DiagHandler(BestTC);
2163           KeywordReplacement->startToken();
2164           KeywordReplacement->setKind(II->getTokenID());
2165           KeywordReplacement->setIdentifierInfo(II);
2166           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2167           // Clean up the state associated with the TypoExpr, since it has
2168           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2169           clearDelayedTypo(TE);
2170           // Signal that a correction to a keyword was performed by returning a
2171           // valid-but-null ExprResult.
2172           return (Expr*)nullptr;
2173         }
2174         State.Consumer->resetCorrectionStream();
2175       }
2176       return TE ? TE : ExprError();
2177     }
2178
2179     assert(!R.empty() &&
2180            "DiagnoseEmptyLookup returned false but added no results");
2181
2182     // If we found an Objective-C instance variable, let
2183     // LookupInObjCMethod build the appropriate expression to
2184     // reference the ivar.
2185     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2186       R.clear();
2187       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2188       // In a hopelessly buggy code, Objective-C instance variable
2189       // lookup fails and no expression will be built to reference it.
2190       if (!E.isInvalid() && !E.get())
2191         return ExprError();
2192       return E;
2193     }
2194   }
2195
2196   // This is guaranteed from this point on.
2197   assert(!R.empty() || ADL);
2198
2199   // Check whether this might be a C++ implicit instance member access.
2200   // C++ [class.mfct.non-static]p3:
2201   //   When an id-expression that is not part of a class member access
2202   //   syntax and not used to form a pointer to member is used in the
2203   //   body of a non-static member function of class X, if name lookup
2204   //   resolves the name in the id-expression to a non-static non-type
2205   //   member of some class C, the id-expression is transformed into a
2206   //   class member access expression using (*this) as the
2207   //   postfix-expression to the left of the . operator.
2208   //
2209   // But we don't actually need to do this for '&' operands if R
2210   // resolved to a function or overloaded function set, because the
2211   // expression is ill-formed if it actually works out to be a
2212   // non-static member function:
2213   //
2214   // C++ [expr.ref]p4:
2215   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2216   //   [t]he expression can be used only as the left-hand operand of a
2217   //   member function call.
2218   //
2219   // There are other safeguards against such uses, but it's important
2220   // to get this right here so that we don't end up making a
2221   // spuriously dependent expression if we're inside a dependent
2222   // instance method.
2223   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2224     bool MightBeImplicitMember;
2225     if (!IsAddressOfOperand)
2226       MightBeImplicitMember = true;
2227     else if (!SS.isEmpty())
2228       MightBeImplicitMember = false;
2229     else if (R.isOverloadedResult())
2230       MightBeImplicitMember = false;
2231     else if (R.isUnresolvableResult())
2232       MightBeImplicitMember = true;
2233     else
2234       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2235                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2236                               isa<MSPropertyDecl>(R.getFoundDecl());
2237
2238     if (MightBeImplicitMember)
2239       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2240                                              R, TemplateArgs, S);
2241   }
2242
2243   if (TemplateArgs || TemplateKWLoc.isValid()) {
2244
2245     // In C++1y, if this is a variable template id, then check it
2246     // in BuildTemplateIdExpr().
2247     // The single lookup result must be a variable template declaration.
2248     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2249         Id.TemplateId->Kind == TNK_Var_template) {
2250       assert(R.getAsSingle<VarTemplateDecl>() &&
2251              "There should only be one declaration found.");
2252     }
2253
2254     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2255   }
2256
2257   return BuildDeclarationNameExpr(SS, R, ADL);
2258 }
2259
2260 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2261 /// declaration name, generally during template instantiation.
2262 /// There's a large number of things which don't need to be done along
2263 /// this path.
2264 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2265     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2266     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2267   DeclContext *DC = computeDeclContext(SS, false);
2268   if (!DC)
2269     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2270                                      NameInfo, /*TemplateArgs=*/nullptr);
2271
2272   if (RequireCompleteDeclContext(SS, DC))
2273     return ExprError();
2274
2275   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2276   LookupQualifiedName(R, DC);
2277
2278   if (R.isAmbiguous())
2279     return ExprError();
2280
2281   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2282     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2283                                      NameInfo, /*TemplateArgs=*/nullptr);
2284
2285   if (R.empty()) {
2286     Diag(NameInfo.getLoc(), diag::err_no_member)
2287       << NameInfo.getName() << DC << SS.getRange();
2288     return ExprError();
2289   }
2290
2291   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2292     // Diagnose a missing typename if this resolved unambiguously to a type in
2293     // a dependent context.  If we can recover with a type, downgrade this to
2294     // a warning in Microsoft compatibility mode.
2295     unsigned DiagID = diag::err_typename_missing;
2296     if (RecoveryTSI && getLangOpts().MSVCCompat)
2297       DiagID = diag::ext_typename_missing;
2298     SourceLocation Loc = SS.getBeginLoc();
2299     auto D = Diag(Loc, DiagID);
2300     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2301       << SourceRange(Loc, NameInfo.getEndLoc());
2302
2303     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2304     // context.
2305     if (!RecoveryTSI)
2306       return ExprError();
2307
2308     // Only issue the fixit if we're prepared to recover.
2309     D << FixItHint::CreateInsertion(Loc, "typename ");
2310
2311     // Recover by pretending this was an elaborated type.
2312     QualType Ty = Context.getTypeDeclType(TD);
2313     TypeLocBuilder TLB;
2314     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2315
2316     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2317     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2318     QTL.setElaboratedKeywordLoc(SourceLocation());
2319     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2320
2321     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2322
2323     return ExprEmpty();
2324   }
2325
2326   // Defend against this resolving to an implicit member access. We usually
2327   // won't get here if this might be a legitimate a class member (we end up in
2328   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2329   // a pointer-to-member or in an unevaluated context in C++11.
2330   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2331     return BuildPossibleImplicitMemberExpr(SS,
2332                                            /*TemplateKWLoc=*/SourceLocation(),
2333                                            R, /*TemplateArgs=*/nullptr, S);
2334
2335   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2336 }
2337
2338 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2339 /// detected that we're currently inside an ObjC method.  Perform some
2340 /// additional lookup.
2341 ///
2342 /// Ideally, most of this would be done by lookup, but there's
2343 /// actually quite a lot of extra work involved.
2344 ///
2345 /// Returns a null sentinel to indicate trivial success.
2346 ExprResult
2347 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2348                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2349   SourceLocation Loc = Lookup.getNameLoc();
2350   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2351   
2352   // Check for error condition which is already reported.
2353   if (!CurMethod)
2354     return ExprError();
2355
2356   // There are two cases to handle here.  1) scoped lookup could have failed,
2357   // in which case we should look for an ivar.  2) scoped lookup could have
2358   // found a decl, but that decl is outside the current instance method (i.e.
2359   // a global variable).  In these two cases, we do a lookup for an ivar with
2360   // this name, if the lookup sucedes, we replace it our current decl.
2361
2362   // If we're in a class method, we don't normally want to look for
2363   // ivars.  But if we don't find anything else, and there's an
2364   // ivar, that's an error.
2365   bool IsClassMethod = CurMethod->isClassMethod();
2366
2367   bool LookForIvars;
2368   if (Lookup.empty())
2369     LookForIvars = true;
2370   else if (IsClassMethod)
2371     LookForIvars = false;
2372   else
2373     LookForIvars = (Lookup.isSingleResult() &&
2374                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2375   ObjCInterfaceDecl *IFace = nullptr;
2376   if (LookForIvars) {
2377     IFace = CurMethod->getClassInterface();
2378     ObjCInterfaceDecl *ClassDeclared;
2379     ObjCIvarDecl *IV = nullptr;
2380     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2381       // Diagnose using an ivar in a class method.
2382       if (IsClassMethod)
2383         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2384                          << IV->getDeclName());
2385
2386       // If we're referencing an invalid decl, just return this as a silent
2387       // error node.  The error diagnostic was already emitted on the decl.
2388       if (IV->isInvalidDecl())
2389         return ExprError();
2390
2391       // Check if referencing a field with __attribute__((deprecated)).
2392       if (DiagnoseUseOfDecl(IV, Loc))
2393         return ExprError();
2394
2395       // Diagnose the use of an ivar outside of the declaring class.
2396       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2397           !declaresSameEntity(ClassDeclared, IFace) &&
2398           !getLangOpts().DebuggerSupport)
2399         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2400
2401       // FIXME: This should use a new expr for a direct reference, don't
2402       // turn this into Self->ivar, just return a BareIVarExpr or something.
2403       IdentifierInfo &II = Context.Idents.get("self");
2404       UnqualifiedId SelfName;
2405       SelfName.setIdentifier(&II, SourceLocation());
2406       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2407       CXXScopeSpec SelfScopeSpec;
2408       SourceLocation TemplateKWLoc;
2409       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2410                                               SelfName, false, false);
2411       if (SelfExpr.isInvalid())
2412         return ExprError();
2413
2414       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2415       if (SelfExpr.isInvalid())
2416         return ExprError();
2417
2418       MarkAnyDeclReferenced(Loc, IV, true);
2419
2420       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2421       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2422           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2423         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2424
2425       ObjCIvarRefExpr *Result = new (Context)
2426           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2427                           IV->getLocation(), SelfExpr.get(), true, true);
2428
2429       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2430         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2431           recordUseOfEvaluatedWeak(Result);
2432       }
2433       if (getLangOpts().ObjCAutoRefCount) {
2434         if (CurContext->isClosure())
2435           Diag(Loc, diag::warn_implicitly_retains_self)
2436             << FixItHint::CreateInsertion(Loc, "self->");
2437       }
2438       
2439       return Result;
2440     }
2441   } else if (CurMethod->isInstanceMethod()) {
2442     // We should warn if a local variable hides an ivar.
2443     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2444       ObjCInterfaceDecl *ClassDeclared;
2445       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2446         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2447             declaresSameEntity(IFace, ClassDeclared))
2448           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2449       }
2450     }
2451   } else if (Lookup.isSingleResult() &&
2452              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2453     // If accessing a stand-alone ivar in a class method, this is an error.
2454     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2455       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2456                        << IV->getDeclName());
2457   }
2458
2459   if (Lookup.empty() && II && AllowBuiltinCreation) {
2460     // FIXME. Consolidate this with similar code in LookupName.
2461     if (unsigned BuiltinID = II->getBuiltinID()) {
2462       if (!(getLangOpts().CPlusPlus &&
2463             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2464         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2465                                            S, Lookup.isForRedeclaration(),
2466                                            Lookup.getNameLoc());
2467         if (D) Lookup.addDecl(D);
2468       }
2469     }
2470   }
2471   // Sentinel value saying that we didn't do anything special.
2472   return ExprResult((Expr *)nullptr);
2473 }
2474
2475 /// \brief Cast a base object to a member's actual type.
2476 ///
2477 /// Logically this happens in three phases:
2478 ///
2479 /// * First we cast from the base type to the naming class.
2480 ///   The naming class is the class into which we were looking
2481 ///   when we found the member;  it's the qualifier type if a
2482 ///   qualifier was provided, and otherwise it's the base type.
2483 ///
2484 /// * Next we cast from the naming class to the declaring class.
2485 ///   If the member we found was brought into a class's scope by
2486 ///   a using declaration, this is that class;  otherwise it's
2487 ///   the class declaring the member.
2488 ///
2489 /// * Finally we cast from the declaring class to the "true"
2490 ///   declaring class of the member.  This conversion does not
2491 ///   obey access control.
2492 ExprResult
2493 Sema::PerformObjectMemberConversion(Expr *From,
2494                                     NestedNameSpecifier *Qualifier,
2495                                     NamedDecl *FoundDecl,
2496                                     NamedDecl *Member) {
2497   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2498   if (!RD)
2499     return From;
2500
2501   QualType DestRecordType;
2502   QualType DestType;
2503   QualType FromRecordType;
2504   QualType FromType = From->getType();
2505   bool PointerConversions = false;
2506   if (isa<FieldDecl>(Member)) {
2507     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2508
2509     if (FromType->getAs<PointerType>()) {
2510       DestType = Context.getPointerType(DestRecordType);
2511       FromRecordType = FromType->getPointeeType();
2512       PointerConversions = true;
2513     } else {
2514       DestType = DestRecordType;
2515       FromRecordType = FromType;
2516     }
2517   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2518     if (Method->isStatic())
2519       return From;
2520
2521     DestType = Method->getThisType(Context);
2522     DestRecordType = DestType->getPointeeType();
2523
2524     if (FromType->getAs<PointerType>()) {
2525       FromRecordType = FromType->getPointeeType();
2526       PointerConversions = true;
2527     } else {
2528       FromRecordType = FromType;
2529       DestType = DestRecordType;
2530     }
2531   } else {
2532     // No conversion necessary.
2533     return From;
2534   }
2535
2536   if (DestType->isDependentType() || FromType->isDependentType())
2537     return From;
2538
2539   // If the unqualified types are the same, no conversion is necessary.
2540   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2541     return From;
2542
2543   SourceRange FromRange = From->getSourceRange();
2544   SourceLocation FromLoc = FromRange.getBegin();
2545
2546   ExprValueKind VK = From->getValueKind();
2547
2548   // C++ [class.member.lookup]p8:
2549   //   [...] Ambiguities can often be resolved by qualifying a name with its
2550   //   class name.
2551   //
2552   // If the member was a qualified name and the qualified referred to a
2553   // specific base subobject type, we'll cast to that intermediate type
2554   // first and then to the object in which the member is declared. That allows
2555   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2556   //
2557   //   class Base { public: int x; };
2558   //   class Derived1 : public Base { };
2559   //   class Derived2 : public Base { };
2560   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2561   //
2562   //   void VeryDerived::f() {
2563   //     x = 17; // error: ambiguous base subobjects
2564   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2565   //   }
2566   if (Qualifier && Qualifier->getAsType()) {
2567     QualType QType = QualType(Qualifier->getAsType(), 0);
2568     assert(QType->isRecordType() && "lookup done with non-record type");
2569
2570     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2571
2572     // In C++98, the qualifier type doesn't actually have to be a base
2573     // type of the object type, in which case we just ignore it.
2574     // Otherwise build the appropriate casts.
2575     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2576       CXXCastPath BasePath;
2577       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2578                                        FromLoc, FromRange, &BasePath))
2579         return ExprError();
2580
2581       if (PointerConversions)
2582         QType = Context.getPointerType(QType);
2583       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2584                                VK, &BasePath).get();
2585
2586       FromType = QType;
2587       FromRecordType = QRecordType;
2588
2589       // If the qualifier type was the same as the destination type,
2590       // we're done.
2591       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2592         return From;
2593     }
2594   }
2595
2596   bool IgnoreAccess = false;
2597
2598   // If we actually found the member through a using declaration, cast
2599   // down to the using declaration's type.
2600   //
2601   // Pointer equality is fine here because only one declaration of a
2602   // class ever has member declarations.
2603   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2604     assert(isa<UsingShadowDecl>(FoundDecl));
2605     QualType URecordType = Context.getTypeDeclType(
2606                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2607
2608     // We only need to do this if the naming-class to declaring-class
2609     // conversion is non-trivial.
2610     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2611       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2612       CXXCastPath BasePath;
2613       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2614                                        FromLoc, FromRange, &BasePath))
2615         return ExprError();
2616
2617       QualType UType = URecordType;
2618       if (PointerConversions)
2619         UType = Context.getPointerType(UType);
2620       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2621                                VK, &BasePath).get();
2622       FromType = UType;
2623       FromRecordType = URecordType;
2624     }
2625
2626     // We don't do access control for the conversion from the
2627     // declaring class to the true declaring class.
2628     IgnoreAccess = true;
2629   }
2630
2631   CXXCastPath BasePath;
2632   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2633                                    FromLoc, FromRange, &BasePath,
2634                                    IgnoreAccess))
2635     return ExprError();
2636
2637   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2638                            VK, &BasePath);
2639 }
2640
2641 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2642                                       const LookupResult &R,
2643                                       bool HasTrailingLParen) {
2644   // Only when used directly as the postfix-expression of a call.
2645   if (!HasTrailingLParen)
2646     return false;
2647
2648   // Never if a scope specifier was provided.
2649   if (SS.isSet())
2650     return false;
2651
2652   // Only in C++ or ObjC++.
2653   if (!getLangOpts().CPlusPlus)
2654     return false;
2655
2656   // Turn off ADL when we find certain kinds of declarations during
2657   // normal lookup:
2658   for (NamedDecl *D : R) {
2659     // C++0x [basic.lookup.argdep]p3:
2660     //     -- a declaration of a class member
2661     // Since using decls preserve this property, we check this on the
2662     // original decl.
2663     if (D->isCXXClassMember())
2664       return false;
2665
2666     // C++0x [basic.lookup.argdep]p3:
2667     //     -- a block-scope function declaration that is not a
2668     //        using-declaration
2669     // NOTE: we also trigger this for function templates (in fact, we
2670     // don't check the decl type at all, since all other decl types
2671     // turn off ADL anyway).
2672     if (isa<UsingShadowDecl>(D))
2673       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2674     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2675       return false;
2676
2677     // C++0x [basic.lookup.argdep]p3:
2678     //     -- a declaration that is neither a function or a function
2679     //        template
2680     // And also for builtin functions.
2681     if (isa<FunctionDecl>(D)) {
2682       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2683
2684       // But also builtin functions.
2685       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2686         return false;
2687     } else if (!isa<FunctionTemplateDecl>(D))
2688       return false;
2689   }
2690
2691   return true;
2692 }
2693
2694
2695 /// Diagnoses obvious problems with the use of the given declaration
2696 /// as an expression.  This is only actually called for lookups that
2697 /// were not overloaded, and it doesn't promise that the declaration
2698 /// will in fact be used.
2699 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2700   if (D->isInvalidDecl())
2701     return true;
2702
2703   if (isa<TypedefNameDecl>(D)) {
2704     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2705     return true;
2706   }
2707
2708   if (isa<ObjCInterfaceDecl>(D)) {
2709     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2710     return true;
2711   }
2712
2713   if (isa<NamespaceDecl>(D)) {
2714     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2715     return true;
2716   }
2717
2718   return false;
2719 }
2720
2721 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2722                                           LookupResult &R, bool NeedsADL,
2723                                           bool AcceptInvalidDecl) {
2724   // If this is a single, fully-resolved result and we don't need ADL,
2725   // just build an ordinary singleton decl ref.
2726   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2727     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2728                                     R.getRepresentativeDecl(), nullptr,
2729                                     AcceptInvalidDecl);
2730
2731   // We only need to check the declaration if there's exactly one
2732   // result, because in the overloaded case the results can only be
2733   // functions and function templates.
2734   if (R.isSingleResult() &&
2735       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2736     return ExprError();
2737
2738   // Otherwise, just build an unresolved lookup expression.  Suppress
2739   // any lookup-related diagnostics; we'll hash these out later, when
2740   // we've picked a target.
2741   R.suppressDiagnostics();
2742
2743   UnresolvedLookupExpr *ULE
2744     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2745                                    SS.getWithLocInContext(Context),
2746                                    R.getLookupNameInfo(),
2747                                    NeedsADL, R.isOverloadedResult(),
2748                                    R.begin(), R.end());
2749
2750   return ULE;
2751 }
2752
2753 static void
2754 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2755                                    ValueDecl *var, DeclContext *DC);
2756
2757 /// \brief Complete semantic analysis for a reference to the given declaration.
2758 ExprResult Sema::BuildDeclarationNameExpr(
2759     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2760     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2761     bool AcceptInvalidDecl) {
2762   assert(D && "Cannot refer to a NULL declaration");
2763   assert(!isa<FunctionTemplateDecl>(D) &&
2764          "Cannot refer unambiguously to a function template");
2765
2766   SourceLocation Loc = NameInfo.getLoc();
2767   if (CheckDeclInExpr(*this, Loc, D))
2768     return ExprError();
2769
2770   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2771     // Specifically diagnose references to class templates that are missing
2772     // a template argument list.
2773     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2774                                            << Template << SS.getRange();
2775     Diag(Template->getLocation(), diag::note_template_decl_here);
2776     return ExprError();
2777   }
2778
2779   // Make sure that we're referring to a value.
2780   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2781   if (!VD) {
2782     Diag(Loc, diag::err_ref_non_value)
2783       << D << SS.getRange();
2784     Diag(D->getLocation(), diag::note_declared_at);
2785     return ExprError();
2786   }
2787
2788   // Check whether this declaration can be used. Note that we suppress
2789   // this check when we're going to perform argument-dependent lookup
2790   // on this function name, because this might not be the function
2791   // that overload resolution actually selects.
2792   if (DiagnoseUseOfDecl(VD, Loc))
2793     return ExprError();
2794
2795   // Only create DeclRefExpr's for valid Decl's.
2796   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2797     return ExprError();
2798
2799   // Handle members of anonymous structs and unions.  If we got here,
2800   // and the reference is to a class member indirect field, then this
2801   // must be the subject of a pointer-to-member expression.
2802   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2803     if (!indirectField->isCXXClassMember())
2804       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2805                                                       indirectField);
2806
2807   {
2808     QualType type = VD->getType();
2809     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2810       // C++ [except.spec]p17:
2811       //   An exception-specification is considered to be needed when:
2812       //   - in an expression, the function is the unique lookup result or
2813       //     the selected member of a set of overloaded functions.
2814       ResolveExceptionSpec(Loc, FPT);
2815       type = VD->getType();
2816     }
2817     ExprValueKind valueKind = VK_RValue;
2818
2819     switch (D->getKind()) {
2820     // Ignore all the non-ValueDecl kinds.
2821 #define ABSTRACT_DECL(kind)
2822 #define VALUE(type, base)
2823 #define DECL(type, base) \
2824     case Decl::type:
2825 #include "clang/AST/DeclNodes.inc"
2826       llvm_unreachable("invalid value decl kind");
2827
2828     // These shouldn't make it here.
2829     case Decl::ObjCAtDefsField:
2830     case Decl::ObjCIvar:
2831       llvm_unreachable("forming non-member reference to ivar?");
2832
2833     // Enum constants are always r-values and never references.
2834     // Unresolved using declarations are dependent.
2835     case Decl::EnumConstant:
2836     case Decl::UnresolvedUsingValue:
2837     case Decl::OMPDeclareReduction:
2838       valueKind = VK_RValue;
2839       break;
2840
2841     // Fields and indirect fields that got here must be for
2842     // pointer-to-member expressions; we just call them l-values for
2843     // internal consistency, because this subexpression doesn't really
2844     // exist in the high-level semantics.
2845     case Decl::Field:
2846     case Decl::IndirectField:
2847       assert(getLangOpts().CPlusPlus &&
2848              "building reference to field in C?");
2849
2850       // These can't have reference type in well-formed programs, but
2851       // for internal consistency we do this anyway.
2852       type = type.getNonReferenceType();
2853       valueKind = VK_LValue;
2854       break;
2855
2856     // Non-type template parameters are either l-values or r-values
2857     // depending on the type.
2858     case Decl::NonTypeTemplateParm: {
2859       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2860         type = reftype->getPointeeType();
2861         valueKind = VK_LValue; // even if the parameter is an r-value reference
2862         break;
2863       }
2864
2865       // For non-references, we need to strip qualifiers just in case
2866       // the template parameter was declared as 'const int' or whatever.
2867       valueKind = VK_RValue;
2868       type = type.getUnqualifiedType();
2869       break;
2870     }
2871
2872     case Decl::Var:
2873     case Decl::VarTemplateSpecialization:
2874     case Decl::VarTemplatePartialSpecialization:
2875     case Decl::Decomposition:
2876     case Decl::OMPCapturedExpr:
2877       // In C, "extern void blah;" is valid and is an r-value.
2878       if (!getLangOpts().CPlusPlus &&
2879           !type.hasQualifiers() &&
2880           type->isVoidType()) {
2881         valueKind = VK_RValue;
2882         break;
2883       }
2884       // fallthrough
2885
2886     case Decl::ImplicitParam:
2887     case Decl::ParmVar: {
2888       // These are always l-values.
2889       valueKind = VK_LValue;
2890       type = type.getNonReferenceType();
2891
2892       // FIXME: Does the addition of const really only apply in
2893       // potentially-evaluated contexts? Since the variable isn't actually
2894       // captured in an unevaluated context, it seems that the answer is no.
2895       if (!isUnevaluatedContext()) {
2896         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2897         if (!CapturedType.isNull())
2898           type = CapturedType;
2899       }
2900       
2901       break;
2902     }
2903
2904     case Decl::Binding: {
2905       // These are always lvalues.
2906       valueKind = VK_LValue;
2907       type = type.getNonReferenceType();
2908       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2909       // decides how that's supposed to work.
2910       auto *BD = cast<BindingDecl>(VD);
2911       if (BD->getDeclContext()->isFunctionOrMethod() &&
2912           BD->getDeclContext() != CurContext)
2913         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2914       break;
2915     }
2916         
2917     case Decl::Function: {
2918       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2919         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2920           type = Context.BuiltinFnTy;
2921           valueKind = VK_RValue;
2922           break;
2923         }
2924       }
2925
2926       const FunctionType *fty = type->castAs<FunctionType>();
2927
2928       // If we're referring to a function with an __unknown_anytype
2929       // result type, make the entire expression __unknown_anytype.
2930       if (fty->getReturnType() == Context.UnknownAnyTy) {
2931         type = Context.UnknownAnyTy;
2932         valueKind = VK_RValue;
2933         break;
2934       }
2935
2936       // Functions are l-values in C++.
2937       if (getLangOpts().CPlusPlus) {
2938         valueKind = VK_LValue;
2939         break;
2940       }
2941       
2942       // C99 DR 316 says that, if a function type comes from a
2943       // function definition (without a prototype), that type is only
2944       // used for checking compatibility. Therefore, when referencing
2945       // the function, we pretend that we don't have the full function
2946       // type.
2947       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2948           isa<FunctionProtoType>(fty))
2949         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2950                                               fty->getExtInfo());
2951
2952       // Functions are r-values in C.
2953       valueKind = VK_RValue;
2954       break;
2955     }
2956
2957     case Decl::CXXDeductionGuide:
2958       llvm_unreachable("building reference to deduction guide");
2959
2960     case Decl::MSProperty:
2961       valueKind = VK_LValue;
2962       break;
2963
2964     case Decl::CXXMethod:
2965       // If we're referring to a method with an __unknown_anytype
2966       // result type, make the entire expression __unknown_anytype.
2967       // This should only be possible with a type written directly.
2968       if (const FunctionProtoType *proto
2969             = dyn_cast<FunctionProtoType>(VD->getType()))
2970         if (proto->getReturnType() == Context.UnknownAnyTy) {
2971           type = Context.UnknownAnyTy;
2972           valueKind = VK_RValue;
2973           break;
2974         }
2975
2976       // C++ methods are l-values if static, r-values if non-static.
2977       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2978         valueKind = VK_LValue;
2979         break;
2980       }
2981       // fallthrough
2982
2983     case Decl::CXXConversion:
2984     case Decl::CXXDestructor:
2985     case Decl::CXXConstructor:
2986       valueKind = VK_RValue;
2987       break;
2988     }
2989
2990     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2991                             TemplateArgs);
2992   }
2993 }
2994
2995 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2996                                     SmallString<32> &Target) {
2997   Target.resize(CharByteWidth * (Source.size() + 1));
2998   char *ResultPtr = &Target[0];
2999   const llvm::UTF8 *ErrorPtr;
3000   bool success =
3001       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3002   (void)success;
3003   assert(success);
3004   Target.resize(ResultPtr - &Target[0]);
3005 }
3006
3007 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3008                                      PredefinedExpr::IdentType IT) {
3009   // Pick the current block, lambda, captured statement or function.
3010   Decl *currentDecl = nullptr;
3011   if (const BlockScopeInfo *BSI = getCurBlock())
3012     currentDecl = BSI->TheDecl;
3013   else if (const LambdaScopeInfo *LSI = getCurLambda())
3014     currentDecl = LSI->CallOperator;
3015   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3016     currentDecl = CSI->TheCapturedDecl;
3017   else
3018     currentDecl = getCurFunctionOrMethodDecl();
3019
3020   if (!currentDecl) {
3021     Diag(Loc, diag::ext_predef_outside_function);
3022     currentDecl = Context.getTranslationUnitDecl();
3023   }
3024
3025   QualType ResTy;
3026   StringLiteral *SL = nullptr;
3027   if (cast<DeclContext>(currentDecl)->isDependentContext())
3028     ResTy = Context.DependentTy;
3029   else {
3030     // Pre-defined identifiers are of type char[x], where x is the length of
3031     // the string.
3032     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3033     unsigned Length = Str.length();
3034
3035     llvm::APInt LengthI(32, Length + 1);
3036     if (IT == PredefinedExpr::LFunction) {
3037       ResTy = Context.WideCharTy.withConst();
3038       SmallString<32> RawChars;
3039       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3040                               Str, RawChars);
3041       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3042                                            /*IndexTypeQuals*/ 0);
3043       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3044                                  /*Pascal*/ false, ResTy, Loc);
3045     } else {
3046       ResTy = Context.CharTy.withConst();
3047       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3048                                            /*IndexTypeQuals*/ 0);
3049       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3050                                  /*Pascal*/ false, ResTy, Loc);
3051     }
3052   }
3053
3054   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3055 }
3056
3057 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3058   PredefinedExpr::IdentType IT;
3059
3060   switch (Kind) {
3061   default: llvm_unreachable("Unknown simple primary expr!");
3062   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3063   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3064   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3065   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3066   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3067   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3068   }
3069
3070   return BuildPredefinedExpr(Loc, IT);
3071 }
3072
3073 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3074   SmallString<16> CharBuffer;
3075   bool Invalid = false;
3076   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3077   if (Invalid)
3078     return ExprError();
3079
3080   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3081                             PP, Tok.getKind());
3082   if (Literal.hadError())
3083     return ExprError();
3084
3085   QualType Ty;
3086   if (Literal.isWide())
3087     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3088   else if (Literal.isUTF16())
3089     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3090   else if (Literal.isUTF32())
3091     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3092   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3093     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3094   else
3095     Ty = Context.CharTy;  // 'x' -> char in C++
3096
3097   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3098   if (Literal.isWide())
3099     Kind = CharacterLiteral::Wide;
3100   else if (Literal.isUTF16())
3101     Kind = CharacterLiteral::UTF16;
3102   else if (Literal.isUTF32())
3103     Kind = CharacterLiteral::UTF32;
3104   else if (Literal.isUTF8())
3105     Kind = CharacterLiteral::UTF8;
3106
3107   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3108                                              Tok.getLocation());
3109
3110   if (Literal.getUDSuffix().empty())
3111     return Lit;
3112
3113   // We're building a user-defined literal.
3114   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3115   SourceLocation UDSuffixLoc =
3116     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3117
3118   // Make sure we're allowed user-defined literals here.
3119   if (!UDLScope)
3120     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3121
3122   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3123   //   operator "" X (ch)
3124   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3125                                         Lit, Tok.getLocation());
3126 }
3127
3128 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3129   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3130   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3131                                 Context.IntTy, Loc);
3132 }
3133
3134 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3135                                   QualType Ty, SourceLocation Loc) {
3136   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3137
3138   using llvm::APFloat;
3139   APFloat Val(Format);
3140
3141   APFloat::opStatus result = Literal.GetFloatValue(Val);
3142
3143   // Overflow is always an error, but underflow is only an error if
3144   // we underflowed to zero (APFloat reports denormals as underflow).
3145   if ((result & APFloat::opOverflow) ||
3146       ((result & APFloat::opUnderflow) && Val.isZero())) {
3147     unsigned diagnostic;
3148     SmallString<20> buffer;
3149     if (result & APFloat::opOverflow) {
3150       diagnostic = diag::warn_float_overflow;
3151       APFloat::getLargest(Format).toString(buffer);
3152     } else {
3153       diagnostic = diag::warn_float_underflow;
3154       APFloat::getSmallest(Format).toString(buffer);
3155     }
3156
3157     S.Diag(Loc, diagnostic)
3158       << Ty
3159       << StringRef(buffer.data(), buffer.size());
3160   }
3161
3162   bool isExact = (result == APFloat::opOK);
3163   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3164 }
3165
3166 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3167   assert(E && "Invalid expression");
3168
3169   if (E->isValueDependent())
3170     return false;
3171
3172   QualType QT = E->getType();
3173   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3174     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3175     return true;
3176   }
3177
3178   llvm::APSInt ValueAPS;
3179   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3180
3181   if (R.isInvalid())
3182     return true;
3183
3184   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3185   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3186     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3187         << ValueAPS.toString(10) << ValueIsPositive;
3188     return true;
3189   }
3190
3191   return false;
3192 }
3193
3194 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3195   // Fast path for a single digit (which is quite common).  A single digit
3196   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3197   if (Tok.getLength() == 1) {
3198     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3199     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3200   }
3201
3202   SmallString<128> SpellingBuffer;
3203   // NumericLiteralParser wants to overread by one character.  Add padding to
3204   // the buffer in case the token is copied to the buffer.  If getSpelling()
3205   // returns a StringRef to the memory buffer, it should have a null char at
3206   // the EOF, so it is also safe.
3207   SpellingBuffer.resize(Tok.getLength() + 1);
3208
3209   // Get the spelling of the token, which eliminates trigraphs, etc.
3210   bool Invalid = false;
3211   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3212   if (Invalid)
3213     return ExprError();
3214
3215   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3216   if (Literal.hadError)
3217     return ExprError();
3218
3219   if (Literal.hasUDSuffix()) {
3220     // We're building a user-defined literal.
3221     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3222     SourceLocation UDSuffixLoc =
3223       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3224
3225     // Make sure we're allowed user-defined literals here.
3226     if (!UDLScope)
3227       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3228
3229     QualType CookedTy;
3230     if (Literal.isFloatingLiteral()) {
3231       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3232       // long double, the literal is treated as a call of the form
3233       //   operator "" X (f L)
3234       CookedTy = Context.LongDoubleTy;
3235     } else {
3236       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3237       // unsigned long long, the literal is treated as a call of the form
3238       //   operator "" X (n ULL)
3239       CookedTy = Context.UnsignedLongLongTy;
3240     }
3241
3242     DeclarationName OpName =
3243       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3244     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3245     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3246
3247     SourceLocation TokLoc = Tok.getLocation();
3248
3249     // Perform literal operator lookup to determine if we're building a raw
3250     // literal or a cooked one.
3251     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3252     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3253                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3254                                   /*AllowStringTemplate*/false)) {
3255     case LOLR_Error:
3256       return ExprError();
3257
3258     case LOLR_Cooked: {
3259       Expr *Lit;
3260       if (Literal.isFloatingLiteral()) {
3261         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3262       } else {
3263         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3264         if (Literal.GetIntegerValue(ResultVal))
3265           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3266               << /* Unsigned */ 1;
3267         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3268                                      Tok.getLocation());
3269       }
3270       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3271     }
3272
3273     case LOLR_Raw: {
3274       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3275       // literal is treated as a call of the form
3276       //   operator "" X ("n")
3277       unsigned Length = Literal.getUDSuffixOffset();
3278       QualType StrTy = Context.getConstantArrayType(
3279           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3280           ArrayType::Normal, 0);
3281       Expr *Lit = StringLiteral::Create(
3282           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3283           /*Pascal*/false, StrTy, &TokLoc, 1);
3284       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3285     }
3286
3287     case LOLR_Template: {
3288       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3289       // template), L is treated as a call fo the form
3290       //   operator "" X <'c1', 'c2', ... 'ck'>()
3291       // where n is the source character sequence c1 c2 ... ck.
3292       TemplateArgumentListInfo ExplicitArgs;
3293       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3294       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3295       llvm::APSInt Value(CharBits, CharIsUnsigned);
3296       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3297         Value = TokSpelling[I];
3298         TemplateArgument Arg(Context, Value, Context.CharTy);
3299         TemplateArgumentLocInfo ArgInfo;
3300         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3301       }
3302       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3303                                       &ExplicitArgs);
3304     }
3305     case LOLR_StringTemplate:
3306       llvm_unreachable("unexpected literal operator lookup result");
3307     }
3308   }
3309
3310   Expr *Res;
3311
3312   if (Literal.isFloatingLiteral()) {
3313     QualType Ty;
3314     if (Literal.isHalf){
3315       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3316         Ty = Context.HalfTy;
3317       else {
3318         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3319         return ExprError();
3320       }
3321     } else if (Literal.isFloat)
3322       Ty = Context.FloatTy;
3323     else if (Literal.isLong)
3324       Ty = Context.LongDoubleTy;
3325     else if (Literal.isFloat128)
3326       Ty = Context.Float128Ty;
3327     else
3328       Ty = Context.DoubleTy;
3329
3330     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3331
3332     if (Ty == Context.DoubleTy) {
3333       if (getLangOpts().SinglePrecisionConstants) {
3334         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3335         if (BTy->getKind() != BuiltinType::Float) {
3336           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3337         }
3338       } else if (getLangOpts().OpenCL &&
3339                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3340         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3341         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3342         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3343       }
3344     }
3345   } else if (!Literal.isIntegerLiteral()) {
3346     return ExprError();
3347   } else {
3348     QualType Ty;
3349
3350     // 'long long' is a C99 or C++11 feature.
3351     if (!getLangOpts().C99 && Literal.isLongLong) {
3352       if (getLangOpts().CPlusPlus)
3353         Diag(Tok.getLocation(),
3354              getLangOpts().CPlusPlus11 ?
3355              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3356       else
3357         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3358     }
3359
3360     // Get the value in the widest-possible width.
3361     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3362     llvm::APInt ResultVal(MaxWidth, 0);
3363
3364     if (Literal.GetIntegerValue(ResultVal)) {
3365       // If this value didn't fit into uintmax_t, error and force to ull.
3366       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3367           << /* Unsigned */ 1;
3368       Ty = Context.UnsignedLongLongTy;
3369       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3370              "long long is not intmax_t?");
3371     } else {
3372       // If this value fits into a ULL, try to figure out what else it fits into
3373       // according to the rules of C99 6.4.4.1p5.
3374
3375       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3376       // be an unsigned int.
3377       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3378
3379       // Check from smallest to largest, picking the smallest type we can.
3380       unsigned Width = 0;
3381
3382       // Microsoft specific integer suffixes are explicitly sized.
3383       if (Literal.MicrosoftInteger) {
3384         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3385           Width = 8;
3386           Ty = Context.CharTy;
3387         } else {
3388           Width = Literal.MicrosoftInteger;
3389           Ty = Context.getIntTypeForBitwidth(Width,
3390                                              /*Signed=*/!Literal.isUnsigned);
3391         }
3392       }
3393
3394       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3395         // Are int/unsigned possibilities?
3396         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3397
3398         // Does it fit in a unsigned int?
3399         if (ResultVal.isIntN(IntSize)) {
3400           // Does it fit in a signed int?
3401           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3402             Ty = Context.IntTy;
3403           else if (AllowUnsigned)
3404             Ty = Context.UnsignedIntTy;
3405           Width = IntSize;
3406         }
3407       }
3408
3409       // Are long/unsigned long possibilities?
3410       if (Ty.isNull() && !Literal.isLongLong) {
3411         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3412
3413         // Does it fit in a unsigned long?
3414         if (ResultVal.isIntN(LongSize)) {
3415           // Does it fit in a signed long?
3416           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3417             Ty = Context.LongTy;
3418           else if (AllowUnsigned)
3419             Ty = Context.UnsignedLongTy;
3420           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3421           // is compatible.
3422           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3423             const unsigned LongLongSize =
3424                 Context.getTargetInfo().getLongLongWidth();
3425             Diag(Tok.getLocation(),
3426                  getLangOpts().CPlusPlus
3427                      ? Literal.isLong
3428                            ? diag::warn_old_implicitly_unsigned_long_cxx
3429                            : /*C++98 UB*/ diag::
3430                                  ext_old_implicitly_unsigned_long_cxx
3431                      : diag::warn_old_implicitly_unsigned_long)
3432                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3433                                             : /*will be ill-formed*/ 1);
3434             Ty = Context.UnsignedLongTy;
3435           }
3436           Width = LongSize;
3437         }
3438       }
3439
3440       // Check long long if needed.
3441       if (Ty.isNull()) {
3442         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3443
3444         // Does it fit in a unsigned long long?
3445         if (ResultVal.isIntN(LongLongSize)) {
3446           // Does it fit in a signed long long?
3447           // To be compatible with MSVC, hex integer literals ending with the
3448           // LL or i64 suffix are always signed in Microsoft mode.
3449           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3450               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3451             Ty = Context.LongLongTy;
3452           else if (AllowUnsigned)
3453             Ty = Context.UnsignedLongLongTy;
3454           Width = LongLongSize;
3455         }
3456       }
3457
3458       // If we still couldn't decide a type, we probably have something that
3459       // does not fit in a signed long long, but has no U suffix.
3460       if (Ty.isNull()) {
3461         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3462         Ty = Context.UnsignedLongLongTy;
3463         Width = Context.getTargetInfo().getLongLongWidth();
3464       }
3465
3466       if (ResultVal.getBitWidth() != Width)
3467         ResultVal = ResultVal.trunc(Width);
3468     }
3469     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3470   }
3471
3472   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3473   if (Literal.isImaginary)
3474     Res = new (Context) ImaginaryLiteral(Res,
3475                                         Context.getComplexType(Res->getType()));
3476
3477   return Res;
3478 }
3479
3480 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3481   assert(E && "ActOnParenExpr() missing expr");
3482   return new (Context) ParenExpr(L, R, E);
3483 }
3484
3485 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3486                                          SourceLocation Loc,
3487                                          SourceRange ArgRange) {
3488   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3489   // scalar or vector data type argument..."
3490   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3491   // type (C99 6.2.5p18) or void.
3492   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3493     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3494       << T << ArgRange;
3495     return true;
3496   }
3497
3498   assert((T->isVoidType() || !T->isIncompleteType()) &&
3499          "Scalar types should always be complete");
3500   return false;
3501 }
3502
3503 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3504                                            SourceLocation Loc,
3505                                            SourceRange ArgRange,
3506                                            UnaryExprOrTypeTrait TraitKind) {
3507   // Invalid types must be hard errors for SFINAE in C++.
3508   if (S.LangOpts.CPlusPlus)
3509     return true;
3510
3511   // C99 6.5.3.4p1:
3512   if (T->isFunctionType() &&
3513       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3514     // sizeof(function)/alignof(function) is allowed as an extension.
3515     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3516       << TraitKind << ArgRange;
3517     return false;
3518   }
3519
3520   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3521   // this is an error (OpenCL v1.1 s6.3.k)
3522   if (T->isVoidType()) {
3523     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3524                                         : diag::ext_sizeof_alignof_void_type;
3525     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3526     return false;
3527   }
3528
3529   return true;
3530 }
3531
3532 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3533                                              SourceLocation Loc,
3534                                              SourceRange ArgRange,
3535                                              UnaryExprOrTypeTrait TraitKind) {
3536   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3537   // runtime doesn't allow it.
3538   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3539     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3540       << T << (TraitKind == UETT_SizeOf)
3541       << ArgRange;
3542     return true;
3543   }
3544
3545   return false;
3546 }
3547
3548 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3549 /// pointer type is equal to T) and emit a warning if it is.
3550 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3551                                      Expr *E) {
3552   // Don't warn if the operation changed the type.
3553   if (T != E->getType())
3554     return;
3555
3556   // Now look for array decays.
3557   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3558   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3559     return;
3560
3561   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3562                                              << ICE->getType()
3563                                              << ICE->getSubExpr()->getType();
3564 }
3565
3566 /// \brief Check the constraints on expression operands to unary type expression
3567 /// and type traits.
3568 ///
3569 /// Completes any types necessary and validates the constraints on the operand
3570 /// expression. The logic mostly mirrors the type-based overload, but may modify
3571 /// the expression as it completes the type for that expression through template
3572 /// instantiation, etc.
3573 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3574                                             UnaryExprOrTypeTrait ExprKind) {
3575   QualType ExprTy = E->getType();
3576   assert(!ExprTy->isReferenceType());
3577
3578   if (ExprKind == UETT_VecStep)
3579     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3580                                         E->getSourceRange());
3581
3582   // Whitelist some types as extensions
3583   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3584                                       E->getSourceRange(), ExprKind))
3585     return false;
3586
3587   // 'alignof' applied to an expression only requires the base element type of
3588   // the expression to be complete. 'sizeof' requires the expression's type to
3589   // be complete (and will attempt to complete it if it's an array of unknown
3590   // bound).
3591   if (ExprKind == UETT_AlignOf) {
3592     if (RequireCompleteType(E->getExprLoc(),
3593                             Context.getBaseElementType(E->getType()),
3594                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3595                             E->getSourceRange()))
3596       return true;
3597   } else {
3598     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3599                                 ExprKind, E->getSourceRange()))
3600       return true;
3601   }
3602
3603   // Completing the expression's type may have changed it.
3604   ExprTy = E->getType();
3605   assert(!ExprTy->isReferenceType());
3606
3607   if (ExprTy->isFunctionType()) {
3608     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3609       << ExprKind << E->getSourceRange();
3610     return true;
3611   }
3612
3613   // The operand for sizeof and alignof is in an unevaluated expression context,
3614   // so side effects could result in unintended consequences.
3615   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3616       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3617     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3618
3619   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3620                                        E->getSourceRange(), ExprKind))
3621     return true;
3622
3623   if (ExprKind == UETT_SizeOf) {
3624     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3625       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3626         QualType OType = PVD->getOriginalType();
3627         QualType Type = PVD->getType();
3628         if (Type->isPointerType() && OType->isArrayType()) {
3629           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3630             << Type << OType;
3631           Diag(PVD->getLocation(), diag::note_declared_at);
3632         }
3633       }
3634     }
3635
3636     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3637     // decays into a pointer and returns an unintended result. This is most
3638     // likely a typo for "sizeof(array) op x".
3639     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3640       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3641                                BO->getLHS());
3642       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3643                                BO->getRHS());
3644     }
3645   }
3646
3647   return false;
3648 }
3649
3650 /// \brief Check the constraints on operands to unary expression and type
3651 /// traits.
3652 ///
3653 /// This will complete any types necessary, and validate the various constraints
3654 /// on those operands.
3655 ///
3656 /// The UsualUnaryConversions() function is *not* called by this routine.
3657 /// C99 6.3.2.1p[2-4] all state:
3658 ///   Except when it is the operand of the sizeof operator ...
3659 ///
3660 /// C++ [expr.sizeof]p4
3661 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3662 ///   standard conversions are not applied to the operand of sizeof.
3663 ///
3664 /// This policy is followed for all of the unary trait expressions.
3665 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3666                                             SourceLocation OpLoc,
3667                                             SourceRange ExprRange,
3668                                             UnaryExprOrTypeTrait ExprKind) {
3669   if (ExprType->isDependentType())
3670     return false;
3671
3672   // C++ [expr.sizeof]p2:
3673   //     When applied to a reference or a reference type, the result
3674   //     is the size of the referenced type.
3675   // C++11 [expr.alignof]p3:
3676   //     When alignof is applied to a reference type, the result
3677   //     shall be the alignment of the referenced type.
3678   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3679     ExprType = Ref->getPointeeType();
3680
3681   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3682   //   When alignof or _Alignof is applied to an array type, the result
3683   //   is the alignment of the element type.
3684   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3685     ExprType = Context.getBaseElementType(ExprType);
3686
3687   if (ExprKind == UETT_VecStep)
3688     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3689
3690   // Whitelist some types as extensions
3691   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3692                                       ExprKind))
3693     return false;
3694
3695   if (RequireCompleteType(OpLoc, ExprType,
3696                           diag::err_sizeof_alignof_incomplete_type,
3697                           ExprKind, ExprRange))
3698     return true;
3699
3700   if (ExprType->isFunctionType()) {
3701     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3702       << ExprKind << ExprRange;
3703     return true;
3704   }
3705
3706   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3707                                        ExprKind))
3708     return true;
3709
3710   return false;
3711 }
3712
3713 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3714   E = E->IgnoreParens();
3715
3716   // Cannot know anything else if the expression is dependent.
3717   if (E->isTypeDependent())
3718     return false;
3719
3720   if (E->getObjectKind() == OK_BitField) {
3721     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3722        << 1 << E->getSourceRange();
3723     return true;
3724   }
3725
3726   ValueDecl *D = nullptr;
3727   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3728     D = DRE->getDecl();
3729   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3730     D = ME->getMemberDecl();
3731   }
3732
3733   // If it's a field, require the containing struct to have a
3734   // complete definition so that we can compute the layout.
3735   //
3736   // This can happen in C++11 onwards, either by naming the member
3737   // in a way that is not transformed into a member access expression
3738   // (in an unevaluated operand, for instance), or by naming the member
3739   // in a trailing-return-type.
3740   //
3741   // For the record, since __alignof__ on expressions is a GCC
3742   // extension, GCC seems to permit this but always gives the
3743   // nonsensical answer 0.
3744   //
3745   // We don't really need the layout here --- we could instead just
3746   // directly check for all the appropriate alignment-lowing
3747   // attributes --- but that would require duplicating a lot of
3748   // logic that just isn't worth duplicating for such a marginal
3749   // use-case.
3750   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3751     // Fast path this check, since we at least know the record has a
3752     // definition if we can find a member of it.
3753     if (!FD->getParent()->isCompleteDefinition()) {
3754       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3755         << E->getSourceRange();
3756       return true;
3757     }
3758
3759     // Otherwise, if it's a field, and the field doesn't have
3760     // reference type, then it must have a complete type (or be a
3761     // flexible array member, which we explicitly want to
3762     // white-list anyway), which makes the following checks trivial.
3763     if (!FD->getType()->isReferenceType())
3764       return false;
3765   }
3766
3767   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3768 }
3769
3770 bool Sema::CheckVecStepExpr(Expr *E) {
3771   E = E->IgnoreParens();
3772
3773   // Cannot know anything else if the expression is dependent.
3774   if (E->isTypeDependent())
3775     return false;
3776
3777   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3778 }
3779
3780 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3781                                         CapturingScopeInfo *CSI) {
3782   assert(T->isVariablyModifiedType());
3783   assert(CSI != nullptr);
3784
3785   // We're going to walk down into the type and look for VLA expressions.
3786   do {
3787     const Type *Ty = T.getTypePtr();
3788     switch (Ty->getTypeClass()) {
3789 #define TYPE(Class, Base)
3790 #define ABSTRACT_TYPE(Class, Base)
3791 #define NON_CANONICAL_TYPE(Class, Base)
3792 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3793 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3794 #include "clang/AST/TypeNodes.def"
3795       T = QualType();
3796       break;
3797     // These types are never variably-modified.
3798     case Type::Builtin:
3799     case Type::Complex:
3800     case Type::Vector:
3801     case Type::ExtVector:
3802     case Type::Record:
3803     case Type::Enum:
3804     case Type::Elaborated:
3805     case Type::TemplateSpecialization:
3806     case Type::ObjCObject:
3807     case Type::ObjCInterface:
3808     case Type::ObjCObjectPointer:
3809     case Type::ObjCTypeParam:
3810     case Type::Pipe:
3811       llvm_unreachable("type class is never variably-modified!");
3812     case Type::Adjusted:
3813       T = cast<AdjustedType>(Ty)->getOriginalType();
3814       break;
3815     case Type::Decayed:
3816       T = cast<DecayedType>(Ty)->getPointeeType();
3817       break;
3818     case Type::Pointer:
3819       T = cast<PointerType>(Ty)->getPointeeType();
3820       break;
3821     case Type::BlockPointer:
3822       T = cast<BlockPointerType>(Ty)->getPointeeType();
3823       break;
3824     case Type::LValueReference:
3825     case Type::RValueReference:
3826       T = cast<ReferenceType>(Ty)->getPointeeType();
3827       break;
3828     case Type::MemberPointer:
3829       T = cast<MemberPointerType>(Ty)->getPointeeType();
3830       break;
3831     case Type::ConstantArray:
3832     case Type::IncompleteArray:
3833       // Losing element qualification here is fine.
3834       T = cast<ArrayType>(Ty)->getElementType();
3835       break;
3836     case Type::VariableArray: {
3837       // Losing element qualification here is fine.
3838       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3839
3840       // Unknown size indication requires no size computation.
3841       // Otherwise, evaluate and record it.
3842       if (auto Size = VAT->getSizeExpr()) {
3843         if (!CSI->isVLATypeCaptured(VAT)) {
3844           RecordDecl *CapRecord = nullptr;
3845           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3846             CapRecord = LSI->Lambda;
3847           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3848             CapRecord = CRSI->TheRecordDecl;
3849           }
3850           if (CapRecord) {
3851             auto ExprLoc = Size->getExprLoc();
3852             auto SizeType = Context.getSizeType();
3853             // Build the non-static data member.
3854             auto Field =
3855                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3856                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3857                                   /*BW*/ nullptr, /*Mutable*/ false,
3858                                   /*InitStyle*/ ICIS_NoInit);
3859             Field->setImplicit(true);
3860             Field->setAccess(AS_private);
3861             Field->setCapturedVLAType(VAT);
3862             CapRecord->addDecl(Field);
3863
3864             CSI->addVLATypeCapture(ExprLoc, SizeType);
3865           }
3866         }
3867       }
3868       T = VAT->getElementType();
3869       break;
3870     }
3871     case Type::FunctionProto:
3872     case Type::FunctionNoProto:
3873       T = cast<FunctionType>(Ty)->getReturnType();
3874       break;
3875     case Type::Paren:
3876     case Type::TypeOf:
3877     case Type::UnaryTransform:
3878     case Type::Attributed:
3879     case Type::SubstTemplateTypeParm:
3880     case Type::PackExpansion:
3881       // Keep walking after single level desugaring.
3882       T = T.getSingleStepDesugaredType(Context);
3883       break;
3884     case Type::Typedef:
3885       T = cast<TypedefType>(Ty)->desugar();
3886       break;
3887     case Type::Decltype:
3888       T = cast<DecltypeType>(Ty)->desugar();
3889       break;
3890     case Type::Auto:
3891     case Type::DeducedTemplateSpecialization:
3892       T = cast<DeducedType>(Ty)->getDeducedType();
3893       break;
3894     case Type::TypeOfExpr:
3895       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3896       break;
3897     case Type::Atomic:
3898       T = cast<AtomicType>(Ty)->getValueType();
3899       break;
3900     }
3901   } while (!T.isNull() && T->isVariablyModifiedType());
3902 }
3903
3904 /// \brief Build a sizeof or alignof expression given a type operand.
3905 ExprResult
3906 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3907                                      SourceLocation OpLoc,
3908                                      UnaryExprOrTypeTrait ExprKind,
3909                                      SourceRange R) {
3910   if (!TInfo)
3911     return ExprError();
3912
3913   QualType T = TInfo->getType();
3914
3915   if (!T->isDependentType() &&
3916       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3917     return ExprError();
3918
3919   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3920     if (auto *TT = T->getAs<TypedefType>()) {
3921       for (auto I = FunctionScopes.rbegin(),
3922                 E = std::prev(FunctionScopes.rend());
3923            I != E; ++I) {
3924         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3925         if (CSI == nullptr)
3926           break;
3927         DeclContext *DC = nullptr;
3928         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3929           DC = LSI->CallOperator;
3930         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3931           DC = CRSI->TheCapturedDecl;
3932         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3933           DC = BSI->TheDecl;
3934         if (DC) {
3935           if (DC->containsDecl(TT->getDecl()))
3936             break;
3937           captureVariablyModifiedType(Context, T, CSI);
3938         }
3939       }
3940     }
3941   }
3942
3943   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3944   return new (Context) UnaryExprOrTypeTraitExpr(
3945       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3946 }
3947
3948 /// \brief Build a sizeof or alignof expression given an expression
3949 /// operand.
3950 ExprResult
3951 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3952                                      UnaryExprOrTypeTrait ExprKind) {
3953   ExprResult PE = CheckPlaceholderExpr(E);
3954   if (PE.isInvalid()) 
3955     return ExprError();
3956
3957   E = PE.get();
3958   
3959   // Verify that the operand is valid.
3960   bool isInvalid = false;
3961   if (E->isTypeDependent()) {
3962     // Delay type-checking for type-dependent expressions.
3963   } else if (ExprKind == UETT_AlignOf) {
3964     isInvalid = CheckAlignOfExpr(*this, E);
3965   } else if (ExprKind == UETT_VecStep) {
3966     isInvalid = CheckVecStepExpr(E);
3967   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3968       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3969       isInvalid = true;
3970   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3971     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3972     isInvalid = true;
3973   } else {
3974     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3975   }
3976
3977   if (isInvalid)
3978     return ExprError();
3979
3980   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3981     PE = TransformToPotentiallyEvaluated(E);
3982     if (PE.isInvalid()) return ExprError();
3983     E = PE.get();
3984   }
3985
3986   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3987   return new (Context) UnaryExprOrTypeTraitExpr(
3988       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3989 }
3990
3991 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3992 /// expr and the same for @c alignof and @c __alignof
3993 /// Note that the ArgRange is invalid if isType is false.
3994 ExprResult
3995 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3996                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3997                                     void *TyOrEx, SourceRange ArgRange) {
3998   // If error parsing type, ignore.
3999   if (!TyOrEx) return ExprError();
4000
4001   if (IsType) {
4002     TypeSourceInfo *TInfo;
4003     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4004     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4005   }
4006
4007   Expr *ArgEx = (Expr *)TyOrEx;
4008   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4009   return Result;
4010 }
4011
4012 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4013                                      bool IsReal) {
4014   if (V.get()->isTypeDependent())
4015     return S.Context.DependentTy;
4016
4017   // _Real and _Imag are only l-values for normal l-values.
4018   if (V.get()->getObjectKind() != OK_Ordinary) {
4019     V = S.DefaultLvalueConversion(V.get());
4020     if (V.isInvalid())
4021       return QualType();
4022   }
4023
4024   // These operators return the element type of a complex type.
4025   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4026     return CT->getElementType();
4027
4028   // Otherwise they pass through real integer and floating point types here.
4029   if (V.get()->getType()->isArithmeticType())
4030     return V.get()->getType();
4031
4032   // Test for placeholders.
4033   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4034   if (PR.isInvalid()) return QualType();
4035   if (PR.get() != V.get()) {
4036     V = PR;
4037     return CheckRealImagOperand(S, V, Loc, IsReal);
4038   }
4039
4040   // Reject anything else.
4041   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4042     << (IsReal ? "__real" : "__imag");
4043   return QualType();
4044 }
4045
4046
4047
4048 ExprResult
4049 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4050                           tok::TokenKind Kind, Expr *Input) {
4051   UnaryOperatorKind Opc;
4052   switch (Kind) {
4053   default: llvm_unreachable("Unknown unary op!");
4054   case tok::plusplus:   Opc = UO_PostInc; break;
4055   case tok::minusminus: Opc = UO_PostDec; break;
4056   }
4057
4058   // Since this might is a postfix expression, get rid of ParenListExprs.
4059   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4060   if (Result.isInvalid()) return ExprError();
4061   Input = Result.get();
4062
4063   return BuildUnaryOp(S, OpLoc, Opc, Input);
4064 }
4065
4066 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4067 ///
4068 /// \return true on error
4069 static bool checkArithmeticOnObjCPointer(Sema &S,
4070                                          SourceLocation opLoc,
4071                                          Expr *op) {
4072   assert(op->getType()->isObjCObjectPointerType());
4073   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4074       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4075     return false;
4076
4077   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4078     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4079     << op->getSourceRange();
4080   return true;
4081 }
4082
4083 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4084   auto *BaseNoParens = Base->IgnoreParens();
4085   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4086     return MSProp->getPropertyDecl()->getType()->isArrayType();
4087   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4088 }
4089
4090 ExprResult
4091 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4092                               Expr *idx, SourceLocation rbLoc) {
4093   if (base && !base->getType().isNull() &&
4094       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4095     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4096                                     /*Length=*/nullptr, rbLoc);
4097
4098   // Since this might be a postfix expression, get rid of ParenListExprs.
4099   if (isa<ParenListExpr>(base)) {
4100     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4101     if (result.isInvalid()) return ExprError();
4102     base = result.get();
4103   }
4104
4105   // Handle any non-overload placeholder types in the base and index
4106   // expressions.  We can't handle overloads here because the other
4107   // operand might be an overloadable type, in which case the overload
4108   // resolution for the operator overload should get the first crack
4109   // at the overload.
4110   bool IsMSPropertySubscript = false;
4111   if (base->getType()->isNonOverloadPlaceholderType()) {
4112     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4113     if (!IsMSPropertySubscript) {
4114       ExprResult result = CheckPlaceholderExpr(base);
4115       if (result.isInvalid())
4116         return ExprError();
4117       base = result.get();
4118     }
4119   }
4120   if (idx->getType()->isNonOverloadPlaceholderType()) {
4121     ExprResult result = CheckPlaceholderExpr(idx);
4122     if (result.isInvalid()) return ExprError();
4123     idx = result.get();
4124   }
4125
4126   // Build an unanalyzed expression if either operand is type-dependent.
4127   if (getLangOpts().CPlusPlus &&
4128       (base->isTypeDependent() || idx->isTypeDependent())) {
4129     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4130                                             VK_LValue, OK_Ordinary, rbLoc);
4131   }
4132
4133   // MSDN, property (C++)
4134   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4135   // This attribute can also be used in the declaration of an empty array in a
4136   // class or structure definition. For example:
4137   // __declspec(property(get=GetX, put=PutX)) int x[];
4138   // The above statement indicates that x[] can be used with one or more array
4139   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4140   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4141   if (IsMSPropertySubscript) {
4142     // Build MS property subscript expression if base is MS property reference
4143     // or MS property subscript.
4144     return new (Context) MSPropertySubscriptExpr(
4145         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4146   }
4147
4148   // Use C++ overloaded-operator rules if either operand has record
4149   // type.  The spec says to do this if either type is *overloadable*,
4150   // but enum types can't declare subscript operators or conversion
4151   // operators, so there's nothing interesting for overload resolution
4152   // to do if there aren't any record types involved.
4153   //
4154   // ObjC pointers have their own subscripting logic that is not tied
4155   // to overload resolution and so should not take this path.
4156   if (getLangOpts().CPlusPlus &&
4157       (base->getType()->isRecordType() ||
4158        (!base->getType()->isObjCObjectPointerType() &&
4159         idx->getType()->isRecordType()))) {
4160     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4161   }
4162
4163   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4164 }
4165
4166 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4167                                           Expr *LowerBound,
4168                                           SourceLocation ColonLoc, Expr *Length,
4169                                           SourceLocation RBLoc) {
4170   if (Base->getType()->isPlaceholderType() &&
4171       !Base->getType()->isSpecificPlaceholderType(
4172           BuiltinType::OMPArraySection)) {
4173     ExprResult Result = CheckPlaceholderExpr(Base);
4174     if (Result.isInvalid())
4175       return ExprError();
4176     Base = Result.get();
4177   }
4178   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4179     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4180     if (Result.isInvalid())
4181       return ExprError();
4182     Result = DefaultLvalueConversion(Result.get());
4183     if (Result.isInvalid())
4184       return ExprError();
4185     LowerBound = Result.get();
4186   }
4187   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4188     ExprResult Result = CheckPlaceholderExpr(Length);
4189     if (Result.isInvalid())
4190       return ExprError();
4191     Result = DefaultLvalueConversion(Result.get());
4192     if (Result.isInvalid())
4193       return ExprError();
4194     Length = Result.get();
4195   }
4196
4197   // Build an unanalyzed expression if either operand is type-dependent.
4198   if (Base->isTypeDependent() ||
4199       (LowerBound &&
4200        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4201       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4202     return new (Context)
4203         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4204                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4205   }
4206
4207   // Perform default conversions.
4208   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4209   QualType ResultTy;
4210   if (OriginalTy->isAnyPointerType()) {
4211     ResultTy = OriginalTy->getPointeeType();
4212   } else if (OriginalTy->isArrayType()) {
4213     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4214   } else {
4215     return ExprError(
4216         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4217         << Base->getSourceRange());
4218   }
4219   // C99 6.5.2.1p1
4220   if (LowerBound) {
4221     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4222                                                       LowerBound);
4223     if (Res.isInvalid())
4224       return ExprError(Diag(LowerBound->getExprLoc(),
4225                             diag::err_omp_typecheck_section_not_integer)
4226                        << 0 << LowerBound->getSourceRange());
4227     LowerBound = Res.get();
4228
4229     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4230         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4231       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4232           << 0 << LowerBound->getSourceRange();
4233   }
4234   if (Length) {
4235     auto Res =
4236         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4237     if (Res.isInvalid())
4238       return ExprError(Diag(Length->getExprLoc(),
4239                             diag::err_omp_typecheck_section_not_integer)
4240                        << 1 << Length->getSourceRange());
4241     Length = Res.get();
4242
4243     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4244         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4245       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4246           << 1 << Length->getSourceRange();
4247   }
4248
4249   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4250   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4251   // type. Note that functions are not objects, and that (in C99 parlance)
4252   // incomplete types are not object types.
4253   if (ResultTy->isFunctionType()) {
4254     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4255         << ResultTy << Base->getSourceRange();
4256     return ExprError();
4257   }
4258
4259   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4260                           diag::err_omp_section_incomplete_type, Base))
4261     return ExprError();
4262
4263   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4264     llvm::APSInt LowerBoundValue;
4265     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4266       // OpenMP 4.5, [2.4 Array Sections]
4267       // The array section must be a subset of the original array.
4268       if (LowerBoundValue.isNegative()) {
4269         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4270             << LowerBound->getSourceRange();
4271         return ExprError();
4272       }
4273     }
4274   }
4275
4276   if (Length) {
4277     llvm::APSInt LengthValue;
4278     if (Length->EvaluateAsInt(LengthValue, Context)) {
4279       // OpenMP 4.5, [2.4 Array Sections]
4280       // The length must evaluate to non-negative integers.
4281       if (LengthValue.isNegative()) {
4282         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4283             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4284             << Length->getSourceRange();
4285         return ExprError();
4286       }
4287     }
4288   } else if (ColonLoc.isValid() &&
4289              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4290                                       !OriginalTy->isVariableArrayType()))) {
4291     // OpenMP 4.5, [2.4 Array Sections]
4292     // When the size of the array dimension is not known, the length must be
4293     // specified explicitly.
4294     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4295         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4296     return ExprError();
4297   }
4298
4299   if (!Base->getType()->isSpecificPlaceholderType(
4300           BuiltinType::OMPArraySection)) {
4301     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4302     if (Result.isInvalid())
4303       return ExprError();
4304     Base = Result.get();
4305   }
4306   return new (Context)
4307       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4308                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4309 }
4310
4311 ExprResult
4312 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4313                                       Expr *Idx, SourceLocation RLoc) {
4314   Expr *LHSExp = Base;
4315   Expr *RHSExp = Idx;
4316
4317   ExprValueKind VK = VK_LValue;
4318   ExprObjectKind OK = OK_Ordinary;
4319
4320   // Per C++ core issue 1213, the result is an xvalue if either operand is
4321   // a non-lvalue array, and an lvalue otherwise.
4322   if (getLangOpts().CPlusPlus11 &&
4323       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4324        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4325     VK = VK_XValue;
4326
4327   // Perform default conversions.
4328   if (!LHSExp->getType()->getAs<VectorType>()) {
4329     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4330     if (Result.isInvalid())
4331       return ExprError();
4332     LHSExp = Result.get();
4333   }
4334   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4335   if (Result.isInvalid())
4336     return ExprError();
4337   RHSExp = Result.get();
4338
4339   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4340
4341   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4342   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4343   // in the subscript position. As a result, we need to derive the array base
4344   // and index from the expression types.
4345   Expr *BaseExpr, *IndexExpr;
4346   QualType ResultType;
4347   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4348     BaseExpr = LHSExp;
4349     IndexExpr = RHSExp;
4350     ResultType = Context.DependentTy;
4351   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4352     BaseExpr = LHSExp;
4353     IndexExpr = RHSExp;
4354     ResultType = PTy->getPointeeType();
4355   } else if (const ObjCObjectPointerType *PTy =
4356                LHSTy->getAs<ObjCObjectPointerType>()) {
4357     BaseExpr = LHSExp;
4358     IndexExpr = RHSExp;
4359
4360     // Use custom logic if this should be the pseudo-object subscript
4361     // expression.
4362     if (!LangOpts.isSubscriptPointerArithmetic())
4363       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4364                                           nullptr);
4365
4366     ResultType = PTy->getPointeeType();
4367   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4368      // Handle the uncommon case of "123[Ptr]".
4369     BaseExpr = RHSExp;
4370     IndexExpr = LHSExp;
4371     ResultType = PTy->getPointeeType();
4372   } else if (const ObjCObjectPointerType *PTy =
4373                RHSTy->getAs<ObjCObjectPointerType>()) {
4374      // Handle the uncommon case of "123[Ptr]".
4375     BaseExpr = RHSExp;
4376     IndexExpr = LHSExp;
4377     ResultType = PTy->getPointeeType();
4378     if (!LangOpts.isSubscriptPointerArithmetic()) {
4379       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4380         << ResultType << BaseExpr->getSourceRange();
4381       return ExprError();
4382     }
4383   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4384     BaseExpr = LHSExp;    // vectors: V[123]
4385     IndexExpr = RHSExp;
4386     VK = LHSExp->getValueKind();
4387     if (VK != VK_RValue)
4388       OK = OK_VectorComponent;
4389
4390     // FIXME: need to deal with const...
4391     ResultType = VTy->getElementType();
4392   } else if (LHSTy->isArrayType()) {
4393     // If we see an array that wasn't promoted by
4394     // DefaultFunctionArrayLvalueConversion, it must be an array that
4395     // wasn't promoted because of the C90 rule that doesn't
4396     // allow promoting non-lvalue arrays.  Warn, then
4397     // force the promotion here.
4398     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4399         LHSExp->getSourceRange();
4400     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4401                                CK_ArrayToPointerDecay).get();
4402     LHSTy = LHSExp->getType();
4403
4404     BaseExpr = LHSExp;
4405     IndexExpr = RHSExp;
4406     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4407   } else if (RHSTy->isArrayType()) {
4408     // Same as previous, except for 123[f().a] case
4409     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4410         RHSExp->getSourceRange();
4411     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4412                                CK_ArrayToPointerDecay).get();
4413     RHSTy = RHSExp->getType();
4414
4415     BaseExpr = RHSExp;
4416     IndexExpr = LHSExp;
4417     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4418   } else {
4419     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4420        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4421   }
4422   // C99 6.5.2.1p1
4423   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4424     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4425                      << IndexExpr->getSourceRange());
4426
4427   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4428        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4429          && !IndexExpr->isTypeDependent())
4430     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4431
4432   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4433   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4434   // type. Note that Functions are not objects, and that (in C99 parlance)
4435   // incomplete types are not object types.
4436   if (ResultType->isFunctionType()) {
4437     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4438       << ResultType << BaseExpr->getSourceRange();
4439     return ExprError();
4440   }
4441
4442   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4443     // GNU extension: subscripting on pointer to void
4444     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4445       << BaseExpr->getSourceRange();
4446
4447     // C forbids expressions of unqualified void type from being l-values.
4448     // See IsCForbiddenLValueType.
4449     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4450   } else if (!ResultType->isDependentType() &&
4451       RequireCompleteType(LLoc, ResultType,
4452                           diag::err_subscript_incomplete_type, BaseExpr))
4453     return ExprError();
4454
4455   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4456          !ResultType.isCForbiddenLValueType());
4457
4458   return new (Context)
4459       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4460 }
4461
4462 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4463                                   ParmVarDecl *Param) {
4464   if (Param->hasUnparsedDefaultArg()) {
4465     Diag(CallLoc,
4466          diag::err_use_of_default_argument_to_function_declared_later) <<
4467       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4468     Diag(UnparsedDefaultArgLocs[Param],
4469          diag::note_default_argument_declared_here);
4470     return true;
4471   }
4472   
4473   if (Param->hasUninstantiatedDefaultArg()) {
4474     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4475
4476     EnterExpressionEvaluationContext EvalContext(
4477         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4478
4479     // Instantiate the expression.
4480     MultiLevelTemplateArgumentList MutiLevelArgList
4481       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4482
4483     InstantiatingTemplate Inst(*this, CallLoc, Param,
4484                                MutiLevelArgList.getInnermost());
4485     if (Inst.isInvalid())
4486       return true;
4487     if (Inst.isAlreadyInstantiating()) {
4488       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4489       Param->setInvalidDecl();
4490       return true;
4491     }
4492
4493     ExprResult Result;
4494     {
4495       // C++ [dcl.fct.default]p5:
4496       //   The names in the [default argument] expression are bound, and
4497       //   the semantic constraints are checked, at the point where the
4498       //   default argument expression appears.
4499       ContextRAII SavedContext(*this, FD);
4500       LocalInstantiationScope Local(*this);
4501       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4502                                 /*DirectInit*/false);
4503     }
4504     if (Result.isInvalid())
4505       return true;
4506
4507     // Check the expression as an initializer for the parameter.
4508     InitializedEntity Entity
4509       = InitializedEntity::InitializeParameter(Context, Param);
4510     InitializationKind Kind
4511       = InitializationKind::CreateCopy(Param->getLocation(),
4512              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4513     Expr *ResultE = Result.getAs<Expr>();
4514
4515     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4516     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4517     if (Result.isInvalid())
4518       return true;
4519
4520     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4521                                  Param->getOuterLocStart());
4522     if (Result.isInvalid())
4523       return true;
4524
4525     // Remember the instantiated default argument.
4526     Param->setDefaultArg(Result.getAs<Expr>());
4527     if (ASTMutationListener *L = getASTMutationListener()) {
4528       L->DefaultArgumentInstantiated(Param);
4529     }
4530   }
4531
4532   // If the default argument expression is not set yet, we are building it now.
4533   if (!Param->hasInit()) {
4534     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4535     Param->setInvalidDecl();
4536     return true;
4537   }
4538
4539   // If the default expression creates temporaries, we need to
4540   // push them to the current stack of expression temporaries so they'll
4541   // be properly destroyed.
4542   // FIXME: We should really be rebuilding the default argument with new
4543   // bound temporaries; see the comment in PR5810.
4544   // We don't need to do that with block decls, though, because
4545   // blocks in default argument expression can never capture anything.
4546   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4547     // Set the "needs cleanups" bit regardless of whether there are
4548     // any explicit objects.
4549     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4550
4551     // Append all the objects to the cleanup list.  Right now, this
4552     // should always be a no-op, because blocks in default argument
4553     // expressions should never be able to capture anything.
4554     assert(!Init->getNumObjects() &&
4555            "default argument expression has capturing blocks?");
4556   }
4557
4558   // We already type-checked the argument, so we know it works. 
4559   // Just mark all of the declarations in this potentially-evaluated expression
4560   // as being "referenced".
4561   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4562                                    /*SkipLocalVariables=*/true);
4563   return false;
4564 }
4565
4566 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4567                                         FunctionDecl *FD, ParmVarDecl *Param) {
4568   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4569     return ExprError();
4570   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4571 }
4572
4573 Sema::VariadicCallType
4574 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4575                           Expr *Fn) {
4576   if (Proto && Proto->isVariadic()) {
4577     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4578       return VariadicConstructor;
4579     else if (Fn && Fn->getType()->isBlockPointerType())
4580       return VariadicBlock;
4581     else if (FDecl) {
4582       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4583         if (Method->isInstance())
4584           return VariadicMethod;
4585     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4586       return VariadicMethod;
4587     return VariadicFunction;
4588   }
4589   return VariadicDoesNotApply;
4590 }
4591
4592 namespace {
4593 class FunctionCallCCC : public FunctionCallFilterCCC {
4594 public:
4595   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4596                   unsigned NumArgs, MemberExpr *ME)
4597       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4598         FunctionName(FuncName) {}
4599
4600   bool ValidateCandidate(const TypoCorrection &candidate) override {
4601     if (!candidate.getCorrectionSpecifier() ||
4602         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4603       return false;
4604     }
4605
4606     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4607   }
4608
4609 private:
4610   const IdentifierInfo *const FunctionName;
4611 };
4612 }
4613
4614 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4615                                                FunctionDecl *FDecl,
4616                                                ArrayRef<Expr *> Args) {
4617   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4618   DeclarationName FuncName = FDecl->getDeclName();
4619   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4620
4621   if (TypoCorrection Corrected = S.CorrectTypo(
4622           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4623           S.getScopeForContext(S.CurContext), nullptr,
4624           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4625                                              Args.size(), ME),
4626           Sema::CTK_ErrorRecovery)) {
4627     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4628       if (Corrected.isOverloaded()) {
4629         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4630         OverloadCandidateSet::iterator Best;
4631         for (NamedDecl *CD : Corrected) {
4632           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4633             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4634                                    OCS);
4635         }
4636         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4637         case OR_Success:
4638           ND = Best->FoundDecl;
4639           Corrected.setCorrectionDecl(ND);
4640           break;
4641         default:
4642           break;
4643         }
4644       }
4645       ND = ND->getUnderlyingDecl();
4646       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4647         return Corrected;
4648     }
4649   }
4650   return TypoCorrection();
4651 }
4652
4653 /// ConvertArgumentsForCall - Converts the arguments specified in
4654 /// Args/NumArgs to the parameter types of the function FDecl with
4655 /// function prototype Proto. Call is the call expression itself, and
4656 /// Fn is the function expression. For a C++ member function, this
4657 /// routine does not attempt to convert the object argument. Returns
4658 /// true if the call is ill-formed.
4659 bool
4660 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4661                               FunctionDecl *FDecl,
4662                               const FunctionProtoType *Proto,
4663                               ArrayRef<Expr *> Args,
4664                               SourceLocation RParenLoc,
4665                               bool IsExecConfig) {
4666   // Bail out early if calling a builtin with custom typechecking.
4667   if (FDecl)
4668     if (unsigned ID = FDecl->getBuiltinID())
4669       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4670         return false;
4671
4672   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4673   // assignment, to the types of the corresponding parameter, ...
4674   unsigned NumParams = Proto->getNumParams();
4675   bool Invalid = false;
4676   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4677   unsigned FnKind = Fn->getType()->isBlockPointerType()
4678                        ? 1 /* block */
4679                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4680                                        : 0 /* function */);
4681
4682   // If too few arguments are available (and we don't have default
4683   // arguments for the remaining parameters), don't make the call.
4684   if (Args.size() < NumParams) {
4685     if (Args.size() < MinArgs) {
4686       TypoCorrection TC;
4687       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4688         unsigned diag_id =
4689             MinArgs == NumParams && !Proto->isVariadic()
4690                 ? diag::err_typecheck_call_too_few_args_suggest
4691                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4692         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4693                                         << static_cast<unsigned>(Args.size())
4694                                         << TC.getCorrectionRange());
4695       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4696         Diag(RParenLoc,
4697              MinArgs == NumParams && !Proto->isVariadic()
4698                  ? diag::err_typecheck_call_too_few_args_one
4699                  : diag::err_typecheck_call_too_few_args_at_least_one)
4700             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4701       else
4702         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4703                             ? diag::err_typecheck_call_too_few_args
4704                             : diag::err_typecheck_call_too_few_args_at_least)
4705             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4706             << Fn->getSourceRange();
4707
4708       // Emit the location of the prototype.
4709       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4710         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4711           << FDecl;
4712
4713       return true;
4714     }
4715     Call->setNumArgs(Context, NumParams);
4716   }
4717
4718   // If too many are passed and not variadic, error on the extras and drop
4719   // them.
4720   if (Args.size() > NumParams) {
4721     if (!Proto->isVariadic()) {
4722       TypoCorrection TC;
4723       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4724         unsigned diag_id =
4725             MinArgs == NumParams && !Proto->isVariadic()
4726                 ? diag::err_typecheck_call_too_many_args_suggest
4727                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4728         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4729                                         << static_cast<unsigned>(Args.size())
4730                                         << TC.getCorrectionRange());
4731       } else if (NumParams == 1 && FDecl &&
4732                  FDecl->getParamDecl(0)->getDeclName())
4733         Diag(Args[NumParams]->getLocStart(),
4734              MinArgs == NumParams
4735                  ? diag::err_typecheck_call_too_many_args_one
4736                  : diag::err_typecheck_call_too_many_args_at_most_one)
4737             << FnKind << FDecl->getParamDecl(0)
4738             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4739             << SourceRange(Args[NumParams]->getLocStart(),
4740                            Args.back()->getLocEnd());
4741       else
4742         Diag(Args[NumParams]->getLocStart(),
4743              MinArgs == NumParams
4744                  ? diag::err_typecheck_call_too_many_args
4745                  : diag::err_typecheck_call_too_many_args_at_most)
4746             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4747             << Fn->getSourceRange()
4748             << SourceRange(Args[NumParams]->getLocStart(),
4749                            Args.back()->getLocEnd());
4750
4751       // Emit the location of the prototype.
4752       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4753         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4754           << FDecl;
4755       
4756       // This deletes the extra arguments.
4757       Call->setNumArgs(Context, NumParams);
4758       return true;
4759     }
4760   }
4761   SmallVector<Expr *, 8> AllArgs;
4762   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4763   
4764   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4765                                    Proto, 0, Args, AllArgs, CallType);
4766   if (Invalid)
4767     return true;
4768   unsigned TotalNumArgs = AllArgs.size();
4769   for (unsigned i = 0; i < TotalNumArgs; ++i)
4770     Call->setArg(i, AllArgs[i]);
4771
4772   return false;
4773 }
4774
4775 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4776                                   const FunctionProtoType *Proto,
4777                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4778                                   SmallVectorImpl<Expr *> &AllArgs,
4779                                   VariadicCallType CallType, bool AllowExplicit,
4780                                   bool IsListInitialization) {
4781   unsigned NumParams = Proto->getNumParams();
4782   bool Invalid = false;
4783   size_t ArgIx = 0;
4784   // Continue to check argument types (even if we have too few/many args).
4785   for (unsigned i = FirstParam; i < NumParams; i++) {
4786     QualType ProtoArgType = Proto->getParamType(i);
4787
4788     Expr *Arg;
4789     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4790     if (ArgIx < Args.size()) {
4791       Arg = Args[ArgIx++];
4792
4793       if (RequireCompleteType(Arg->getLocStart(),
4794                               ProtoArgType,
4795                               diag::err_call_incomplete_argument, Arg))
4796         return true;
4797
4798       // Strip the unbridged-cast placeholder expression off, if applicable.
4799       bool CFAudited = false;
4800       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4801           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4802           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4803         Arg = stripARCUnbridgedCast(Arg);
4804       else if (getLangOpts().ObjCAutoRefCount &&
4805                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4806                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4807         CFAudited = true;
4808
4809       InitializedEntity Entity =
4810           Param ? InitializedEntity::InitializeParameter(Context, Param,
4811                                                          ProtoArgType)
4812                 : InitializedEntity::InitializeParameter(
4813                       Context, ProtoArgType, Proto->isParamConsumed(i));
4814
4815       // Remember that parameter belongs to a CF audited API.
4816       if (CFAudited)
4817         Entity.setParameterCFAudited();
4818
4819       ExprResult ArgE = PerformCopyInitialization(
4820           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4821       if (ArgE.isInvalid())
4822         return true;
4823
4824       Arg = ArgE.getAs<Expr>();
4825     } else {
4826       assert(Param && "can't use default arguments without a known callee");
4827
4828       ExprResult ArgExpr =
4829         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4830       if (ArgExpr.isInvalid())
4831         return true;
4832
4833       Arg = ArgExpr.getAs<Expr>();
4834     }
4835
4836     // Check for array bounds violations for each argument to the call. This
4837     // check only triggers warnings when the argument isn't a more complex Expr
4838     // with its own checking, such as a BinaryOperator.
4839     CheckArrayAccess(Arg);
4840
4841     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4842     CheckStaticArrayArgument(CallLoc, Param, Arg);
4843
4844     AllArgs.push_back(Arg);
4845   }
4846
4847   // If this is a variadic call, handle args passed through "...".
4848   if (CallType != VariadicDoesNotApply) {
4849     // Assume that extern "C" functions with variadic arguments that
4850     // return __unknown_anytype aren't *really* variadic.
4851     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4852         FDecl->isExternC()) {
4853       for (Expr *A : Args.slice(ArgIx)) {
4854         QualType paramType; // ignored
4855         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4856         Invalid |= arg.isInvalid();
4857         AllArgs.push_back(arg.get());
4858       }
4859
4860     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4861     } else {
4862       for (Expr *A : Args.slice(ArgIx)) {
4863         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4864         Invalid |= Arg.isInvalid();
4865         AllArgs.push_back(Arg.get());
4866       }
4867     }
4868
4869     // Check for array bounds violations.
4870     for (Expr *A : Args.slice(ArgIx))
4871       CheckArrayAccess(A);
4872   }
4873   return Invalid;
4874 }
4875
4876 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4877   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4878   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4879     TL = DTL.getOriginalLoc();
4880   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4881     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4882       << ATL.getLocalSourceRange();
4883 }
4884
4885 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4886 /// array parameter, check that it is non-null, and that if it is formed by
4887 /// array-to-pointer decay, the underlying array is sufficiently large.
4888 ///
4889 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4890 /// array type derivation, then for each call to the function, the value of the
4891 /// corresponding actual argument shall provide access to the first element of
4892 /// an array with at least as many elements as specified by the size expression.
4893 void
4894 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4895                                ParmVarDecl *Param,
4896                                const Expr *ArgExpr) {
4897   // Static array parameters are not supported in C++.
4898   if (!Param || getLangOpts().CPlusPlus)
4899     return;
4900
4901   QualType OrigTy = Param->getOriginalType();
4902
4903   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4904   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4905     return;
4906
4907   if (ArgExpr->isNullPointerConstant(Context,
4908                                      Expr::NPC_NeverValueDependent)) {
4909     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4910     DiagnoseCalleeStaticArrayParam(*this, Param);
4911     return;
4912   }
4913
4914   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4915   if (!CAT)
4916     return;
4917
4918   const ConstantArrayType *ArgCAT =
4919     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4920   if (!ArgCAT)
4921     return;
4922
4923   if (ArgCAT->getSize().ult(CAT->getSize())) {
4924     Diag(CallLoc, diag::warn_static_array_too_small)
4925       << ArgExpr->getSourceRange()
4926       << (unsigned) ArgCAT->getSize().getZExtValue()
4927       << (unsigned) CAT->getSize().getZExtValue();
4928     DiagnoseCalleeStaticArrayParam(*this, Param);
4929   }
4930 }
4931
4932 /// Given a function expression of unknown-any type, try to rebuild it
4933 /// to have a function type.
4934 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4935
4936 /// Is the given type a placeholder that we need to lower out
4937 /// immediately during argument processing?
4938 static bool isPlaceholderToRemoveAsArg(QualType type) {
4939   // Placeholders are never sugared.
4940   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4941   if (!placeholder) return false;
4942
4943   switch (placeholder->getKind()) {
4944   // Ignore all the non-placeholder types.
4945 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4946   case BuiltinType::Id:
4947 #include "clang/Basic/OpenCLImageTypes.def"
4948 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4949 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4950 #include "clang/AST/BuiltinTypes.def"
4951     return false;
4952
4953   // We cannot lower out overload sets; they might validly be resolved
4954   // by the call machinery.
4955   case BuiltinType::Overload:
4956     return false;
4957
4958   // Unbridged casts in ARC can be handled in some call positions and
4959   // should be left in place.
4960   case BuiltinType::ARCUnbridgedCast:
4961     return false;
4962
4963   // Pseudo-objects should be converted as soon as possible.
4964   case BuiltinType::PseudoObject:
4965     return true;
4966
4967   // The debugger mode could theoretically but currently does not try
4968   // to resolve unknown-typed arguments based on known parameter types.
4969   case BuiltinType::UnknownAny:
4970     return true;
4971
4972   // These are always invalid as call arguments and should be reported.
4973   case BuiltinType::BoundMember:
4974   case BuiltinType::BuiltinFn:
4975   case BuiltinType::OMPArraySection:
4976     return true;
4977
4978   }
4979   llvm_unreachable("bad builtin type kind");
4980 }
4981
4982 /// Check an argument list for placeholders that we won't try to
4983 /// handle later.
4984 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4985   // Apply this processing to all the arguments at once instead of
4986   // dying at the first failure.
4987   bool hasInvalid = false;
4988   for (size_t i = 0, e = args.size(); i != e; i++) {
4989     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4990       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4991       if (result.isInvalid()) hasInvalid = true;
4992       else args[i] = result.get();
4993     } else if (hasInvalid) {
4994       (void)S.CorrectDelayedTyposInExpr(args[i]);
4995     }
4996   }
4997   return hasInvalid;
4998 }
4999
5000 /// If a builtin function has a pointer argument with no explicit address
5001 /// space, then it should be able to accept a pointer to any address
5002 /// space as input.  In order to do this, we need to replace the
5003 /// standard builtin declaration with one that uses the same address space
5004 /// as the call.
5005 ///
5006 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5007 ///                  it does not contain any pointer arguments without
5008 ///                  an address space qualifer.  Otherwise the rewritten
5009 ///                  FunctionDecl is returned.
5010 /// TODO: Handle pointer return types.
5011 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5012                                                 const FunctionDecl *FDecl,
5013                                                 MultiExprArg ArgExprs) {
5014
5015   QualType DeclType = FDecl->getType();
5016   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5017
5018   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5019       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5020     return nullptr;
5021
5022   bool NeedsNewDecl = false;
5023   unsigned i = 0;
5024   SmallVector<QualType, 8> OverloadParams;
5025
5026   for (QualType ParamType : FT->param_types()) {
5027
5028     // Convert array arguments to pointer to simplify type lookup.
5029     ExprResult ArgRes =
5030         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5031     if (ArgRes.isInvalid())
5032       return nullptr;
5033     Expr *Arg = ArgRes.get();
5034     QualType ArgType = Arg->getType();
5035     if (!ParamType->isPointerType() ||
5036         ParamType.getQualifiers().hasAddressSpace() ||
5037         !ArgType->isPointerType() ||
5038         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5039       OverloadParams.push_back(ParamType);
5040       continue;
5041     }
5042
5043     NeedsNewDecl = true;
5044     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5045
5046     QualType PointeeType = ParamType->getPointeeType();
5047     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5048     OverloadParams.push_back(Context.getPointerType(PointeeType));
5049   }
5050
5051   if (!NeedsNewDecl)
5052     return nullptr;
5053
5054   FunctionProtoType::ExtProtoInfo EPI;
5055   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5056                                                 OverloadParams, EPI);
5057   DeclContext *Parent = Context.getTranslationUnitDecl();
5058   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5059                                                     FDecl->getLocation(),
5060                                                     FDecl->getLocation(),
5061                                                     FDecl->getIdentifier(),
5062                                                     OverloadTy,
5063                                                     /*TInfo=*/nullptr,
5064                                                     SC_Extern, false,
5065                                                     /*hasPrototype=*/true);
5066   SmallVector<ParmVarDecl*, 16> Params;
5067   FT = cast<FunctionProtoType>(OverloadTy);
5068   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5069     QualType ParamType = FT->getParamType(i);
5070     ParmVarDecl *Parm =
5071         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5072                                 SourceLocation(), nullptr, ParamType,
5073                                 /*TInfo=*/nullptr, SC_None, nullptr);
5074     Parm->setScopeInfo(0, i);
5075     Params.push_back(Parm);
5076   }
5077   OverloadDecl->setParams(Params);
5078   return OverloadDecl;
5079 }
5080
5081 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5082                                     FunctionDecl *Callee,
5083                                     MultiExprArg ArgExprs) {
5084   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5085   // similar attributes) really don't like it when functions are called with an
5086   // invalid number of args.
5087   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5088                          /*PartialOverloading=*/false) &&
5089       !Callee->isVariadic())
5090     return;
5091   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5092     return;
5093
5094   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5095     S.Diag(Fn->getLocStart(),
5096            isa<CXXMethodDecl>(Callee)
5097                ? diag::err_ovl_no_viable_member_function_in_call
5098                : diag::err_ovl_no_viable_function_in_call)
5099         << Callee << Callee->getSourceRange();
5100     S.Diag(Callee->getLocation(),
5101            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5102         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5103     return;
5104   }
5105 }
5106
5107 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5108 /// This provides the location of the left/right parens and a list of comma
5109 /// locations.
5110 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5111                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5112                                Expr *ExecConfig, bool IsExecConfig) {
5113   // Since this might be a postfix expression, get rid of ParenListExprs.
5114   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5115   if (Result.isInvalid()) return ExprError();
5116   Fn = Result.get();
5117
5118   if (checkArgsForPlaceholders(*this, ArgExprs))
5119     return ExprError();
5120
5121   if (getLangOpts().CPlusPlus) {
5122     // If this is a pseudo-destructor expression, build the call immediately.
5123     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5124       if (!ArgExprs.empty()) {
5125         // Pseudo-destructor calls should not have any arguments.
5126         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5127             << FixItHint::CreateRemoval(
5128                    SourceRange(ArgExprs.front()->getLocStart(),
5129                                ArgExprs.back()->getLocEnd()));
5130       }
5131
5132       return new (Context)
5133           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5134     }
5135     if (Fn->getType() == Context.PseudoObjectTy) {
5136       ExprResult result = CheckPlaceholderExpr(Fn);
5137       if (result.isInvalid()) return ExprError();
5138       Fn = result.get();
5139     }
5140
5141     // Determine whether this is a dependent call inside a C++ template,
5142     // in which case we won't do any semantic analysis now.
5143     bool Dependent = false;
5144     if (Fn->isTypeDependent())
5145       Dependent = true;
5146     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5147       Dependent = true;
5148
5149     if (Dependent) {
5150       if (ExecConfig) {
5151         return new (Context) CUDAKernelCallExpr(
5152             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5153             Context.DependentTy, VK_RValue, RParenLoc);
5154       } else {
5155         return new (Context) CallExpr(
5156             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5157       }
5158     }
5159
5160     // Determine whether this is a call to an object (C++ [over.call.object]).
5161     if (Fn->getType()->isRecordType())
5162       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5163                                           RParenLoc);
5164
5165     if (Fn->getType() == Context.UnknownAnyTy) {
5166       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5167       if (result.isInvalid()) return ExprError();
5168       Fn = result.get();
5169     }
5170
5171     if (Fn->getType() == Context.BoundMemberTy) {
5172       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5173                                        RParenLoc);
5174     }
5175   }
5176
5177   // Check for overloaded calls.  This can happen even in C due to extensions.
5178   if (Fn->getType() == Context.OverloadTy) {
5179     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5180
5181     // We aren't supposed to apply this logic if there's an '&' involved.
5182     if (!find.HasFormOfMemberPointer) {
5183       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5184         return new (Context) CallExpr(
5185             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5186       OverloadExpr *ovl = find.Expression;
5187       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5188         return BuildOverloadedCallExpr(
5189             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5190             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5191       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5192                                        RParenLoc);
5193     }
5194   }
5195
5196   // If we're directly calling a function, get the appropriate declaration.
5197   if (Fn->getType() == Context.UnknownAnyTy) {
5198     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5199     if (result.isInvalid()) return ExprError();
5200     Fn = result.get();
5201   }
5202
5203   Expr *NakedFn = Fn->IgnoreParens();
5204
5205   bool CallingNDeclIndirectly = false;
5206   NamedDecl *NDecl = nullptr;
5207   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5208     if (UnOp->getOpcode() == UO_AddrOf) {
5209       CallingNDeclIndirectly = true;
5210       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5211     }
5212   }
5213
5214   if (isa<DeclRefExpr>(NakedFn)) {
5215     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5216
5217     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5218     if (FDecl && FDecl->getBuiltinID()) {
5219       // Rewrite the function decl for this builtin by replacing parameters
5220       // with no explicit address space with the address space of the arguments
5221       // in ArgExprs.
5222       if ((FDecl =
5223                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5224         NDecl = FDecl;
5225         Fn = DeclRefExpr::Create(
5226             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5227             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5228       }
5229     }
5230   } else if (isa<MemberExpr>(NakedFn))
5231     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5232
5233   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5234     if (CallingNDeclIndirectly &&
5235         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5236                                            Fn->getLocStart()))
5237       return ExprError();
5238
5239     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5240       return ExprError();
5241
5242     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5243   }
5244
5245   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5246                                ExecConfig, IsExecConfig);
5247 }
5248
5249 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5250 ///
5251 /// __builtin_astype( value, dst type )
5252 ///
5253 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5254                                  SourceLocation BuiltinLoc,
5255                                  SourceLocation RParenLoc) {
5256   ExprValueKind VK = VK_RValue;
5257   ExprObjectKind OK = OK_Ordinary;
5258   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5259   QualType SrcTy = E->getType();
5260   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5261     return ExprError(Diag(BuiltinLoc,
5262                           diag::err_invalid_astype_of_different_size)
5263                      << DstTy
5264                      << SrcTy
5265                      << E->getSourceRange());
5266   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5267 }
5268
5269 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5270 /// provided arguments.
5271 ///
5272 /// __builtin_convertvector( value, dst type )
5273 ///
5274 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5275                                         SourceLocation BuiltinLoc,
5276                                         SourceLocation RParenLoc) {
5277   TypeSourceInfo *TInfo;
5278   GetTypeFromParser(ParsedDestTy, &TInfo);
5279   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5280 }
5281
5282 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5283 /// i.e. an expression not of \p OverloadTy.  The expression should
5284 /// unary-convert to an expression of function-pointer or
5285 /// block-pointer type.
5286 ///
5287 /// \param NDecl the declaration being called, if available
5288 ExprResult
5289 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5290                             SourceLocation LParenLoc,
5291                             ArrayRef<Expr *> Args,
5292                             SourceLocation RParenLoc,
5293                             Expr *Config, bool IsExecConfig) {
5294   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5295   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5296
5297   // Functions with 'interrupt' attribute cannot be called directly.
5298   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5299     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5300     return ExprError();
5301   }
5302
5303   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5304   // so there's some risk when calling out to non-interrupt handler functions
5305   // that the callee might not preserve them. This is easy to diagnose here,
5306   // but can be very challenging to debug.
5307   if (auto *Caller = getCurFunctionDecl())
5308     if (Caller->hasAttr<ARMInterruptAttr>()) {
5309       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5310       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5311         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5312     }
5313
5314   // Promote the function operand.
5315   // We special-case function promotion here because we only allow promoting
5316   // builtin functions to function pointers in the callee of a call.
5317   ExprResult Result;
5318   if (BuiltinID &&
5319       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5320     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5321                                CK_BuiltinFnToFnPtr).get();
5322   } else {
5323     Result = CallExprUnaryConversions(Fn);
5324   }
5325   if (Result.isInvalid())
5326     return ExprError();
5327   Fn = Result.get();
5328
5329   // Make the call expr early, before semantic checks.  This guarantees cleanup
5330   // of arguments and function on error.
5331   CallExpr *TheCall;
5332   if (Config)
5333     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5334                                                cast<CallExpr>(Config), Args,
5335                                                Context.BoolTy, VK_RValue,
5336                                                RParenLoc);
5337   else
5338     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5339                                      VK_RValue, RParenLoc);
5340
5341   if (!getLangOpts().CPlusPlus) {
5342     // C cannot always handle TypoExpr nodes in builtin calls and direct
5343     // function calls as their argument checking don't necessarily handle
5344     // dependent types properly, so make sure any TypoExprs have been
5345     // dealt with.
5346     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5347     if (!Result.isUsable()) return ExprError();
5348     TheCall = dyn_cast<CallExpr>(Result.get());
5349     if (!TheCall) return Result;
5350     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5351   }
5352
5353   // Bail out early if calling a builtin with custom typechecking.
5354   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5355     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5356
5357  retry:
5358   const FunctionType *FuncT;
5359   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5360     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5361     // have type pointer to function".
5362     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5363     if (!FuncT)
5364       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5365                          << Fn->getType() << Fn->getSourceRange());
5366   } else if (const BlockPointerType *BPT =
5367                Fn->getType()->getAs<BlockPointerType>()) {
5368     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5369   } else {
5370     // Handle calls to expressions of unknown-any type.
5371     if (Fn->getType() == Context.UnknownAnyTy) {
5372       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5373       if (rewrite.isInvalid()) return ExprError();
5374       Fn = rewrite.get();
5375       TheCall->setCallee(Fn);
5376       goto retry;
5377     }
5378
5379     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5380       << Fn->getType() << Fn->getSourceRange());
5381   }
5382
5383   if (getLangOpts().CUDA) {
5384     if (Config) {
5385       // CUDA: Kernel calls must be to global functions
5386       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5387         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5388             << FDecl->getName() << Fn->getSourceRange());
5389
5390       // CUDA: Kernel function must have 'void' return type
5391       if (!FuncT->getReturnType()->isVoidType())
5392         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5393             << Fn->getType() << Fn->getSourceRange());
5394     } else {
5395       // CUDA: Calls to global functions must be configured
5396       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5397         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5398             << FDecl->getName() << Fn->getSourceRange());
5399     }
5400   }
5401
5402   // Check for a valid return type
5403   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5404                           FDecl))
5405     return ExprError();
5406
5407   // We know the result type of the call, set it.
5408   TheCall->setType(FuncT->getCallResultType(Context));
5409   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5410
5411   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5412   if (Proto) {
5413     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5414                                 IsExecConfig))
5415       return ExprError();
5416   } else {
5417     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5418
5419     if (FDecl) {
5420       // Check if we have too few/too many template arguments, based
5421       // on our knowledge of the function definition.
5422       const FunctionDecl *Def = nullptr;
5423       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5424         Proto = Def->getType()->getAs<FunctionProtoType>();
5425        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5426           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5427           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5428       }
5429       
5430       // If the function we're calling isn't a function prototype, but we have
5431       // a function prototype from a prior declaratiom, use that prototype.
5432       if (!FDecl->hasPrototype())
5433         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5434     }
5435
5436     // Promote the arguments (C99 6.5.2.2p6).
5437     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5438       Expr *Arg = Args[i];
5439
5440       if (Proto && i < Proto->getNumParams()) {
5441         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5442             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5443         ExprResult ArgE =
5444             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5445         if (ArgE.isInvalid())
5446           return true;
5447         
5448         Arg = ArgE.getAs<Expr>();
5449
5450       } else {
5451         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5452
5453         if (ArgE.isInvalid())
5454           return true;
5455
5456         Arg = ArgE.getAs<Expr>();
5457       }
5458       
5459       if (RequireCompleteType(Arg->getLocStart(),
5460                               Arg->getType(),
5461                               diag::err_call_incomplete_argument, Arg))
5462         return ExprError();
5463
5464       TheCall->setArg(i, Arg);
5465     }
5466   }
5467
5468   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5469     if (!Method->isStatic())
5470       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5471         << Fn->getSourceRange());
5472
5473   // Check for sentinels
5474   if (NDecl)
5475     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5476
5477   // Do special checking on direct calls to functions.
5478   if (FDecl) {
5479     if (CheckFunctionCall(FDecl, TheCall, Proto))
5480       return ExprError();
5481
5482     if (BuiltinID)
5483       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5484   } else if (NDecl) {
5485     if (CheckPointerCall(NDecl, TheCall, Proto))
5486       return ExprError();
5487   } else {
5488     if (CheckOtherCall(TheCall, Proto))
5489       return ExprError();
5490   }
5491
5492   return MaybeBindToTemporary(TheCall);
5493 }
5494
5495 ExprResult
5496 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5497                            SourceLocation RParenLoc, Expr *InitExpr) {
5498   assert(Ty && "ActOnCompoundLiteral(): missing type");
5499   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5500
5501   TypeSourceInfo *TInfo;
5502   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5503   if (!TInfo)
5504     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5505
5506   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5507 }
5508
5509 ExprResult
5510 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5511                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5512   QualType literalType = TInfo->getType();
5513
5514   if (literalType->isArrayType()) {
5515     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5516           diag::err_illegal_decl_array_incomplete_type,
5517           SourceRange(LParenLoc,
5518                       LiteralExpr->getSourceRange().getEnd())))
5519       return ExprError();
5520     if (literalType->isVariableArrayType())
5521       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5522         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5523   } else if (!literalType->isDependentType() &&
5524              RequireCompleteType(LParenLoc, literalType,
5525                diag::err_typecheck_decl_incomplete_type,
5526                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5527     return ExprError();
5528
5529   InitializedEntity Entity
5530     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5531   InitializationKind Kind
5532     = InitializationKind::CreateCStyleCast(LParenLoc, 
5533                                            SourceRange(LParenLoc, RParenLoc),
5534                                            /*InitList=*/true);
5535   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5536   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5537                                       &literalType);
5538   if (Result.isInvalid())
5539     return ExprError();
5540   LiteralExpr = Result.get();
5541
5542   bool isFileScope = !CurContext->isFunctionOrMethod();
5543   if (isFileScope &&
5544       !LiteralExpr->isTypeDependent() &&
5545       !LiteralExpr->isValueDependent() &&
5546       !literalType->isDependentType()) { // 6.5.2.5p3
5547     if (CheckForConstantInitializer(LiteralExpr, literalType))
5548       return ExprError();
5549   }
5550
5551   // In C, compound literals are l-values for some reason.
5552   // For GCC compatibility, in C++, file-scope array compound literals with
5553   // constant initializers are also l-values, and compound literals are
5554   // otherwise prvalues.
5555   //
5556   // (GCC also treats C++ list-initialized file-scope array prvalues with
5557   // constant initializers as l-values, but that's non-conforming, so we don't
5558   // follow it there.)
5559   //
5560   // FIXME: It would be better to handle the lvalue cases as materializing and
5561   // lifetime-extending a temporary object, but our materialized temporaries
5562   // representation only supports lifetime extension from a variable, not "out
5563   // of thin air".
5564   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5565   // is bound to the result of applying array-to-pointer decay to the compound
5566   // literal.
5567   // FIXME: GCC supports compound literals of reference type, which should
5568   // obviously have a value kind derived from the kind of reference involved.
5569   ExprValueKind VK =
5570       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5571           ? VK_RValue
5572           : VK_LValue;
5573
5574   return MaybeBindToTemporary(
5575       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5576                                         VK, LiteralExpr, isFileScope));
5577 }
5578
5579 ExprResult
5580 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5581                     SourceLocation RBraceLoc) {
5582   // Immediately handle non-overload placeholders.  Overloads can be
5583   // resolved contextually, but everything else here can't.
5584   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5585     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5586       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5587
5588       // Ignore failures; dropping the entire initializer list because
5589       // of one failure would be terrible for indexing/etc.
5590       if (result.isInvalid()) continue;
5591
5592       InitArgList[I] = result.get();
5593     }
5594   }
5595
5596   // Semantic analysis for initializers is done by ActOnDeclarator() and
5597   // CheckInitializer() - it requires knowledge of the object being intialized.
5598
5599   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5600                                                RBraceLoc);
5601   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5602   return E;
5603 }
5604
5605 /// Do an explicit extend of the given block pointer if we're in ARC.
5606 void Sema::maybeExtendBlockObject(ExprResult &E) {
5607   assert(E.get()->getType()->isBlockPointerType());
5608   assert(E.get()->isRValue());
5609
5610   // Only do this in an r-value context.
5611   if (!getLangOpts().ObjCAutoRefCount) return;
5612
5613   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5614                                CK_ARCExtendBlockObject, E.get(),
5615                                /*base path*/ nullptr, VK_RValue);
5616   Cleanup.setExprNeedsCleanups(true);
5617 }
5618
5619 /// Prepare a conversion of the given expression to an ObjC object
5620 /// pointer type.
5621 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5622   QualType type = E.get()->getType();
5623   if (type->isObjCObjectPointerType()) {
5624     return CK_BitCast;
5625   } else if (type->isBlockPointerType()) {
5626     maybeExtendBlockObject(E);
5627     return CK_BlockPointerToObjCPointerCast;
5628   } else {
5629     assert(type->isPointerType());
5630     return CK_CPointerToObjCPointerCast;
5631   }
5632 }
5633
5634 /// Prepares for a scalar cast, performing all the necessary stages
5635 /// except the final cast and returning the kind required.
5636 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5637   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5638   // Also, callers should have filtered out the invalid cases with
5639   // pointers.  Everything else should be possible.
5640
5641   QualType SrcTy = Src.get()->getType();
5642   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5643     return CK_NoOp;
5644
5645   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5646   case Type::STK_MemberPointer:
5647     llvm_unreachable("member pointer type in C");
5648
5649   case Type::STK_CPointer:
5650   case Type::STK_BlockPointer:
5651   case Type::STK_ObjCObjectPointer:
5652     switch (DestTy->getScalarTypeKind()) {
5653     case Type::STK_CPointer: {
5654       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5655       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5656       if (SrcAS != DestAS)
5657         return CK_AddressSpaceConversion;
5658       return CK_BitCast;
5659     }
5660     case Type::STK_BlockPointer:
5661       return (SrcKind == Type::STK_BlockPointer
5662                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5663     case Type::STK_ObjCObjectPointer:
5664       if (SrcKind == Type::STK_ObjCObjectPointer)
5665         return CK_BitCast;
5666       if (SrcKind == Type::STK_CPointer)
5667         return CK_CPointerToObjCPointerCast;
5668       maybeExtendBlockObject(Src);
5669       return CK_BlockPointerToObjCPointerCast;
5670     case Type::STK_Bool:
5671       return CK_PointerToBoolean;
5672     case Type::STK_Integral:
5673       return CK_PointerToIntegral;
5674     case Type::STK_Floating:
5675     case Type::STK_FloatingComplex:
5676     case Type::STK_IntegralComplex:
5677     case Type::STK_MemberPointer:
5678       llvm_unreachable("illegal cast from pointer");
5679     }
5680     llvm_unreachable("Should have returned before this");
5681
5682   case Type::STK_Bool: // casting from bool is like casting from an integer
5683   case Type::STK_Integral:
5684     switch (DestTy->getScalarTypeKind()) {
5685     case Type::STK_CPointer:
5686     case Type::STK_ObjCObjectPointer:
5687     case Type::STK_BlockPointer:
5688       if (Src.get()->isNullPointerConstant(Context,
5689                                            Expr::NPC_ValueDependentIsNull))
5690         return CK_NullToPointer;
5691       return CK_IntegralToPointer;
5692     case Type::STK_Bool:
5693       return CK_IntegralToBoolean;
5694     case Type::STK_Integral:
5695       return CK_IntegralCast;
5696     case Type::STK_Floating:
5697       return CK_IntegralToFloating;
5698     case Type::STK_IntegralComplex:
5699       Src = ImpCastExprToType(Src.get(),
5700                       DestTy->castAs<ComplexType>()->getElementType(),
5701                       CK_IntegralCast);
5702       return CK_IntegralRealToComplex;
5703     case Type::STK_FloatingComplex:
5704       Src = ImpCastExprToType(Src.get(),
5705                       DestTy->castAs<ComplexType>()->getElementType(),
5706                       CK_IntegralToFloating);
5707       return CK_FloatingRealToComplex;
5708     case Type::STK_MemberPointer:
5709       llvm_unreachable("member pointer type in C");
5710     }
5711     llvm_unreachable("Should have returned before this");
5712
5713   case Type::STK_Floating:
5714     switch (DestTy->getScalarTypeKind()) {
5715     case Type::STK_Floating:
5716       return CK_FloatingCast;
5717     case Type::STK_Bool:
5718       return CK_FloatingToBoolean;
5719     case Type::STK_Integral:
5720       return CK_FloatingToIntegral;
5721     case Type::STK_FloatingComplex:
5722       Src = ImpCastExprToType(Src.get(),
5723                               DestTy->castAs<ComplexType>()->getElementType(),
5724                               CK_FloatingCast);
5725       return CK_FloatingRealToComplex;
5726     case Type::STK_IntegralComplex:
5727       Src = ImpCastExprToType(Src.get(),
5728                               DestTy->castAs<ComplexType>()->getElementType(),
5729                               CK_FloatingToIntegral);
5730       return CK_IntegralRealToComplex;
5731     case Type::STK_CPointer:
5732     case Type::STK_ObjCObjectPointer:
5733     case Type::STK_BlockPointer:
5734       llvm_unreachable("valid float->pointer cast?");
5735     case Type::STK_MemberPointer:
5736       llvm_unreachable("member pointer type in C");
5737     }
5738     llvm_unreachable("Should have returned before this");
5739
5740   case Type::STK_FloatingComplex:
5741     switch (DestTy->getScalarTypeKind()) {
5742     case Type::STK_FloatingComplex:
5743       return CK_FloatingComplexCast;
5744     case Type::STK_IntegralComplex:
5745       return CK_FloatingComplexToIntegralComplex;
5746     case Type::STK_Floating: {
5747       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5748       if (Context.hasSameType(ET, DestTy))
5749         return CK_FloatingComplexToReal;
5750       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5751       return CK_FloatingCast;
5752     }
5753     case Type::STK_Bool:
5754       return CK_FloatingComplexToBoolean;
5755     case Type::STK_Integral:
5756       Src = ImpCastExprToType(Src.get(),
5757                               SrcTy->castAs<ComplexType>()->getElementType(),
5758                               CK_FloatingComplexToReal);
5759       return CK_FloatingToIntegral;
5760     case Type::STK_CPointer:
5761     case Type::STK_ObjCObjectPointer:
5762     case Type::STK_BlockPointer:
5763       llvm_unreachable("valid complex float->pointer cast?");
5764     case Type::STK_MemberPointer:
5765       llvm_unreachable("member pointer type in C");
5766     }
5767     llvm_unreachable("Should have returned before this");
5768
5769   case Type::STK_IntegralComplex:
5770     switch (DestTy->getScalarTypeKind()) {
5771     case Type::STK_FloatingComplex:
5772       return CK_IntegralComplexToFloatingComplex;
5773     case Type::STK_IntegralComplex:
5774       return CK_IntegralComplexCast;
5775     case Type::STK_Integral: {
5776       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5777       if (Context.hasSameType(ET, DestTy))
5778         return CK_IntegralComplexToReal;
5779       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5780       return CK_IntegralCast;
5781     }
5782     case Type::STK_Bool:
5783       return CK_IntegralComplexToBoolean;
5784     case Type::STK_Floating:
5785       Src = ImpCastExprToType(Src.get(),
5786                               SrcTy->castAs<ComplexType>()->getElementType(),
5787                               CK_IntegralComplexToReal);
5788       return CK_IntegralToFloating;
5789     case Type::STK_CPointer:
5790     case Type::STK_ObjCObjectPointer:
5791     case Type::STK_BlockPointer:
5792       llvm_unreachable("valid complex int->pointer cast?");
5793     case Type::STK_MemberPointer:
5794       llvm_unreachable("member pointer type in C");
5795     }
5796     llvm_unreachable("Should have returned before this");
5797   }
5798
5799   llvm_unreachable("Unhandled scalar cast");
5800 }
5801
5802 static bool breakDownVectorType(QualType type, uint64_t &len,
5803                                 QualType &eltType) {
5804   // Vectors are simple.
5805   if (const VectorType *vecType = type->getAs<VectorType>()) {
5806     len = vecType->getNumElements();
5807     eltType = vecType->getElementType();
5808     assert(eltType->isScalarType());
5809     return true;
5810   }
5811   
5812   // We allow lax conversion to and from non-vector types, but only if
5813   // they're real types (i.e. non-complex, non-pointer scalar types).
5814   if (!type->isRealType()) return false;
5815   
5816   len = 1;
5817   eltType = type;
5818   return true;
5819 }
5820
5821 /// Are the two types lax-compatible vector types?  That is, given
5822 /// that one of them is a vector, do they have equal storage sizes,
5823 /// where the storage size is the number of elements times the element
5824 /// size?
5825 ///
5826 /// This will also return false if either of the types is neither a
5827 /// vector nor a real type.
5828 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5829   assert(destTy->isVectorType() || srcTy->isVectorType());
5830   
5831   // Disallow lax conversions between scalars and ExtVectors (these
5832   // conversions are allowed for other vector types because common headers
5833   // depend on them).  Most scalar OP ExtVector cases are handled by the
5834   // splat path anyway, which does what we want (convert, not bitcast).
5835   // What this rules out for ExtVectors is crazy things like char4*float.
5836   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5837   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5838
5839   uint64_t srcLen, destLen;
5840   QualType srcEltTy, destEltTy;
5841   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5842   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5843   
5844   // ASTContext::getTypeSize will return the size rounded up to a
5845   // power of 2, so instead of using that, we need to use the raw
5846   // element size multiplied by the element count.
5847   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5848   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5849   
5850   return (srcLen * srcEltSize == destLen * destEltSize);
5851 }
5852
5853 /// Is this a legal conversion between two types, one of which is
5854 /// known to be a vector type?
5855 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5856   assert(destTy->isVectorType() || srcTy->isVectorType());
5857   
5858   if (!Context.getLangOpts().LaxVectorConversions)
5859     return false;
5860   return areLaxCompatibleVectorTypes(srcTy, destTy);
5861 }
5862
5863 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5864                            CastKind &Kind) {
5865   assert(VectorTy->isVectorType() && "Not a vector type!");
5866
5867   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5868     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5869       return Diag(R.getBegin(),
5870                   Ty->isVectorType() ?
5871                   diag::err_invalid_conversion_between_vectors :
5872                   diag::err_invalid_conversion_between_vector_and_integer)
5873         << VectorTy << Ty << R;
5874   } else
5875     return Diag(R.getBegin(),
5876                 diag::err_invalid_conversion_between_vector_and_scalar)
5877       << VectorTy << Ty << R;
5878
5879   Kind = CK_BitCast;
5880   return false;
5881 }
5882
5883 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5884   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5885
5886   if (DestElemTy == SplattedExpr->getType())
5887     return SplattedExpr;
5888
5889   assert(DestElemTy->isFloatingType() ||
5890          DestElemTy->isIntegralOrEnumerationType());
5891
5892   CastKind CK;
5893   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5894     // OpenCL requires that we convert `true` boolean expressions to -1, but
5895     // only when splatting vectors.
5896     if (DestElemTy->isFloatingType()) {
5897       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5898       // in two steps: boolean to signed integral, then to floating.
5899       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5900                                                  CK_BooleanToSignedIntegral);
5901       SplattedExpr = CastExprRes.get();
5902       CK = CK_IntegralToFloating;
5903     } else {
5904       CK = CK_BooleanToSignedIntegral;
5905     }
5906   } else {
5907     ExprResult CastExprRes = SplattedExpr;
5908     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5909     if (CastExprRes.isInvalid())
5910       return ExprError();
5911     SplattedExpr = CastExprRes.get();
5912   }
5913   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5914 }
5915
5916 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5917                                     Expr *CastExpr, CastKind &Kind) {
5918   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5919
5920   QualType SrcTy = CastExpr->getType();
5921
5922   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5923   // an ExtVectorType.
5924   // In OpenCL, casts between vectors of different types are not allowed.
5925   // (See OpenCL 6.2).
5926   if (SrcTy->isVectorType()) {
5927     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5928         || (getLangOpts().OpenCL &&
5929             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5930       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5931         << DestTy << SrcTy << R;
5932       return ExprError();
5933     }
5934     Kind = CK_BitCast;
5935     return CastExpr;
5936   }
5937
5938   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5939   // conversion will take place first from scalar to elt type, and then
5940   // splat from elt type to vector.
5941   if (SrcTy->isPointerType())
5942     return Diag(R.getBegin(),
5943                 diag::err_invalid_conversion_between_vector_and_scalar)
5944       << DestTy << SrcTy << R;
5945
5946   Kind = CK_VectorSplat;
5947   return prepareVectorSplat(DestTy, CastExpr);
5948 }
5949
5950 ExprResult
5951 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5952                     Declarator &D, ParsedType &Ty,
5953                     SourceLocation RParenLoc, Expr *CastExpr) {
5954   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5955          "ActOnCastExpr(): missing type or expr");
5956
5957   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5958   if (D.isInvalidType())
5959     return ExprError();
5960
5961   if (getLangOpts().CPlusPlus) {
5962     // Check that there are no default arguments (C++ only).
5963     CheckExtraCXXDefaultArguments(D);
5964   } else {
5965     // Make sure any TypoExprs have been dealt with.
5966     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5967     if (!Res.isUsable())
5968       return ExprError();
5969     CastExpr = Res.get();
5970   }
5971
5972   checkUnusedDeclAttributes(D);
5973
5974   QualType castType = castTInfo->getType();
5975   Ty = CreateParsedType(castType, castTInfo);
5976
5977   bool isVectorLiteral = false;
5978
5979   // Check for an altivec or OpenCL literal,
5980   // i.e. all the elements are integer constants.
5981   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5982   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5983   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5984        && castType->isVectorType() && (PE || PLE)) {
5985     if (PLE && PLE->getNumExprs() == 0) {
5986       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5987       return ExprError();
5988     }
5989     if (PE || PLE->getNumExprs() == 1) {
5990       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5991       if (!E->getType()->isVectorType())
5992         isVectorLiteral = true;
5993     }
5994     else
5995       isVectorLiteral = true;
5996   }
5997
5998   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5999   // then handle it as such.
6000   if (isVectorLiteral)
6001     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6002
6003   // If the Expr being casted is a ParenListExpr, handle it specially.
6004   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6005   // sequence of BinOp comma operators.
6006   if (isa<ParenListExpr>(CastExpr)) {
6007     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6008     if (Result.isInvalid()) return ExprError();
6009     CastExpr = Result.get();
6010   }
6011
6012   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6013       !getSourceManager().isInSystemMacro(LParenLoc))
6014     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6015   
6016   CheckTollFreeBridgeCast(castType, CastExpr);
6017   
6018   CheckObjCBridgeRelatedCast(castType, CastExpr);
6019
6020   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6021
6022   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6023 }
6024
6025 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6026                                     SourceLocation RParenLoc, Expr *E,
6027                                     TypeSourceInfo *TInfo) {
6028   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6029          "Expected paren or paren list expression");
6030
6031   Expr **exprs;
6032   unsigned numExprs;
6033   Expr *subExpr;
6034   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6035   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6036     LiteralLParenLoc = PE->getLParenLoc();
6037     LiteralRParenLoc = PE->getRParenLoc();
6038     exprs = PE->getExprs();
6039     numExprs = PE->getNumExprs();
6040   } else { // isa<ParenExpr> by assertion at function entrance
6041     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6042     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6043     subExpr = cast<ParenExpr>(E)->getSubExpr();
6044     exprs = &subExpr;
6045     numExprs = 1;
6046   }
6047
6048   QualType Ty = TInfo->getType();
6049   assert(Ty->isVectorType() && "Expected vector type");
6050
6051   SmallVector<Expr *, 8> initExprs;
6052   const VectorType *VTy = Ty->getAs<VectorType>();
6053   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6054   
6055   // '(...)' form of vector initialization in AltiVec: the number of
6056   // initializers must be one or must match the size of the vector.
6057   // If a single value is specified in the initializer then it will be
6058   // replicated to all the components of the vector
6059   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6060     // The number of initializers must be one or must match the size of the
6061     // vector. If a single value is specified in the initializer then it will
6062     // be replicated to all the components of the vector
6063     if (numExprs == 1) {
6064       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6065       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6066       if (Literal.isInvalid())
6067         return ExprError();
6068       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6069                                   PrepareScalarCast(Literal, ElemTy));
6070       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6071     }
6072     else if (numExprs < numElems) {
6073       Diag(E->getExprLoc(),
6074            diag::err_incorrect_number_of_vector_initializers);
6075       return ExprError();
6076     }
6077     else
6078       initExprs.append(exprs, exprs + numExprs);
6079   }
6080   else {
6081     // For OpenCL, when the number of initializers is a single value,
6082     // it will be replicated to all components of the vector.
6083     if (getLangOpts().OpenCL &&
6084         VTy->getVectorKind() == VectorType::GenericVector &&
6085         numExprs == 1) {
6086         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6087         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6088         if (Literal.isInvalid())
6089           return ExprError();
6090         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6091                                     PrepareScalarCast(Literal, ElemTy));
6092         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6093     }
6094     
6095     initExprs.append(exprs, exprs + numExprs);
6096   }
6097   // FIXME: This means that pretty-printing the final AST will produce curly
6098   // braces instead of the original commas.
6099   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6100                                                    initExprs, LiteralRParenLoc);
6101   initE->setType(Ty);
6102   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6103 }
6104
6105 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6106 /// the ParenListExpr into a sequence of comma binary operators.
6107 ExprResult
6108 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6109   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6110   if (!E)
6111     return OrigExpr;
6112
6113   ExprResult Result(E->getExpr(0));
6114
6115   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6116     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6117                         E->getExpr(i));
6118
6119   if (Result.isInvalid()) return ExprError();
6120
6121   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6122 }
6123
6124 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6125                                     SourceLocation R,
6126                                     MultiExprArg Val) {
6127   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6128   return expr;
6129 }
6130
6131 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6132 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6133 /// emitted.
6134 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6135                                       SourceLocation QuestionLoc) {
6136   Expr *NullExpr = LHSExpr;
6137   Expr *NonPointerExpr = RHSExpr;
6138   Expr::NullPointerConstantKind NullKind =
6139       NullExpr->isNullPointerConstant(Context,
6140                                       Expr::NPC_ValueDependentIsNotNull);
6141
6142   if (NullKind == Expr::NPCK_NotNull) {
6143     NullExpr = RHSExpr;
6144     NonPointerExpr = LHSExpr;
6145     NullKind =
6146         NullExpr->isNullPointerConstant(Context,
6147                                         Expr::NPC_ValueDependentIsNotNull);
6148   }
6149
6150   if (NullKind == Expr::NPCK_NotNull)
6151     return false;
6152
6153   if (NullKind == Expr::NPCK_ZeroExpression)
6154     return false;
6155
6156   if (NullKind == Expr::NPCK_ZeroLiteral) {
6157     // In this case, check to make sure that we got here from a "NULL"
6158     // string in the source code.
6159     NullExpr = NullExpr->IgnoreParenImpCasts();
6160     SourceLocation loc = NullExpr->getExprLoc();
6161     if (!findMacroSpelling(loc, "NULL"))
6162       return false;
6163   }
6164
6165   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6166   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6167       << NonPointerExpr->getType() << DiagType
6168       << NonPointerExpr->getSourceRange();
6169   return true;
6170 }
6171
6172 /// \brief Return false if the condition expression is valid, true otherwise.
6173 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6174   QualType CondTy = Cond->getType();
6175
6176   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6177   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6178     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6179       << CondTy << Cond->getSourceRange();
6180     return true;
6181   }
6182
6183   // C99 6.5.15p2
6184   if (CondTy->isScalarType()) return false;
6185
6186   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6187     << CondTy << Cond->getSourceRange();
6188   return true;
6189 }
6190
6191 /// \brief Handle when one or both operands are void type.
6192 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6193                                          ExprResult &RHS) {
6194     Expr *LHSExpr = LHS.get();
6195     Expr *RHSExpr = RHS.get();
6196
6197     if (!LHSExpr->getType()->isVoidType())
6198       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6199         << RHSExpr->getSourceRange();
6200     if (!RHSExpr->getType()->isVoidType())
6201       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6202         << LHSExpr->getSourceRange();
6203     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6204     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6205     return S.Context.VoidTy;
6206 }
6207
6208 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6209 /// true otherwise.
6210 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6211                                         QualType PointerTy) {
6212   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6213       !NullExpr.get()->isNullPointerConstant(S.Context,
6214                                             Expr::NPC_ValueDependentIsNull))
6215     return true;
6216
6217   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6218   return false;
6219 }
6220
6221 /// \brief Checks compatibility between two pointers and return the resulting
6222 /// type.
6223 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6224                                                      ExprResult &RHS,
6225                                                      SourceLocation Loc) {
6226   QualType LHSTy = LHS.get()->getType();
6227   QualType RHSTy = RHS.get()->getType();
6228
6229   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6230     // Two identical pointers types are always compatible.
6231     return LHSTy;
6232   }
6233
6234   QualType lhptee, rhptee;
6235
6236   // Get the pointee types.
6237   bool IsBlockPointer = false;
6238   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6239     lhptee = LHSBTy->getPointeeType();
6240     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6241     IsBlockPointer = true;
6242   } else {
6243     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6244     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6245   }
6246
6247   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6248   // differently qualified versions of compatible types, the result type is
6249   // a pointer to an appropriately qualified version of the composite
6250   // type.
6251
6252   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6253   // clause doesn't make sense for our extensions. E.g. address space 2 should
6254   // be incompatible with address space 3: they may live on different devices or
6255   // anything.
6256   Qualifiers lhQual = lhptee.getQualifiers();
6257   Qualifiers rhQual = rhptee.getQualifiers();
6258
6259   unsigned ResultAddrSpace = 0;
6260   unsigned LAddrSpace = lhQual.getAddressSpace();
6261   unsigned RAddrSpace = rhQual.getAddressSpace();
6262   if (S.getLangOpts().OpenCL) {
6263     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6264     // spaces is disallowed.
6265     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6266       ResultAddrSpace = LAddrSpace;
6267     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6268       ResultAddrSpace = RAddrSpace;
6269     else {
6270       S.Diag(Loc,
6271              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6272           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6273           << RHS.get()->getSourceRange();
6274       return QualType();
6275     }
6276   }
6277
6278   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6279   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6280   lhQual.removeCVRQualifiers();
6281   rhQual.removeCVRQualifiers();
6282
6283   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6284   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6285   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6286   // qual types are compatible iff
6287   //  * corresponded types are compatible
6288   //  * CVR qualifiers are equal
6289   //  * address spaces are equal
6290   // Thus for conditional operator we merge CVR and address space unqualified
6291   // pointees and if there is a composite type we return a pointer to it with
6292   // merged qualifiers.
6293   if (S.getLangOpts().OpenCL) {
6294     LHSCastKind = LAddrSpace == ResultAddrSpace
6295                       ? CK_BitCast
6296                       : CK_AddressSpaceConversion;
6297     RHSCastKind = RAddrSpace == ResultAddrSpace
6298                       ? CK_BitCast
6299                       : CK_AddressSpaceConversion;
6300     lhQual.removeAddressSpace();
6301     rhQual.removeAddressSpace();
6302   }
6303
6304   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6305   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6306
6307   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6308
6309   if (CompositeTy.isNull()) {
6310     // In this situation, we assume void* type. No especially good
6311     // reason, but this is what gcc does, and we do have to pick
6312     // to get a consistent AST.
6313     QualType incompatTy;
6314     incompatTy = S.Context.getPointerType(
6315         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6316     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6317     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6318     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6319     // for casts between types with incompatible address space qualifiers.
6320     // For the following code the compiler produces casts between global and
6321     // local address spaces of the corresponded innermost pointees:
6322     // local int *global *a;
6323     // global int *global *b;
6324     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6325     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6326         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6327         << RHS.get()->getSourceRange();
6328     return incompatTy;
6329   }
6330
6331   // The pointer types are compatible.
6332   // In case of OpenCL ResultTy should have the address space qualifier
6333   // which is a superset of address spaces of both the 2nd and the 3rd
6334   // operands of the conditional operator.
6335   QualType ResultTy = [&, ResultAddrSpace]() {
6336     if (S.getLangOpts().OpenCL) {
6337       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6338       CompositeQuals.setAddressSpace(ResultAddrSpace);
6339       return S.Context
6340           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6341           .withCVRQualifiers(MergedCVRQual);
6342     }
6343     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6344   }();
6345   if (IsBlockPointer)
6346     ResultTy = S.Context.getBlockPointerType(ResultTy);
6347   else
6348     ResultTy = S.Context.getPointerType(ResultTy);
6349
6350   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6351   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6352   return ResultTy;
6353 }
6354
6355 /// \brief Return the resulting type when the operands are both block pointers.
6356 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6357                                                           ExprResult &LHS,
6358                                                           ExprResult &RHS,
6359                                                           SourceLocation Loc) {
6360   QualType LHSTy = LHS.get()->getType();
6361   QualType RHSTy = RHS.get()->getType();
6362
6363   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6364     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6365       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6366       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6367       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6368       return destType;
6369     }
6370     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6371       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6372       << RHS.get()->getSourceRange();
6373     return QualType();
6374   }
6375
6376   // We have 2 block pointer types.
6377   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6378 }
6379
6380 /// \brief Return the resulting type when the operands are both pointers.
6381 static QualType
6382 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6383                                             ExprResult &RHS,
6384                                             SourceLocation Loc) {
6385   // get the pointer types
6386   QualType LHSTy = LHS.get()->getType();
6387   QualType RHSTy = RHS.get()->getType();
6388
6389   // get the "pointed to" types
6390   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6391   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6392
6393   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6394   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6395     // Figure out necessary qualifiers (C99 6.5.15p6)
6396     QualType destPointee
6397       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6398     QualType destType = S.Context.getPointerType(destPointee);
6399     // Add qualifiers if necessary.
6400     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6401     // Promote to void*.
6402     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6403     return destType;
6404   }
6405   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6406     QualType destPointee
6407       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6408     QualType destType = S.Context.getPointerType(destPointee);
6409     // Add qualifiers if necessary.
6410     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6411     // Promote to void*.
6412     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6413     return destType;
6414   }
6415
6416   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6417 }
6418
6419 /// \brief Return false if the first expression is not an integer and the second
6420 /// expression is not a pointer, true otherwise.
6421 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6422                                         Expr* PointerExpr, SourceLocation Loc,
6423                                         bool IsIntFirstExpr) {
6424   if (!PointerExpr->getType()->isPointerType() ||
6425       !Int.get()->getType()->isIntegerType())
6426     return false;
6427
6428   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6429   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6430
6431   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6432     << Expr1->getType() << Expr2->getType()
6433     << Expr1->getSourceRange() << Expr2->getSourceRange();
6434   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6435                             CK_IntegralToPointer);
6436   return true;
6437 }
6438
6439 /// \brief Simple conversion between integer and floating point types.
6440 ///
6441 /// Used when handling the OpenCL conditional operator where the
6442 /// condition is a vector while the other operands are scalar.
6443 ///
6444 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6445 /// types are either integer or floating type. Between the two
6446 /// operands, the type with the higher rank is defined as the "result
6447 /// type". The other operand needs to be promoted to the same type. No
6448 /// other type promotion is allowed. We cannot use
6449 /// UsualArithmeticConversions() for this purpose, since it always
6450 /// promotes promotable types.
6451 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6452                                             ExprResult &RHS,
6453                                             SourceLocation QuestionLoc) {
6454   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6455   if (LHS.isInvalid())
6456     return QualType();
6457   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6458   if (RHS.isInvalid())
6459     return QualType();
6460
6461   // For conversion purposes, we ignore any qualifiers.
6462   // For example, "const float" and "float" are equivalent.
6463   QualType LHSType =
6464     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6465   QualType RHSType =
6466     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6467
6468   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6469     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6470       << LHSType << LHS.get()->getSourceRange();
6471     return QualType();
6472   }
6473
6474   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6475     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6476       << RHSType << RHS.get()->getSourceRange();
6477     return QualType();
6478   }
6479
6480   // If both types are identical, no conversion is needed.
6481   if (LHSType == RHSType)
6482     return LHSType;
6483
6484   // Now handle "real" floating types (i.e. float, double, long double).
6485   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6486     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6487                                  /*IsCompAssign = */ false);
6488
6489   // Finally, we have two differing integer types.
6490   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6491   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6492 }
6493
6494 /// \brief Convert scalar operands to a vector that matches the
6495 ///        condition in length.
6496 ///
6497 /// Used when handling the OpenCL conditional operator where the
6498 /// condition is a vector while the other operands are scalar.
6499 ///
6500 /// We first compute the "result type" for the scalar operands
6501 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6502 /// into a vector of that type where the length matches the condition
6503 /// vector type. s6.11.6 requires that the element types of the result
6504 /// and the condition must have the same number of bits.
6505 static QualType
6506 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6507                               QualType CondTy, SourceLocation QuestionLoc) {
6508   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6509   if (ResTy.isNull()) return QualType();
6510
6511   const VectorType *CV = CondTy->getAs<VectorType>();
6512   assert(CV);
6513
6514   // Determine the vector result type
6515   unsigned NumElements = CV->getNumElements();
6516   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6517
6518   // Ensure that all types have the same number of bits
6519   if (S.Context.getTypeSize(CV->getElementType())
6520       != S.Context.getTypeSize(ResTy)) {
6521     // Since VectorTy is created internally, it does not pretty print
6522     // with an OpenCL name. Instead, we just print a description.
6523     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6524     SmallString<64> Str;
6525     llvm::raw_svector_ostream OS(Str);
6526     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6527     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6528       << CondTy << OS.str();
6529     return QualType();
6530   }
6531
6532   // Convert operands to the vector result type
6533   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6534   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6535
6536   return VectorTy;
6537 }
6538
6539 /// \brief Return false if this is a valid OpenCL condition vector
6540 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6541                                        SourceLocation QuestionLoc) {
6542   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6543   // integral type.
6544   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6545   assert(CondTy);
6546   QualType EleTy = CondTy->getElementType();
6547   if (EleTy->isIntegerType()) return false;
6548
6549   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6550     << Cond->getType() << Cond->getSourceRange();
6551   return true;
6552 }
6553
6554 /// \brief Return false if the vector condition type and the vector
6555 ///        result type are compatible.
6556 ///
6557 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6558 /// number of elements, and their element types have the same number
6559 /// of bits.
6560 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6561                               SourceLocation QuestionLoc) {
6562   const VectorType *CV = CondTy->getAs<VectorType>();
6563   const VectorType *RV = VecResTy->getAs<VectorType>();
6564   assert(CV && RV);
6565
6566   if (CV->getNumElements() != RV->getNumElements()) {
6567     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6568       << CondTy << VecResTy;
6569     return true;
6570   }
6571
6572   QualType CVE = CV->getElementType();
6573   QualType RVE = RV->getElementType();
6574
6575   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6576     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6577       << CondTy << VecResTy;
6578     return true;
6579   }
6580
6581   return false;
6582 }
6583
6584 /// \brief Return the resulting type for the conditional operator in
6585 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6586 ///        s6.3.i) when the condition is a vector type.
6587 static QualType
6588 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6589                              ExprResult &LHS, ExprResult &RHS,
6590                              SourceLocation QuestionLoc) {
6591   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
6592   if (Cond.isInvalid())
6593     return QualType();
6594   QualType CondTy = Cond.get()->getType();
6595
6596   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6597     return QualType();
6598
6599   // If either operand is a vector then find the vector type of the
6600   // result as specified in OpenCL v1.1 s6.3.i.
6601   if (LHS.get()->getType()->isVectorType() ||
6602       RHS.get()->getType()->isVectorType()) {
6603     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6604                                               /*isCompAssign*/false,
6605                                               /*AllowBothBool*/true,
6606                                               /*AllowBoolConversions*/false);
6607     if (VecResTy.isNull()) return QualType();
6608     // The result type must match the condition type as specified in
6609     // OpenCL v1.1 s6.11.6.
6610     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6611       return QualType();
6612     return VecResTy;
6613   }
6614
6615   // Both operands are scalar.
6616   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6617 }
6618
6619 /// \brief Return true if the Expr is block type
6620 static bool checkBlockType(Sema &S, const Expr *E) {
6621   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6622     QualType Ty = CE->getCallee()->getType();
6623     if (Ty->isBlockPointerType()) {
6624       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6625       return true;
6626     }
6627   }
6628   return false;
6629 }
6630
6631 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6632 /// In that case, LHS = cond.
6633 /// C99 6.5.15
6634 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6635                                         ExprResult &RHS, ExprValueKind &VK,
6636                                         ExprObjectKind &OK,
6637                                         SourceLocation QuestionLoc) {
6638
6639   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6640   if (!LHSResult.isUsable()) return QualType();
6641   LHS = LHSResult;
6642
6643   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6644   if (!RHSResult.isUsable()) return QualType();
6645   RHS = RHSResult;
6646
6647   // C++ is sufficiently different to merit its own checker.
6648   if (getLangOpts().CPlusPlus)
6649     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6650
6651   VK = VK_RValue;
6652   OK = OK_Ordinary;
6653
6654   // The OpenCL operator with a vector condition is sufficiently
6655   // different to merit its own checker.
6656   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6657     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6658
6659   // First, check the condition.
6660   Cond = UsualUnaryConversions(Cond.get());
6661   if (Cond.isInvalid())
6662     return QualType();
6663   if (checkCondition(*this, Cond.get(), QuestionLoc))
6664     return QualType();
6665
6666   // Now check the two expressions.
6667   if (LHS.get()->getType()->isVectorType() ||
6668       RHS.get()->getType()->isVectorType())
6669     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6670                                /*AllowBothBool*/true,
6671                                /*AllowBoolConversions*/false);
6672
6673   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6674   if (LHS.isInvalid() || RHS.isInvalid())
6675     return QualType();
6676
6677   QualType LHSTy = LHS.get()->getType();
6678   QualType RHSTy = RHS.get()->getType();
6679
6680   // Diagnose attempts to convert between __float128 and long double where
6681   // such conversions currently can't be handled.
6682   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6683     Diag(QuestionLoc,
6684          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6685       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6686     return QualType();
6687   }
6688
6689   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6690   // selection operator (?:).
6691   if (getLangOpts().OpenCL &&
6692       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6693     return QualType();
6694   }
6695
6696   // If both operands have arithmetic type, do the usual arithmetic conversions
6697   // to find a common type: C99 6.5.15p3,5.
6698   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6699     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6700     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6701
6702     return ResTy;
6703   }
6704
6705   // If both operands are the same structure or union type, the result is that
6706   // type.
6707   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6708     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6709       if (LHSRT->getDecl() == RHSRT->getDecl())
6710         // "If both the operands have structure or union type, the result has
6711         // that type."  This implies that CV qualifiers are dropped.
6712         return LHSTy.getUnqualifiedType();
6713     // FIXME: Type of conditional expression must be complete in C mode.
6714   }
6715
6716   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6717   // The following || allows only one side to be void (a GCC-ism).
6718   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6719     return checkConditionalVoidType(*this, LHS, RHS);
6720   }
6721
6722   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6723   // the type of the other operand."
6724   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6725   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6726
6727   // All objective-c pointer type analysis is done here.
6728   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6729                                                         QuestionLoc);
6730   if (LHS.isInvalid() || RHS.isInvalid())
6731     return QualType();
6732   if (!compositeType.isNull())
6733     return compositeType;
6734
6735
6736   // Handle block pointer types.
6737   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6738     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6739                                                      QuestionLoc);
6740
6741   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6742   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6743     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6744                                                        QuestionLoc);
6745
6746   // GCC compatibility: soften pointer/integer mismatch.  Note that
6747   // null pointers have been filtered out by this point.
6748   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6749       /*isIntFirstExpr=*/true))
6750     return RHSTy;
6751   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6752       /*isIntFirstExpr=*/false))
6753     return LHSTy;
6754
6755   // Emit a better diagnostic if one of the expressions is a null pointer
6756   // constant and the other is not a pointer type. In this case, the user most
6757   // likely forgot to take the address of the other expression.
6758   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6759     return QualType();
6760
6761   // Otherwise, the operands are not compatible.
6762   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6763     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6764     << RHS.get()->getSourceRange();
6765   return QualType();
6766 }
6767
6768 /// FindCompositeObjCPointerType - Helper method to find composite type of
6769 /// two objective-c pointer types of the two input expressions.
6770 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6771                                             SourceLocation QuestionLoc) {
6772   QualType LHSTy = LHS.get()->getType();
6773   QualType RHSTy = RHS.get()->getType();
6774
6775   // Handle things like Class and struct objc_class*.  Here we case the result
6776   // to the pseudo-builtin, because that will be implicitly cast back to the
6777   // redefinition type if an attempt is made to access its fields.
6778   if (LHSTy->isObjCClassType() &&
6779       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6780     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6781     return LHSTy;
6782   }
6783   if (RHSTy->isObjCClassType() &&
6784       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6785     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6786     return RHSTy;
6787   }
6788   // And the same for struct objc_object* / id
6789   if (LHSTy->isObjCIdType() &&
6790       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6791     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6792     return LHSTy;
6793   }
6794   if (RHSTy->isObjCIdType() &&
6795       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6796     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6797     return RHSTy;
6798   }
6799   // And the same for struct objc_selector* / SEL
6800   if (Context.isObjCSelType(LHSTy) &&
6801       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6802     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6803     return LHSTy;
6804   }
6805   if (Context.isObjCSelType(RHSTy) &&
6806       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6807     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6808     return RHSTy;
6809   }
6810   // Check constraints for Objective-C object pointers types.
6811   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6812
6813     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6814       // Two identical object pointer types are always compatible.
6815       return LHSTy;
6816     }
6817     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6818     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6819     QualType compositeType = LHSTy;
6820
6821     // If both operands are interfaces and either operand can be
6822     // assigned to the other, use that type as the composite
6823     // type. This allows
6824     //   xxx ? (A*) a : (B*) b
6825     // where B is a subclass of A.
6826     //
6827     // Additionally, as for assignment, if either type is 'id'
6828     // allow silent coercion. Finally, if the types are
6829     // incompatible then make sure to use 'id' as the composite
6830     // type so the result is acceptable for sending messages to.
6831
6832     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6833     // It could return the composite type.
6834     if (!(compositeType =
6835           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6836       // Nothing more to do.
6837     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6838       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6839     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6840       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6841     } else if ((LHSTy->isObjCQualifiedIdType() ||
6842                 RHSTy->isObjCQualifiedIdType()) &&
6843                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6844       // Need to handle "id<xx>" explicitly.
6845       // GCC allows qualified id and any Objective-C type to devolve to
6846       // id. Currently localizing to here until clear this should be
6847       // part of ObjCQualifiedIdTypesAreCompatible.
6848       compositeType = Context.getObjCIdType();
6849     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6850       compositeType = Context.getObjCIdType();
6851     } else {
6852       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6853       << LHSTy << RHSTy
6854       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6855       QualType incompatTy = Context.getObjCIdType();
6856       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6857       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6858       return incompatTy;
6859     }
6860     // The object pointer types are compatible.
6861     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6862     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6863     return compositeType;
6864   }
6865   // Check Objective-C object pointer types and 'void *'
6866   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6867     if (getLangOpts().ObjCAutoRefCount) {
6868       // ARC forbids the implicit conversion of object pointers to 'void *',
6869       // so these types are not compatible.
6870       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6871           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6872       LHS = RHS = true;
6873       return QualType();
6874     }
6875     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6876     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6877     QualType destPointee
6878     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6879     QualType destType = Context.getPointerType(destPointee);
6880     // Add qualifiers if necessary.
6881     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6882     // Promote to void*.
6883     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6884     return destType;
6885   }
6886   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6887     if (getLangOpts().ObjCAutoRefCount) {
6888       // ARC forbids the implicit conversion of object pointers to 'void *',
6889       // so these types are not compatible.
6890       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6891           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6892       LHS = RHS = true;
6893       return QualType();
6894     }
6895     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6896     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6897     QualType destPointee
6898     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6899     QualType destType = Context.getPointerType(destPointee);
6900     // Add qualifiers if necessary.
6901     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6902     // Promote to void*.
6903     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6904     return destType;
6905   }
6906   return QualType();
6907 }
6908
6909 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6910 /// ParenRange in parentheses.
6911 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6912                                const PartialDiagnostic &Note,
6913                                SourceRange ParenRange) {
6914   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6915   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6916       EndLoc.isValid()) {
6917     Self.Diag(Loc, Note)
6918       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6919       << FixItHint::CreateInsertion(EndLoc, ")");
6920   } else {
6921     // We can't display the parentheses, so just show the bare note.
6922     Self.Diag(Loc, Note) << ParenRange;
6923   }
6924 }
6925
6926 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6927   return BinaryOperator::isAdditiveOp(Opc) ||
6928          BinaryOperator::isMultiplicativeOp(Opc) ||
6929          BinaryOperator::isShiftOp(Opc);
6930 }
6931
6932 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6933 /// expression, either using a built-in or overloaded operator,
6934 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6935 /// expression.
6936 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6937                                    Expr **RHSExprs) {
6938   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6939   E = E->IgnoreImpCasts();
6940   E = E->IgnoreConversionOperator();
6941   E = E->IgnoreImpCasts();
6942
6943   // Built-in binary operator.
6944   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6945     if (IsArithmeticOp(OP->getOpcode())) {
6946       *Opcode = OP->getOpcode();
6947       *RHSExprs = OP->getRHS();
6948       return true;
6949     }
6950   }
6951
6952   // Overloaded operator.
6953   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6954     if (Call->getNumArgs() != 2)
6955       return false;
6956
6957     // Make sure this is really a binary operator that is safe to pass into
6958     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6959     OverloadedOperatorKind OO = Call->getOperator();
6960     if (OO < OO_Plus || OO > OO_Arrow ||
6961         OO == OO_PlusPlus || OO == OO_MinusMinus)
6962       return false;
6963
6964     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6965     if (IsArithmeticOp(OpKind)) {
6966       *Opcode = OpKind;
6967       *RHSExprs = Call->getArg(1);
6968       return true;
6969     }
6970   }
6971
6972   return false;
6973 }
6974
6975 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6976 /// or is a logical expression such as (x==y) which has int type, but is
6977 /// commonly interpreted as boolean.
6978 static bool ExprLooksBoolean(Expr *E) {
6979   E = E->IgnoreParenImpCasts();
6980
6981   if (E->getType()->isBooleanType())
6982     return true;
6983   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6984     return OP->isComparisonOp() || OP->isLogicalOp();
6985   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6986     return OP->getOpcode() == UO_LNot;
6987   if (E->getType()->isPointerType())
6988     return true;
6989
6990   return false;
6991 }
6992
6993 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6994 /// and binary operator are mixed in a way that suggests the programmer assumed
6995 /// the conditional operator has higher precedence, for example:
6996 /// "int x = a + someBinaryCondition ? 1 : 2".
6997 static void DiagnoseConditionalPrecedence(Sema &Self,
6998                                           SourceLocation OpLoc,
6999                                           Expr *Condition,
7000                                           Expr *LHSExpr,
7001                                           Expr *RHSExpr) {
7002   BinaryOperatorKind CondOpcode;
7003   Expr *CondRHS;
7004
7005   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7006     return;
7007   if (!ExprLooksBoolean(CondRHS))
7008     return;
7009
7010   // The condition is an arithmetic binary expression, with a right-
7011   // hand side that looks boolean, so warn.
7012
7013   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7014       << Condition->getSourceRange()
7015       << BinaryOperator::getOpcodeStr(CondOpcode);
7016
7017   SuggestParentheses(Self, OpLoc,
7018     Self.PDiag(diag::note_precedence_silence)
7019       << BinaryOperator::getOpcodeStr(CondOpcode),
7020     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7021
7022   SuggestParentheses(Self, OpLoc,
7023     Self.PDiag(diag::note_precedence_conditional_first),
7024     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7025 }
7026
7027 /// Compute the nullability of a conditional expression.
7028 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7029                                               QualType LHSTy, QualType RHSTy,
7030                                               ASTContext &Ctx) {
7031   if (!ResTy->isAnyPointerType())
7032     return ResTy;
7033
7034   auto GetNullability = [&Ctx](QualType Ty) {
7035     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7036     if (Kind)
7037       return *Kind;
7038     return NullabilityKind::Unspecified;
7039   };
7040
7041   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7042   NullabilityKind MergedKind;
7043
7044   // Compute nullability of a binary conditional expression.
7045   if (IsBin) {
7046     if (LHSKind == NullabilityKind::NonNull)
7047       MergedKind = NullabilityKind::NonNull;
7048     else
7049       MergedKind = RHSKind;
7050   // Compute nullability of a normal conditional expression.
7051   } else {
7052     if (LHSKind == NullabilityKind::Nullable ||
7053         RHSKind == NullabilityKind::Nullable)
7054       MergedKind = NullabilityKind::Nullable;
7055     else if (LHSKind == NullabilityKind::NonNull)
7056       MergedKind = RHSKind;
7057     else if (RHSKind == NullabilityKind::NonNull)
7058       MergedKind = LHSKind;
7059     else
7060       MergedKind = NullabilityKind::Unspecified;
7061   }
7062
7063   // Return if ResTy already has the correct nullability.
7064   if (GetNullability(ResTy) == MergedKind)
7065     return ResTy;
7066
7067   // Strip all nullability from ResTy.
7068   while (ResTy->getNullability(Ctx))
7069     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7070
7071   // Create a new AttributedType with the new nullability kind.
7072   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7073   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7074 }
7075
7076 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7077 /// in the case of a the GNU conditional expr extension.
7078 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7079                                     SourceLocation ColonLoc,
7080                                     Expr *CondExpr, Expr *LHSExpr,
7081                                     Expr *RHSExpr) {
7082   if (!getLangOpts().CPlusPlus) {
7083     // C cannot handle TypoExpr nodes in the condition because it
7084     // doesn't handle dependent types properly, so make sure any TypoExprs have
7085     // been dealt with before checking the operands.
7086     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7087     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7088     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7089
7090     if (!CondResult.isUsable())
7091       return ExprError();
7092
7093     if (LHSExpr) {
7094       if (!LHSResult.isUsable())
7095         return ExprError();
7096     }
7097
7098     if (!RHSResult.isUsable())
7099       return ExprError();
7100
7101     CondExpr = CondResult.get();
7102     LHSExpr = LHSResult.get();
7103     RHSExpr = RHSResult.get();
7104   }
7105
7106   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7107   // was the condition.
7108   OpaqueValueExpr *opaqueValue = nullptr;
7109   Expr *commonExpr = nullptr;
7110   if (!LHSExpr) {
7111     commonExpr = CondExpr;
7112     // Lower out placeholder types first.  This is important so that we don't
7113     // try to capture a placeholder. This happens in few cases in C++; such
7114     // as Objective-C++'s dictionary subscripting syntax.
7115     if (commonExpr->hasPlaceholderType()) {
7116       ExprResult result = CheckPlaceholderExpr(commonExpr);
7117       if (!result.isUsable()) return ExprError();
7118       commonExpr = result.get();
7119     }
7120     // We usually want to apply unary conversions *before* saving, except
7121     // in the special case of a C++ l-value conditional.
7122     if (!(getLangOpts().CPlusPlus
7123           && !commonExpr->isTypeDependent()
7124           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7125           && commonExpr->isGLValue()
7126           && commonExpr->isOrdinaryOrBitFieldObject()
7127           && RHSExpr->isOrdinaryOrBitFieldObject()
7128           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7129       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7130       if (commonRes.isInvalid())
7131         return ExprError();
7132       commonExpr = commonRes.get();
7133     }
7134
7135     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7136                                                 commonExpr->getType(),
7137                                                 commonExpr->getValueKind(),
7138                                                 commonExpr->getObjectKind(),
7139                                                 commonExpr);
7140     LHSExpr = CondExpr = opaqueValue;
7141   }
7142
7143   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7144   ExprValueKind VK = VK_RValue;
7145   ExprObjectKind OK = OK_Ordinary;
7146   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7147   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
7148                                              VK, OK, QuestionLoc);
7149   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7150       RHS.isInvalid())
7151     return ExprError();
7152
7153   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7154                                 RHS.get());
7155
7156   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7157
7158   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7159                                          Context);
7160
7161   if (!commonExpr)
7162     return new (Context)
7163         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7164                             RHS.get(), result, VK, OK);
7165
7166   return new (Context) BinaryConditionalOperator(
7167       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7168       ColonLoc, result, VK, OK);
7169 }
7170
7171 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7172 // being closely modeled after the C99 spec:-). The odd characteristic of this
7173 // routine is it effectively iqnores the qualifiers on the top level pointee.
7174 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7175 // FIXME: add a couple examples in this comment.
7176 static Sema::AssignConvertType
7177 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7178   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7179   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7180
7181   // get the "pointed to" type (ignoring qualifiers at the top level)
7182   const Type *lhptee, *rhptee;
7183   Qualifiers lhq, rhq;
7184   std::tie(lhptee, lhq) =
7185       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7186   std::tie(rhptee, rhq) =
7187       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7188
7189   Sema::AssignConvertType ConvTy = Sema::Compatible;
7190
7191   // C99 6.5.16.1p1: This following citation is common to constraints
7192   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7193   // qualifiers of the type *pointed to* by the right;
7194
7195   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7196   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7197       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7198     // Ignore lifetime for further calculation.
7199     lhq.removeObjCLifetime();
7200     rhq.removeObjCLifetime();
7201   }
7202
7203   if (!lhq.compatiblyIncludes(rhq)) {
7204     // Treat address-space mismatches as fatal.  TODO: address subspaces
7205     if (!lhq.isAddressSpaceSupersetOf(rhq))
7206       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7207
7208     // It's okay to add or remove GC or lifetime qualifiers when converting to
7209     // and from void*.
7210     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7211                         .compatiblyIncludes(
7212                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7213              && (lhptee->isVoidType() || rhptee->isVoidType()))
7214       ; // keep old
7215
7216     // Treat lifetime mismatches as fatal.
7217     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7218       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7219     
7220     // For GCC/MS compatibility, other qualifier mismatches are treated
7221     // as still compatible in C.
7222     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7223   }
7224
7225   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7226   // incomplete type and the other is a pointer to a qualified or unqualified
7227   // version of void...
7228   if (lhptee->isVoidType()) {
7229     if (rhptee->isIncompleteOrObjectType())
7230       return ConvTy;
7231
7232     // As an extension, we allow cast to/from void* to function pointer.
7233     assert(rhptee->isFunctionType());
7234     return Sema::FunctionVoidPointer;
7235   }
7236
7237   if (rhptee->isVoidType()) {
7238     if (lhptee->isIncompleteOrObjectType())
7239       return ConvTy;
7240
7241     // As an extension, we allow cast to/from void* to function pointer.
7242     assert(lhptee->isFunctionType());
7243     return Sema::FunctionVoidPointer;
7244   }
7245
7246   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7247   // unqualified versions of compatible types, ...
7248   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7249   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7250     // Check if the pointee types are compatible ignoring the sign.
7251     // We explicitly check for char so that we catch "char" vs
7252     // "unsigned char" on systems where "char" is unsigned.
7253     if (lhptee->isCharType())
7254       ltrans = S.Context.UnsignedCharTy;
7255     else if (lhptee->hasSignedIntegerRepresentation())
7256       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7257
7258     if (rhptee->isCharType())
7259       rtrans = S.Context.UnsignedCharTy;
7260     else if (rhptee->hasSignedIntegerRepresentation())
7261       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7262
7263     if (ltrans == rtrans) {
7264       // Types are compatible ignoring the sign. Qualifier incompatibility
7265       // takes priority over sign incompatibility because the sign
7266       // warning can be disabled.
7267       if (ConvTy != Sema::Compatible)
7268         return ConvTy;
7269
7270       return Sema::IncompatiblePointerSign;
7271     }
7272
7273     // If we are a multi-level pointer, it's possible that our issue is simply
7274     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7275     // the eventual target type is the same and the pointers have the same
7276     // level of indirection, this must be the issue.
7277     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7278       do {
7279         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7280         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7281       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7282
7283       if (lhptee == rhptee)
7284         return Sema::IncompatibleNestedPointerQualifiers;
7285     }
7286
7287     // General pointer incompatibility takes priority over qualifiers.
7288     return Sema::IncompatiblePointer;
7289   }
7290   if (!S.getLangOpts().CPlusPlus &&
7291       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7292     return Sema::IncompatiblePointer;
7293   return ConvTy;
7294 }
7295
7296 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7297 /// block pointer types are compatible or whether a block and normal pointer
7298 /// are compatible. It is more restrict than comparing two function pointer
7299 // types.
7300 static Sema::AssignConvertType
7301 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7302                                     QualType RHSType) {
7303   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7304   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7305
7306   QualType lhptee, rhptee;
7307
7308   // get the "pointed to" type (ignoring qualifiers at the top level)
7309   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7310   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7311
7312   // In C++, the types have to match exactly.
7313   if (S.getLangOpts().CPlusPlus)
7314     return Sema::IncompatibleBlockPointer;
7315
7316   Sema::AssignConvertType ConvTy = Sema::Compatible;
7317
7318   // For blocks we enforce that qualifiers are identical.
7319   Qualifiers LQuals = lhptee.getLocalQualifiers();
7320   Qualifiers RQuals = rhptee.getLocalQualifiers();
7321   if (S.getLangOpts().OpenCL) {
7322     LQuals.removeAddressSpace();
7323     RQuals.removeAddressSpace();
7324   }
7325   if (LQuals != RQuals)
7326     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7327
7328   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7329   // assignment.
7330   // The current behavior is similar to C++ lambdas. A block might be
7331   // assigned to a variable iff its return type and parameters are compatible
7332   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7333   // an assignment. Presumably it should behave in way that a function pointer
7334   // assignment does in C, so for each parameter and return type:
7335   //  * CVR and address space of LHS should be a superset of CVR and address
7336   //  space of RHS.
7337   //  * unqualified types should be compatible.
7338   if (S.getLangOpts().OpenCL) {
7339     if (!S.Context.typesAreBlockPointerCompatible(
7340             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7341             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7342       return Sema::IncompatibleBlockPointer;
7343   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7344     return Sema::IncompatibleBlockPointer;
7345
7346   return ConvTy;
7347 }
7348
7349 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7350 /// for assignment compatibility.
7351 static Sema::AssignConvertType
7352 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7353                                    QualType RHSType) {
7354   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7355   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7356
7357   if (LHSType->isObjCBuiltinType()) {
7358     // Class is not compatible with ObjC object pointers.
7359     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7360         !RHSType->isObjCQualifiedClassType())
7361       return Sema::IncompatiblePointer;
7362     return Sema::Compatible;
7363   }
7364   if (RHSType->isObjCBuiltinType()) {
7365     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7366         !LHSType->isObjCQualifiedClassType())
7367       return Sema::IncompatiblePointer;
7368     return Sema::Compatible;
7369   }
7370   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7371   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7372
7373   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7374       // make an exception for id<P>
7375       !LHSType->isObjCQualifiedIdType())
7376     return Sema::CompatiblePointerDiscardsQualifiers;
7377
7378   if (S.Context.typesAreCompatible(LHSType, RHSType))
7379     return Sema::Compatible;
7380   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7381     return Sema::IncompatibleObjCQualifiedId;
7382   return Sema::IncompatiblePointer;
7383 }
7384
7385 Sema::AssignConvertType
7386 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7387                                  QualType LHSType, QualType RHSType) {
7388   // Fake up an opaque expression.  We don't actually care about what
7389   // cast operations are required, so if CheckAssignmentConstraints
7390   // adds casts to this they'll be wasted, but fortunately that doesn't
7391   // usually happen on valid code.
7392   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7393   ExprResult RHSPtr = &RHSExpr;
7394   CastKind K = CK_Invalid;
7395
7396   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7397 }
7398
7399 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7400 /// has code to accommodate several GCC extensions when type checking
7401 /// pointers. Here are some objectionable examples that GCC considers warnings:
7402 ///
7403 ///  int a, *pint;
7404 ///  short *pshort;
7405 ///  struct foo *pfoo;
7406 ///
7407 ///  pint = pshort; // warning: assignment from incompatible pointer type
7408 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7409 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7410 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7411 ///
7412 /// As a result, the code for dealing with pointers is more complex than the
7413 /// C99 spec dictates.
7414 ///
7415 /// Sets 'Kind' for any result kind except Incompatible.
7416 Sema::AssignConvertType
7417 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7418                                  CastKind &Kind, bool ConvertRHS) {
7419   QualType RHSType = RHS.get()->getType();
7420   QualType OrigLHSType = LHSType;
7421
7422   // Get canonical types.  We're not formatting these types, just comparing
7423   // them.
7424   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7425   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7426
7427   // Common case: no conversion required.
7428   if (LHSType == RHSType) {
7429     Kind = CK_NoOp;
7430     return Compatible;
7431   }
7432
7433   // If we have an atomic type, try a non-atomic assignment, then just add an
7434   // atomic qualification step.
7435   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7436     Sema::AssignConvertType result =
7437       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7438     if (result != Compatible)
7439       return result;
7440     if (Kind != CK_NoOp && ConvertRHS)
7441       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7442     Kind = CK_NonAtomicToAtomic;
7443     return Compatible;
7444   }
7445
7446   // If the left-hand side is a reference type, then we are in a
7447   // (rare!) case where we've allowed the use of references in C,
7448   // e.g., as a parameter type in a built-in function. In this case,
7449   // just make sure that the type referenced is compatible with the
7450   // right-hand side type. The caller is responsible for adjusting
7451   // LHSType so that the resulting expression does not have reference
7452   // type.
7453   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7454     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7455       Kind = CK_LValueBitCast;
7456       return Compatible;
7457     }
7458     return Incompatible;
7459   }
7460
7461   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7462   // to the same ExtVector type.
7463   if (LHSType->isExtVectorType()) {
7464     if (RHSType->isExtVectorType())
7465       return Incompatible;
7466     if (RHSType->isArithmeticType()) {
7467       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7468       if (ConvertRHS)
7469         RHS = prepareVectorSplat(LHSType, RHS.get());
7470       Kind = CK_VectorSplat;
7471       return Compatible;
7472     }
7473   }
7474
7475   // Conversions to or from vector type.
7476   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7477     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7478       // Allow assignments of an AltiVec vector type to an equivalent GCC
7479       // vector type and vice versa
7480       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7481         Kind = CK_BitCast;
7482         return Compatible;
7483       }
7484
7485       // If we are allowing lax vector conversions, and LHS and RHS are both
7486       // vectors, the total size only needs to be the same. This is a bitcast;
7487       // no bits are changed but the result type is different.
7488       if (isLaxVectorConversion(RHSType, LHSType)) {
7489         Kind = CK_BitCast;
7490         return IncompatibleVectors;
7491       }
7492     }
7493
7494     // When the RHS comes from another lax conversion (e.g. binops between
7495     // scalars and vectors) the result is canonicalized as a vector. When the
7496     // LHS is also a vector, the lax is allowed by the condition above. Handle
7497     // the case where LHS is a scalar.
7498     if (LHSType->isScalarType()) {
7499       const VectorType *VecType = RHSType->getAs<VectorType>();
7500       if (VecType && VecType->getNumElements() == 1 &&
7501           isLaxVectorConversion(RHSType, LHSType)) {
7502         ExprResult *VecExpr = &RHS;
7503         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7504         Kind = CK_BitCast;
7505         return Compatible;
7506       }
7507     }
7508
7509     return Incompatible;
7510   }
7511
7512   // Diagnose attempts to convert between __float128 and long double where
7513   // such conversions currently can't be handled.
7514   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7515     return Incompatible;
7516
7517   // Arithmetic conversions.
7518   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7519       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7520     if (ConvertRHS)
7521       Kind = PrepareScalarCast(RHS, LHSType);
7522     return Compatible;
7523   }
7524
7525   // Conversions to normal pointers.
7526   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7527     // U* -> T*
7528     if (isa<PointerType>(RHSType)) {
7529       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7530       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7531       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7532       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7533     }
7534
7535     // int -> T*
7536     if (RHSType->isIntegerType()) {
7537       Kind = CK_IntegralToPointer; // FIXME: null?
7538       return IntToPointer;
7539     }
7540
7541     // C pointers are not compatible with ObjC object pointers,
7542     // with two exceptions:
7543     if (isa<ObjCObjectPointerType>(RHSType)) {
7544       //  - conversions to void*
7545       if (LHSPointer->getPointeeType()->isVoidType()) {
7546         Kind = CK_BitCast;
7547         return Compatible;
7548       }
7549
7550       //  - conversions from 'Class' to the redefinition type
7551       if (RHSType->isObjCClassType() &&
7552           Context.hasSameType(LHSType, 
7553                               Context.getObjCClassRedefinitionType())) {
7554         Kind = CK_BitCast;
7555         return Compatible;
7556       }
7557
7558       Kind = CK_BitCast;
7559       return IncompatiblePointer;
7560     }
7561
7562     // U^ -> void*
7563     if (RHSType->getAs<BlockPointerType>()) {
7564       if (LHSPointer->getPointeeType()->isVoidType()) {
7565         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7566         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7567                                   ->getPointeeType()
7568                                   .getAddressSpace();
7569         Kind =
7570             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7571         return Compatible;
7572       }
7573     }
7574
7575     return Incompatible;
7576   }
7577
7578   // Conversions to block pointers.
7579   if (isa<BlockPointerType>(LHSType)) {
7580     // U^ -> T^
7581     if (RHSType->isBlockPointerType()) {
7582       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7583                                 ->getPointeeType()
7584                                 .getAddressSpace();
7585       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7586                                 ->getPointeeType()
7587                                 .getAddressSpace();
7588       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7589       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7590     }
7591
7592     // int or null -> T^
7593     if (RHSType->isIntegerType()) {
7594       Kind = CK_IntegralToPointer; // FIXME: null
7595       return IntToBlockPointer;
7596     }
7597
7598     // id -> T^
7599     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7600       Kind = CK_AnyPointerToBlockPointerCast;
7601       return Compatible;
7602     }
7603
7604     // void* -> T^
7605     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7606       if (RHSPT->getPointeeType()->isVoidType()) {
7607         Kind = CK_AnyPointerToBlockPointerCast;
7608         return Compatible;
7609       }
7610
7611     return Incompatible;
7612   }
7613
7614   // Conversions to Objective-C pointers.
7615   if (isa<ObjCObjectPointerType>(LHSType)) {
7616     // A* -> B*
7617     if (RHSType->isObjCObjectPointerType()) {
7618       Kind = CK_BitCast;
7619       Sema::AssignConvertType result = 
7620         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7621       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7622           result == Compatible && 
7623           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7624         result = IncompatibleObjCWeakRef;
7625       return result;
7626     }
7627
7628     // int or null -> A*
7629     if (RHSType->isIntegerType()) {
7630       Kind = CK_IntegralToPointer; // FIXME: null
7631       return IntToPointer;
7632     }
7633
7634     // In general, C pointers are not compatible with ObjC object pointers,
7635     // with two exceptions:
7636     if (isa<PointerType>(RHSType)) {
7637       Kind = CK_CPointerToObjCPointerCast;
7638
7639       //  - conversions from 'void*'
7640       if (RHSType->isVoidPointerType()) {
7641         return Compatible;
7642       }
7643
7644       //  - conversions to 'Class' from its redefinition type
7645       if (LHSType->isObjCClassType() &&
7646           Context.hasSameType(RHSType, 
7647                               Context.getObjCClassRedefinitionType())) {
7648         return Compatible;
7649       }
7650
7651       return IncompatiblePointer;
7652     }
7653
7654     // Only under strict condition T^ is compatible with an Objective-C pointer.
7655     if (RHSType->isBlockPointerType() && 
7656         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7657       if (ConvertRHS)
7658         maybeExtendBlockObject(RHS);
7659       Kind = CK_BlockPointerToObjCPointerCast;
7660       return Compatible;
7661     }
7662
7663     return Incompatible;
7664   }
7665
7666   // Conversions from pointers that are not covered by the above.
7667   if (isa<PointerType>(RHSType)) {
7668     // T* -> _Bool
7669     if (LHSType == Context.BoolTy) {
7670       Kind = CK_PointerToBoolean;
7671       return Compatible;
7672     }
7673
7674     // T* -> int
7675     if (LHSType->isIntegerType()) {
7676       Kind = CK_PointerToIntegral;
7677       return PointerToInt;
7678     }
7679
7680     return Incompatible;
7681   }
7682
7683   // Conversions from Objective-C pointers that are not covered by the above.
7684   if (isa<ObjCObjectPointerType>(RHSType)) {
7685     // T* -> _Bool
7686     if (LHSType == Context.BoolTy) {
7687       Kind = CK_PointerToBoolean;
7688       return Compatible;
7689     }
7690
7691     // T* -> int
7692     if (LHSType->isIntegerType()) {
7693       Kind = CK_PointerToIntegral;
7694       return PointerToInt;
7695     }
7696
7697     return Incompatible;
7698   }
7699
7700   // struct A -> struct B
7701   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7702     if (Context.typesAreCompatible(LHSType, RHSType)) {
7703       Kind = CK_NoOp;
7704       return Compatible;
7705     }
7706   }
7707
7708   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7709     Kind = CK_IntToOCLSampler;
7710     return Compatible;
7711   }
7712
7713   return Incompatible;
7714 }
7715
7716 /// \brief Constructs a transparent union from an expression that is
7717 /// used to initialize the transparent union.
7718 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7719                                       ExprResult &EResult, QualType UnionType,
7720                                       FieldDecl *Field) {
7721   // Build an initializer list that designates the appropriate member
7722   // of the transparent union.
7723   Expr *E = EResult.get();
7724   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7725                                                    E, SourceLocation());
7726   Initializer->setType(UnionType);
7727   Initializer->setInitializedFieldInUnion(Field);
7728
7729   // Build a compound literal constructing a value of the transparent
7730   // union type from this initializer list.
7731   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7732   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7733                                         VK_RValue, Initializer, false);
7734 }
7735
7736 Sema::AssignConvertType
7737 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7738                                                ExprResult &RHS) {
7739   QualType RHSType = RHS.get()->getType();
7740
7741   // If the ArgType is a Union type, we want to handle a potential
7742   // transparent_union GCC extension.
7743   const RecordType *UT = ArgType->getAsUnionType();
7744   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7745     return Incompatible;
7746
7747   // The field to initialize within the transparent union.
7748   RecordDecl *UD = UT->getDecl();
7749   FieldDecl *InitField = nullptr;
7750   // It's compatible if the expression matches any of the fields.
7751   for (auto *it : UD->fields()) {
7752     if (it->getType()->isPointerType()) {
7753       // If the transparent union contains a pointer type, we allow:
7754       // 1) void pointer
7755       // 2) null pointer constant
7756       if (RHSType->isPointerType())
7757         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7758           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7759           InitField = it;
7760           break;
7761         }
7762
7763       if (RHS.get()->isNullPointerConstant(Context,
7764                                            Expr::NPC_ValueDependentIsNull)) {
7765         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7766                                 CK_NullToPointer);
7767         InitField = it;
7768         break;
7769       }
7770     }
7771
7772     CastKind Kind = CK_Invalid;
7773     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7774           == Compatible) {
7775       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7776       InitField = it;
7777       break;
7778     }
7779   }
7780
7781   if (!InitField)
7782     return Incompatible;
7783
7784   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7785   return Compatible;
7786 }
7787
7788 Sema::AssignConvertType
7789 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7790                                        bool Diagnose,
7791                                        bool DiagnoseCFAudited,
7792                                        bool ConvertRHS) {
7793   // We need to be able to tell the caller whether we diagnosed a problem, if
7794   // they ask us to issue diagnostics.
7795   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7796
7797   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7798   // we can't avoid *all* modifications at the moment, so we need some somewhere
7799   // to put the updated value.
7800   ExprResult LocalRHS = CallerRHS;
7801   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7802
7803   if (getLangOpts().CPlusPlus) {
7804     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7805       // C++ 5.17p3: If the left operand is not of class type, the
7806       // expression is implicitly converted (C++ 4) to the
7807       // cv-unqualified type of the left operand.
7808       QualType RHSType = RHS.get()->getType();
7809       if (Diagnose) {
7810         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7811                                         AA_Assigning);
7812       } else {
7813         ImplicitConversionSequence ICS =
7814             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7815                                   /*SuppressUserConversions=*/false,
7816                                   /*AllowExplicit=*/false,
7817                                   /*InOverloadResolution=*/false,
7818                                   /*CStyle=*/false,
7819                                   /*AllowObjCWritebackConversion=*/false);
7820         if (ICS.isFailure())
7821           return Incompatible;
7822         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7823                                         ICS, AA_Assigning);
7824       }
7825       if (RHS.isInvalid())
7826         return Incompatible;
7827       Sema::AssignConvertType result = Compatible;
7828       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7829           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7830         result = IncompatibleObjCWeakRef;
7831       return result;
7832     }
7833
7834     // FIXME: Currently, we fall through and treat C++ classes like C
7835     // structures.
7836     // FIXME: We also fall through for atomics; not sure what should
7837     // happen there, though.
7838   } else if (RHS.get()->getType() == Context.OverloadTy) {
7839     // As a set of extensions to C, we support overloading on functions. These
7840     // functions need to be resolved here.
7841     DeclAccessPair DAP;
7842     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7843             RHS.get(), LHSType, /*Complain=*/false, DAP))
7844       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7845     else
7846       return Incompatible;
7847   }
7848
7849   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7850   // a null pointer constant.
7851   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7852        LHSType->isBlockPointerType()) &&
7853       RHS.get()->isNullPointerConstant(Context,
7854                                        Expr::NPC_ValueDependentIsNull)) {
7855     if (Diagnose || ConvertRHS) {
7856       CastKind Kind;
7857       CXXCastPath Path;
7858       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7859                              /*IgnoreBaseAccess=*/false, Diagnose);
7860       if (ConvertRHS)
7861         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7862     }
7863     return Compatible;
7864   }
7865
7866   // This check seems unnatural, however it is necessary to ensure the proper
7867   // conversion of functions/arrays. If the conversion were done for all
7868   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7869   // expressions that suppress this implicit conversion (&, sizeof).
7870   //
7871   // Suppress this for references: C++ 8.5.3p5.
7872   if (!LHSType->isReferenceType()) {
7873     // FIXME: We potentially allocate here even if ConvertRHS is false.
7874     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7875     if (RHS.isInvalid())
7876       return Incompatible;
7877   }
7878
7879   Expr *PRE = RHS.get()->IgnoreParenCasts();
7880   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7881     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7882     if (PDecl && !PDecl->hasDefinition()) {
7883       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7884       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7885     }
7886   }
7887   
7888   CastKind Kind = CK_Invalid;
7889   Sema::AssignConvertType result =
7890     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7891
7892   // C99 6.5.16.1p2: The value of the right operand is converted to the
7893   // type of the assignment expression.
7894   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7895   // so that we can use references in built-in functions even in C.
7896   // The getNonReferenceType() call makes sure that the resulting expression
7897   // does not have reference type.
7898   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7899     QualType Ty = LHSType.getNonLValueExprType(Context);
7900     Expr *E = RHS.get();
7901
7902     // Check for various Objective-C errors. If we are not reporting
7903     // diagnostics and just checking for errors, e.g., during overload
7904     // resolution, return Incompatible to indicate the failure.
7905     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7906         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7907                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
7908       if (!Diagnose)
7909         return Incompatible;
7910     }
7911     if (getLangOpts().ObjC1 &&
7912         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7913                                            E->getType(), E, Diagnose) ||
7914          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7915       if (!Diagnose)
7916         return Incompatible;
7917       // Replace the expression with a corrected version and continue so we
7918       // can find further errors.
7919       RHS = E;
7920       return Compatible;
7921     }
7922     
7923     if (ConvertRHS)
7924       RHS = ImpCastExprToType(E, Ty, Kind);
7925   }
7926   return result;
7927 }
7928
7929 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7930                                ExprResult &RHS) {
7931   Diag(Loc, diag::err_typecheck_invalid_operands)
7932     << LHS.get()->getType() << RHS.get()->getType()
7933     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7934   return QualType();
7935 }
7936
7937 // Diagnose cases where a scalar was implicitly converted to a vector and
7938 // diagnose the underlying types. Otherwise, diagnose the error
7939 // as invalid vector logical operands for non-C++ cases.
7940 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
7941                                             ExprResult &RHS) {
7942   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
7943   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
7944
7945   bool LHSNatVec = LHSType->isVectorType();
7946   bool RHSNatVec = RHSType->isVectorType();
7947
7948   if (!(LHSNatVec && RHSNatVec)) {
7949     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
7950     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
7951     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
7952         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
7953         << Vector->getSourceRange();
7954     return QualType();
7955   }
7956
7957   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
7958       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
7959       << RHS.get()->getSourceRange();
7960
7961   return QualType();
7962 }
7963
7964 /// Try to convert a value of non-vector type to a vector type by converting
7965 /// the type to the element type of the vector and then performing a splat.
7966 /// If the language is OpenCL, we only use conversions that promote scalar
7967 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7968 /// for float->int.
7969 ///
7970 /// OpenCL V2.0 6.2.6.p2:
7971 /// An error shall occur if any scalar operand type has greater rank
7972 /// than the type of the vector element.
7973 ///
7974 /// \param scalar - if non-null, actually perform the conversions
7975 /// \return true if the operation fails (but without diagnosing the failure)
7976 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7977                                      QualType scalarTy,
7978                                      QualType vectorEltTy,
7979                                      QualType vectorTy,
7980                                      unsigned &DiagID) {
7981   // The conversion to apply to the scalar before splatting it,
7982   // if necessary.
7983   CastKind scalarCast = CK_Invalid;
7984   
7985   if (vectorEltTy->isIntegralType(S.Context)) {
7986     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
7987         (scalarTy->isIntegerType() &&
7988          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
7989       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
7990       return true;
7991     }
7992     if (!scalarTy->isIntegralType(S.Context))
7993       return true;
7994     scalarCast = CK_IntegralCast;
7995   } else if (vectorEltTy->isRealFloatingType()) {
7996     if (scalarTy->isRealFloatingType()) {
7997       if (S.getLangOpts().OpenCL &&
7998           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
7999         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8000         return true;
8001       }
8002       scalarCast = CK_FloatingCast;
8003     }
8004     else if (scalarTy->isIntegralType(S.Context))
8005       scalarCast = CK_IntegralToFloating;
8006     else
8007       return true;
8008   } else {
8009     return true;
8010   }
8011
8012   // Adjust scalar if desired.
8013   if (scalar) {
8014     if (scalarCast != CK_Invalid)
8015       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8016     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8017   }
8018   return false;
8019 }
8020
8021 /// Test if a (constant) integer Int can be casted to another integer type
8022 /// IntTy without losing precision.
8023 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8024                                       QualType OtherIntTy) {
8025   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8026
8027   // Reject cases where the value of the Int is unknown as that would
8028   // possibly cause truncation, but accept cases where the scalar can be
8029   // demoted without loss of precision.
8030   llvm::APSInt Result;
8031   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8032   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8033   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8034   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8035
8036   if (CstInt) {
8037     // If the scalar is constant and is of a higher order and has more active
8038     // bits that the vector element type, reject it.
8039     unsigned NumBits = IntSigned
8040                            ? (Result.isNegative() ? Result.getMinSignedBits()
8041                                                   : Result.getActiveBits())
8042                            : Result.getActiveBits();
8043     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8044       return true;
8045
8046     // If the signedness of the scalar type and the vector element type
8047     // differs and the number of bits is greater than that of the vector
8048     // element reject it.
8049     return (IntSigned != OtherIntSigned &&
8050             NumBits > S.Context.getIntWidth(OtherIntTy));
8051   }
8052
8053   // Reject cases where the value of the scalar is not constant and it's
8054   // order is greater than that of the vector element type.
8055   return (Order < 0);
8056 }
8057
8058 /// Test if a (constant) integer Int can be casted to floating point type
8059 /// FloatTy without losing precision.
8060 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8061                                      QualType FloatTy) {
8062   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8063
8064   // Determine if the integer constant can be expressed as a floating point
8065   // number of the appropiate type.
8066   llvm::APSInt Result;
8067   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8068   uint64_t Bits = 0;
8069   if (CstInt) {
8070     // Reject constants that would be truncated if they were converted to
8071     // the floating point type. Test by simple to/from conversion.
8072     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8073     //        could be avoided if there was a convertFromAPInt method
8074     //        which could signal back if implicit truncation occurred.
8075     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8076     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8077                            llvm::APFloat::rmTowardZero);
8078     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8079                              !IntTy->hasSignedIntegerRepresentation());
8080     bool Ignored = false;
8081     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8082                            &Ignored);
8083     if (Result != ConvertBack)
8084       return true;
8085   } else {
8086     // Reject types that cannot be fully encoded into the mantissa of
8087     // the float.
8088     Bits = S.Context.getTypeSize(IntTy);
8089     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8090         S.Context.getFloatTypeSemantics(FloatTy));
8091     if (Bits > FloatPrec)
8092       return true;
8093   }
8094
8095   return false;
8096 }
8097
8098 /// Attempt to convert and splat Scalar into a vector whose types matches
8099 /// Vector following GCC conversion rules. The rule is that implicit
8100 /// conversion can occur when Scalar can be casted to match Vector's element
8101 /// type without causing truncation of Scalar.
8102 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8103                                         ExprResult *Vector) {
8104   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8105   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8106   const VectorType *VT = VectorTy->getAs<VectorType>();
8107
8108   assert(!isa<ExtVectorType>(VT) &&
8109          "ExtVectorTypes should not be handled here!");
8110
8111   QualType VectorEltTy = VT->getElementType();
8112
8113   // Reject cases where the vector element type or the scalar element type are
8114   // not integral or floating point types.
8115   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8116     return true;
8117
8118   // The conversion to apply to the scalar before splatting it,
8119   // if necessary.
8120   CastKind ScalarCast = CK_NoOp;
8121
8122   // Accept cases where the vector elements are integers and the scalar is
8123   // an integer.
8124   // FIXME: Notionally if the scalar was a floating point value with a precise
8125   //        integral representation, we could cast it to an appropriate integer
8126   //        type and then perform the rest of the checks here. GCC will perform
8127   //        this conversion in some cases as determined by the input language.
8128   //        We should accept it on a language independent basis.
8129   if (VectorEltTy->isIntegralType(S.Context) &&
8130       ScalarTy->isIntegralType(S.Context) &&
8131       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8132
8133     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8134       return true;
8135
8136     ScalarCast = CK_IntegralCast;
8137   } else if (VectorEltTy->isRealFloatingType()) {
8138     if (ScalarTy->isRealFloatingType()) {
8139
8140       // Reject cases where the scalar type is not a constant and has a higher
8141       // Order than the vector element type.
8142       llvm::APFloat Result(0.0);
8143       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8144       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8145       if (!CstScalar && Order < 0)
8146         return true;
8147
8148       // If the scalar cannot be safely casted to the vector element type,
8149       // reject it.
8150       if (CstScalar) {
8151         bool Truncated = false;
8152         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8153                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8154         if (Truncated)
8155           return true;
8156       }
8157
8158       ScalarCast = CK_FloatingCast;
8159     } else if (ScalarTy->isIntegralType(S.Context)) {
8160       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8161         return true;
8162
8163       ScalarCast = CK_IntegralToFloating;
8164     } else
8165       return true;
8166   }
8167
8168   // Adjust scalar if desired.
8169   if (Scalar) {
8170     if (ScalarCast != CK_NoOp)
8171       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8172     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8173   }
8174   return false;
8175 }
8176
8177 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8178                                    SourceLocation Loc, bool IsCompAssign,
8179                                    bool AllowBothBool,
8180                                    bool AllowBoolConversions) {
8181   if (!IsCompAssign) {
8182     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8183     if (LHS.isInvalid())
8184       return QualType();
8185   }
8186   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8187   if (RHS.isInvalid())
8188     return QualType();
8189
8190   // For conversion purposes, we ignore any qualifiers.
8191   // For example, "const float" and "float" are equivalent.
8192   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8193   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8194
8195   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8196   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8197   assert(LHSVecType || RHSVecType);
8198
8199   // AltiVec-style "vector bool op vector bool" combinations are allowed
8200   // for some operators but not others.
8201   if (!AllowBothBool &&
8202       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8203       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8204     return InvalidOperands(Loc, LHS, RHS);
8205
8206   // If the vector types are identical, return.
8207   if (Context.hasSameType(LHSType, RHSType))
8208     return LHSType;
8209
8210   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8211   if (LHSVecType && RHSVecType &&
8212       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8213     if (isa<ExtVectorType>(LHSVecType)) {
8214       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8215       return LHSType;
8216     }
8217
8218     if (!IsCompAssign)
8219       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8220     return RHSType;
8221   }
8222
8223   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8224   // can be mixed, with the result being the non-bool type.  The non-bool
8225   // operand must have integer element type.
8226   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8227       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8228       (Context.getTypeSize(LHSVecType->getElementType()) ==
8229        Context.getTypeSize(RHSVecType->getElementType()))) {
8230     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8231         LHSVecType->getElementType()->isIntegerType() &&
8232         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8233       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8234       return LHSType;
8235     }
8236     if (!IsCompAssign &&
8237         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8238         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8239         RHSVecType->getElementType()->isIntegerType()) {
8240       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8241       return RHSType;
8242     }
8243   }
8244
8245   // If there's a vector type and a scalar, try to convert the scalar to
8246   // the vector element type and splat.
8247   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8248   if (!RHSVecType) {
8249     if (isa<ExtVectorType>(LHSVecType)) {
8250       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8251                                     LHSVecType->getElementType(), LHSType,
8252                                     DiagID))
8253         return LHSType;
8254     } else {
8255       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8256         return LHSType;
8257     }
8258   }
8259   if (!LHSVecType) {
8260     if (isa<ExtVectorType>(RHSVecType)) {
8261       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8262                                     LHSType, RHSVecType->getElementType(),
8263                                     RHSType, DiagID))
8264         return RHSType;
8265     } else {
8266       if (LHS.get()->getValueKind() == VK_LValue ||
8267           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8268         return RHSType;
8269     }
8270   }
8271
8272   // FIXME: The code below also handles conversion between vectors and
8273   // non-scalars, we should break this down into fine grained specific checks
8274   // and emit proper diagnostics.
8275   QualType VecType = LHSVecType ? LHSType : RHSType;
8276   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8277   QualType OtherType = LHSVecType ? RHSType : LHSType;
8278   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8279   if (isLaxVectorConversion(OtherType, VecType)) {
8280     // If we're allowing lax vector conversions, only the total (data) size
8281     // needs to be the same. For non compound assignment, if one of the types is
8282     // scalar, the result is always the vector type.
8283     if (!IsCompAssign) {
8284       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8285       return VecType;
8286     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8287     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8288     // type. Note that this is already done by non-compound assignments in
8289     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8290     // <1 x T> -> T. The result is also a vector type.
8291     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8292                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8293       ExprResult *RHSExpr = &RHS;
8294       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8295       return VecType;
8296     }
8297   }
8298
8299   // Okay, the expression is invalid.
8300
8301   // If there's a non-vector, non-real operand, diagnose that.
8302   if ((!RHSVecType && !RHSType->isRealType()) ||
8303       (!LHSVecType && !LHSType->isRealType())) {
8304     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8305       << LHSType << RHSType
8306       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8307     return QualType();
8308   }
8309
8310   // OpenCL V1.1 6.2.6.p1:
8311   // If the operands are of more than one vector type, then an error shall
8312   // occur. Implicit conversions between vector types are not permitted, per
8313   // section 6.2.1.
8314   if (getLangOpts().OpenCL &&
8315       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8316       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8317     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8318                                                            << RHSType;
8319     return QualType();
8320   }
8321
8322
8323   // If there is a vector type that is not a ExtVector and a scalar, we reach
8324   // this point if scalar could not be converted to the vector's element type
8325   // without truncation.
8326   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8327       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8328     QualType Scalar = LHSVecType ? RHSType : LHSType;
8329     QualType Vector = LHSVecType ? LHSType : RHSType;
8330     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8331     Diag(Loc,
8332          diag::err_typecheck_vector_not_convertable_implict_truncation)
8333         << ScalarOrVector << Scalar << Vector;
8334
8335     return QualType();
8336   }
8337
8338   // Otherwise, use the generic diagnostic.
8339   Diag(Loc, DiagID)
8340     << LHSType << RHSType
8341     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8342   return QualType();
8343 }
8344
8345 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8346 // expression.  These are mainly cases where the null pointer is used as an
8347 // integer instead of a pointer.
8348 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8349                                 SourceLocation Loc, bool IsCompare) {
8350   // The canonical way to check for a GNU null is with isNullPointerConstant,
8351   // but we use a bit of a hack here for speed; this is a relatively
8352   // hot path, and isNullPointerConstant is slow.
8353   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8354   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8355
8356   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8357
8358   // Avoid analyzing cases where the result will either be invalid (and
8359   // diagnosed as such) or entirely valid and not something to warn about.
8360   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8361       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8362     return;
8363
8364   // Comparison operations would not make sense with a null pointer no matter
8365   // what the other expression is.
8366   if (!IsCompare) {
8367     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8368         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8369         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8370     return;
8371   }
8372
8373   // The rest of the operations only make sense with a null pointer
8374   // if the other expression is a pointer.
8375   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8376       NonNullType->canDecayToPointerType())
8377     return;
8378
8379   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8380       << LHSNull /* LHS is NULL */ << NonNullType
8381       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8382 }
8383
8384 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8385                                                ExprResult &RHS,
8386                                                SourceLocation Loc, bool IsDiv) {
8387   // Check for division/remainder by zero.
8388   llvm::APSInt RHSValue;
8389   if (!RHS.get()->isValueDependent() &&
8390       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8391     S.DiagRuntimeBehavior(Loc, RHS.get(),
8392                           S.PDiag(diag::warn_remainder_division_by_zero)
8393                             << IsDiv << RHS.get()->getSourceRange());
8394 }
8395
8396 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8397                                            SourceLocation Loc,
8398                                            bool IsCompAssign, bool IsDiv) {
8399   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8400
8401   if (LHS.get()->getType()->isVectorType() ||
8402       RHS.get()->getType()->isVectorType())
8403     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8404                                /*AllowBothBool*/getLangOpts().AltiVec,
8405                                /*AllowBoolConversions*/false);
8406
8407   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8408   if (LHS.isInvalid() || RHS.isInvalid())
8409     return QualType();
8410
8411
8412   if (compType.isNull() || !compType->isArithmeticType())
8413     return InvalidOperands(Loc, LHS, RHS);
8414   if (IsDiv)
8415     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8416   return compType;
8417 }
8418
8419 QualType Sema::CheckRemainderOperands(
8420   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8421   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8422
8423   if (LHS.get()->getType()->isVectorType() ||
8424       RHS.get()->getType()->isVectorType()) {
8425     if (LHS.get()->getType()->hasIntegerRepresentation() && 
8426         RHS.get()->getType()->hasIntegerRepresentation())
8427       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8428                                  /*AllowBothBool*/getLangOpts().AltiVec,
8429                                  /*AllowBoolConversions*/false);
8430     return InvalidOperands(Loc, LHS, RHS);
8431   }
8432
8433   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8434   if (LHS.isInvalid() || RHS.isInvalid())
8435     return QualType();
8436
8437   if (compType.isNull() || !compType->isIntegerType())
8438     return InvalidOperands(Loc, LHS, RHS);
8439   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8440   return compType;
8441 }
8442
8443 /// \brief Diagnose invalid arithmetic on two void pointers.
8444 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8445                                                 Expr *LHSExpr, Expr *RHSExpr) {
8446   S.Diag(Loc, S.getLangOpts().CPlusPlus
8447                 ? diag::err_typecheck_pointer_arith_void_type
8448                 : diag::ext_gnu_void_ptr)
8449     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8450                             << RHSExpr->getSourceRange();
8451 }
8452
8453 /// \brief Diagnose invalid arithmetic on a void pointer.
8454 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8455                                             Expr *Pointer) {
8456   S.Diag(Loc, S.getLangOpts().CPlusPlus
8457                 ? diag::err_typecheck_pointer_arith_void_type
8458                 : diag::ext_gnu_void_ptr)
8459     << 0 /* one pointer */ << Pointer->getSourceRange();
8460 }
8461
8462 /// \brief Diagnose invalid arithmetic on two function pointers.
8463 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8464                                                     Expr *LHS, Expr *RHS) {
8465   assert(LHS->getType()->isAnyPointerType());
8466   assert(RHS->getType()->isAnyPointerType());
8467   S.Diag(Loc, S.getLangOpts().CPlusPlus
8468                 ? diag::err_typecheck_pointer_arith_function_type
8469                 : diag::ext_gnu_ptr_func_arith)
8470     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8471     // We only show the second type if it differs from the first.
8472     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8473                                                    RHS->getType())
8474     << RHS->getType()->getPointeeType()
8475     << LHS->getSourceRange() << RHS->getSourceRange();
8476 }
8477
8478 /// \brief Diagnose invalid arithmetic on a function pointer.
8479 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8480                                                 Expr *Pointer) {
8481   assert(Pointer->getType()->isAnyPointerType());
8482   S.Diag(Loc, S.getLangOpts().CPlusPlus
8483                 ? diag::err_typecheck_pointer_arith_function_type
8484                 : diag::ext_gnu_ptr_func_arith)
8485     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8486     << 0 /* one pointer, so only one type */
8487     << Pointer->getSourceRange();
8488 }
8489
8490 /// \brief Emit error if Operand is incomplete pointer type
8491 ///
8492 /// \returns True if pointer has incomplete type
8493 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8494                                                  Expr *Operand) {
8495   QualType ResType = Operand->getType();
8496   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8497     ResType = ResAtomicType->getValueType();
8498
8499   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8500   QualType PointeeTy = ResType->getPointeeType();
8501   return S.RequireCompleteType(Loc, PointeeTy,
8502                                diag::err_typecheck_arithmetic_incomplete_type,
8503                                PointeeTy, Operand->getSourceRange());
8504 }
8505
8506 /// \brief Check the validity of an arithmetic pointer operand.
8507 ///
8508 /// If the operand has pointer type, this code will check for pointer types
8509 /// which are invalid in arithmetic operations. These will be diagnosed
8510 /// appropriately, including whether or not the use is supported as an
8511 /// extension.
8512 ///
8513 /// \returns True when the operand is valid to use (even if as an extension).
8514 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8515                                             Expr *Operand) {
8516   QualType ResType = Operand->getType();
8517   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8518     ResType = ResAtomicType->getValueType();
8519
8520   if (!ResType->isAnyPointerType()) return true;
8521
8522   QualType PointeeTy = ResType->getPointeeType();
8523   if (PointeeTy->isVoidType()) {
8524     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8525     return !S.getLangOpts().CPlusPlus;
8526   }
8527   if (PointeeTy->isFunctionType()) {
8528     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8529     return !S.getLangOpts().CPlusPlus;
8530   }
8531
8532   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8533
8534   return true;
8535 }
8536
8537 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8538 /// operands.
8539 ///
8540 /// This routine will diagnose any invalid arithmetic on pointer operands much
8541 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8542 /// for emitting a single diagnostic even for operations where both LHS and RHS
8543 /// are (potentially problematic) pointers.
8544 ///
8545 /// \returns True when the operand is valid to use (even if as an extension).
8546 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8547                                                 Expr *LHSExpr, Expr *RHSExpr) {
8548   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8549   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8550   if (!isLHSPointer && !isRHSPointer) return true;
8551
8552   QualType LHSPointeeTy, RHSPointeeTy;
8553   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8554   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8555
8556   // if both are pointers check if operation is valid wrt address spaces
8557   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8558     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8559     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8560     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8561       S.Diag(Loc,
8562              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8563           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8564           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8565       return false;
8566     }
8567   }
8568
8569   // Check for arithmetic on pointers to incomplete types.
8570   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8571   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8572   if (isLHSVoidPtr || isRHSVoidPtr) {
8573     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8574     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8575     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8576
8577     return !S.getLangOpts().CPlusPlus;
8578   }
8579
8580   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8581   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8582   if (isLHSFuncPtr || isRHSFuncPtr) {
8583     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8584     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8585                                                                 RHSExpr);
8586     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8587
8588     return !S.getLangOpts().CPlusPlus;
8589   }
8590
8591   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8592     return false;
8593   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8594     return false;
8595
8596   return true;
8597 }
8598
8599 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8600 /// literal.
8601 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8602                                   Expr *LHSExpr, Expr *RHSExpr) {
8603   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8604   Expr* IndexExpr = RHSExpr;
8605   if (!StrExpr) {
8606     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8607     IndexExpr = LHSExpr;
8608   }
8609
8610   bool IsStringPlusInt = StrExpr &&
8611       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8612   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8613     return;
8614
8615   llvm::APSInt index;
8616   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8617     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8618     if (index.isNonNegative() &&
8619         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8620                               index.isUnsigned()))
8621       return;
8622   }
8623
8624   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8625   Self.Diag(OpLoc, diag::warn_string_plus_int)
8626       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8627
8628   // Only print a fixit for "str" + int, not for int + "str".
8629   if (IndexExpr == RHSExpr) {
8630     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8631     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8632         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8633         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8634         << FixItHint::CreateInsertion(EndLoc, "]");
8635   } else
8636     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8637 }
8638
8639 /// \brief Emit a warning when adding a char literal to a string.
8640 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8641                                    Expr *LHSExpr, Expr *RHSExpr) {
8642   const Expr *StringRefExpr = LHSExpr;
8643   const CharacterLiteral *CharExpr =
8644       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8645
8646   if (!CharExpr) {
8647     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8648     StringRefExpr = RHSExpr;
8649   }
8650
8651   if (!CharExpr || !StringRefExpr)
8652     return;
8653
8654   const QualType StringType = StringRefExpr->getType();
8655
8656   // Return if not a PointerType.
8657   if (!StringType->isAnyPointerType())
8658     return;
8659
8660   // Return if not a CharacterType.
8661   if (!StringType->getPointeeType()->isAnyCharacterType())
8662     return;
8663
8664   ASTContext &Ctx = Self.getASTContext();
8665   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8666
8667   const QualType CharType = CharExpr->getType();
8668   if (!CharType->isAnyCharacterType() &&
8669       CharType->isIntegerType() &&
8670       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8671     Self.Diag(OpLoc, diag::warn_string_plus_char)
8672         << DiagRange << Ctx.CharTy;
8673   } else {
8674     Self.Diag(OpLoc, diag::warn_string_plus_char)
8675         << DiagRange << CharExpr->getType();
8676   }
8677
8678   // Only print a fixit for str + char, not for char + str.
8679   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8680     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8681     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8682         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8683         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8684         << FixItHint::CreateInsertion(EndLoc, "]");
8685   } else {
8686     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8687   }
8688 }
8689
8690 /// \brief Emit error when two pointers are incompatible.
8691 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8692                                            Expr *LHSExpr, Expr *RHSExpr) {
8693   assert(LHSExpr->getType()->isAnyPointerType());
8694   assert(RHSExpr->getType()->isAnyPointerType());
8695   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8696     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8697     << RHSExpr->getSourceRange();
8698 }
8699
8700 // C99 6.5.6
8701 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8702                                      SourceLocation Loc, BinaryOperatorKind Opc,
8703                                      QualType* CompLHSTy) {
8704   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8705
8706   if (LHS.get()->getType()->isVectorType() ||
8707       RHS.get()->getType()->isVectorType()) {
8708     QualType compType = CheckVectorOperands(
8709         LHS, RHS, Loc, CompLHSTy,
8710         /*AllowBothBool*/getLangOpts().AltiVec,
8711         /*AllowBoolConversions*/getLangOpts().ZVector);
8712     if (CompLHSTy) *CompLHSTy = compType;
8713     return compType;
8714   }
8715
8716   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8717   if (LHS.isInvalid() || RHS.isInvalid())
8718     return QualType();
8719
8720   // Diagnose "string literal" '+' int and string '+' "char literal".
8721   if (Opc == BO_Add) {
8722     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8723     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8724   }
8725
8726   // handle the common case first (both operands are arithmetic).
8727   if (!compType.isNull() && compType->isArithmeticType()) {
8728     if (CompLHSTy) *CompLHSTy = compType;
8729     return compType;
8730   }
8731
8732   // Type-checking.  Ultimately the pointer's going to be in PExp;
8733   // note that we bias towards the LHS being the pointer.
8734   Expr *PExp = LHS.get(), *IExp = RHS.get();
8735
8736   bool isObjCPointer;
8737   if (PExp->getType()->isPointerType()) {
8738     isObjCPointer = false;
8739   } else if (PExp->getType()->isObjCObjectPointerType()) {
8740     isObjCPointer = true;
8741   } else {
8742     std::swap(PExp, IExp);
8743     if (PExp->getType()->isPointerType()) {
8744       isObjCPointer = false;
8745     } else if (PExp->getType()->isObjCObjectPointerType()) {
8746       isObjCPointer = true;
8747     } else {
8748       return InvalidOperands(Loc, LHS, RHS);
8749     }
8750   }
8751   assert(PExp->getType()->isAnyPointerType());
8752
8753   if (!IExp->getType()->isIntegerType())
8754     return InvalidOperands(Loc, LHS, RHS);
8755
8756   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8757     return QualType();
8758
8759   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8760     return QualType();
8761
8762   // Check array bounds for pointer arithemtic
8763   CheckArrayAccess(PExp, IExp);
8764
8765   if (CompLHSTy) {
8766     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8767     if (LHSTy.isNull()) {
8768       LHSTy = LHS.get()->getType();
8769       if (LHSTy->isPromotableIntegerType())
8770         LHSTy = Context.getPromotedIntegerType(LHSTy);
8771     }
8772     *CompLHSTy = LHSTy;
8773   }
8774
8775   return PExp->getType();
8776 }
8777
8778 // C99 6.5.6
8779 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8780                                         SourceLocation Loc,
8781                                         QualType* CompLHSTy) {
8782   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8783
8784   if (LHS.get()->getType()->isVectorType() ||
8785       RHS.get()->getType()->isVectorType()) {
8786     QualType compType = CheckVectorOperands(
8787         LHS, RHS, Loc, CompLHSTy,
8788         /*AllowBothBool*/getLangOpts().AltiVec,
8789         /*AllowBoolConversions*/getLangOpts().ZVector);
8790     if (CompLHSTy) *CompLHSTy = compType;
8791     return compType;
8792   }
8793
8794   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8795   if (LHS.isInvalid() || RHS.isInvalid())
8796     return QualType();
8797
8798   // Enforce type constraints: C99 6.5.6p3.
8799
8800   // Handle the common case first (both operands are arithmetic).
8801   if (!compType.isNull() && compType->isArithmeticType()) {
8802     if (CompLHSTy) *CompLHSTy = compType;
8803     return compType;
8804   }
8805
8806   // Either ptr - int   or   ptr - ptr.
8807   if (LHS.get()->getType()->isAnyPointerType()) {
8808     QualType lpointee = LHS.get()->getType()->getPointeeType();
8809
8810     // Diagnose bad cases where we step over interface counts.
8811     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8812         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8813       return QualType();
8814
8815     // The result type of a pointer-int computation is the pointer type.
8816     if (RHS.get()->getType()->isIntegerType()) {
8817       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8818         return QualType();
8819
8820       // Check array bounds for pointer arithemtic
8821       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8822                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8823
8824       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8825       return LHS.get()->getType();
8826     }
8827
8828     // Handle pointer-pointer subtractions.
8829     if (const PointerType *RHSPTy
8830           = RHS.get()->getType()->getAs<PointerType>()) {
8831       QualType rpointee = RHSPTy->getPointeeType();
8832
8833       if (getLangOpts().CPlusPlus) {
8834         // Pointee types must be the same: C++ [expr.add]
8835         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8836           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8837         }
8838       } else {
8839         // Pointee types must be compatible C99 6.5.6p3
8840         if (!Context.typesAreCompatible(
8841                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8842                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8843           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8844           return QualType();
8845         }
8846       }
8847
8848       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8849                                                LHS.get(), RHS.get()))
8850         return QualType();
8851
8852       // The pointee type may have zero size.  As an extension, a structure or
8853       // union may have zero size or an array may have zero length.  In this
8854       // case subtraction does not make sense.
8855       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8856         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8857         if (ElementSize.isZero()) {
8858           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8859             << rpointee.getUnqualifiedType()
8860             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8861         }
8862       }
8863
8864       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8865       return Context.getPointerDiffType();
8866     }
8867   }
8868
8869   return InvalidOperands(Loc, LHS, RHS);
8870 }
8871
8872 static bool isScopedEnumerationType(QualType T) {
8873   if (const EnumType *ET = T->getAs<EnumType>())
8874     return ET->getDecl()->isScoped();
8875   return false;
8876 }
8877
8878 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8879                                    SourceLocation Loc, BinaryOperatorKind Opc,
8880                                    QualType LHSType) {
8881   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8882   // so skip remaining warnings as we don't want to modify values within Sema.
8883   if (S.getLangOpts().OpenCL)
8884     return;
8885
8886   llvm::APSInt Right;
8887   // Check right/shifter operand
8888   if (RHS.get()->isValueDependent() ||
8889       !RHS.get()->EvaluateAsInt(Right, S.Context))
8890     return;
8891
8892   if (Right.isNegative()) {
8893     S.DiagRuntimeBehavior(Loc, RHS.get(),
8894                           S.PDiag(diag::warn_shift_negative)
8895                             << RHS.get()->getSourceRange());
8896     return;
8897   }
8898   llvm::APInt LeftBits(Right.getBitWidth(),
8899                        S.Context.getTypeSize(LHS.get()->getType()));
8900   if (Right.uge(LeftBits)) {
8901     S.DiagRuntimeBehavior(Loc, RHS.get(),
8902                           S.PDiag(diag::warn_shift_gt_typewidth)
8903                             << RHS.get()->getSourceRange());
8904     return;
8905   }
8906   if (Opc != BO_Shl)
8907     return;
8908
8909   // When left shifting an ICE which is signed, we can check for overflow which
8910   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8911   // integers have defined behavior modulo one more than the maximum value
8912   // representable in the result type, so never warn for those.
8913   llvm::APSInt Left;
8914   if (LHS.get()->isValueDependent() ||
8915       LHSType->hasUnsignedIntegerRepresentation() ||
8916       !LHS.get()->EvaluateAsInt(Left, S.Context))
8917     return;
8918
8919   // If LHS does not have a signed type and non-negative value
8920   // then, the behavior is undefined. Warn about it.
8921   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8922     S.DiagRuntimeBehavior(Loc, LHS.get(),
8923                           S.PDiag(diag::warn_shift_lhs_negative)
8924                             << LHS.get()->getSourceRange());
8925     return;
8926   }
8927
8928   llvm::APInt ResultBits =
8929       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8930   if (LeftBits.uge(ResultBits))
8931     return;
8932   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8933   Result = Result.shl(Right);
8934
8935   // Print the bit representation of the signed integer as an unsigned
8936   // hexadecimal number.
8937   SmallString<40> HexResult;
8938   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8939
8940   // If we are only missing a sign bit, this is less likely to result in actual
8941   // bugs -- if the result is cast back to an unsigned type, it will have the
8942   // expected value. Thus we place this behind a different warning that can be
8943   // turned off separately if needed.
8944   if (LeftBits == ResultBits - 1) {
8945     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8946         << HexResult << LHSType
8947         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8948     return;
8949   }
8950
8951   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8952     << HexResult.str() << Result.getMinSignedBits() << LHSType
8953     << Left.getBitWidth() << LHS.get()->getSourceRange()
8954     << RHS.get()->getSourceRange();
8955 }
8956
8957 /// \brief Return the resulting type when a vector is shifted
8958 ///        by a scalar or vector shift amount.
8959 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8960                                  SourceLocation Loc, bool IsCompAssign) {
8961   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8962   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8963       !LHS.get()->getType()->isVectorType()) {
8964     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8965       << RHS.get()->getType() << LHS.get()->getType()
8966       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8967     return QualType();
8968   }
8969
8970   if (!IsCompAssign) {
8971     LHS = S.UsualUnaryConversions(LHS.get());
8972     if (LHS.isInvalid()) return QualType();
8973   }
8974
8975   RHS = S.UsualUnaryConversions(RHS.get());
8976   if (RHS.isInvalid()) return QualType();
8977
8978   QualType LHSType = LHS.get()->getType();
8979   // Note that LHS might be a scalar because the routine calls not only in
8980   // OpenCL case.
8981   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8982   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8983
8984   // Note that RHS might not be a vector.
8985   QualType RHSType = RHS.get()->getType();
8986   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8987   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8988
8989   // The operands need to be integers.
8990   if (!LHSEleType->isIntegerType()) {
8991     S.Diag(Loc, diag::err_typecheck_expect_int)
8992       << LHS.get()->getType() << LHS.get()->getSourceRange();
8993     return QualType();
8994   }
8995
8996   if (!RHSEleType->isIntegerType()) {
8997     S.Diag(Loc, diag::err_typecheck_expect_int)
8998       << RHS.get()->getType() << RHS.get()->getSourceRange();
8999     return QualType();
9000   }
9001
9002   if (!LHSVecTy) {
9003     assert(RHSVecTy);
9004     if (IsCompAssign)
9005       return RHSType;
9006     if (LHSEleType != RHSEleType) {
9007       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9008       LHSEleType = RHSEleType;
9009     }
9010     QualType VecTy =
9011         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9012     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9013     LHSType = VecTy;
9014   } else if (RHSVecTy) {
9015     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9016     // are applied component-wise. So if RHS is a vector, then ensure
9017     // that the number of elements is the same as LHS...
9018     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9019       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9020         << LHS.get()->getType() << RHS.get()->getType()
9021         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9022       return QualType();
9023     }
9024     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9025       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9026       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9027       if (LHSBT != RHSBT &&
9028           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9029         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9030             << LHS.get()->getType() << RHS.get()->getType()
9031             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9032       }
9033     }
9034   } else {
9035     // ...else expand RHS to match the number of elements in LHS.
9036     QualType VecTy =
9037       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9038     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9039   }
9040
9041   return LHSType;
9042 }
9043
9044 // C99 6.5.7
9045 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9046                                   SourceLocation Loc, BinaryOperatorKind Opc,
9047                                   bool IsCompAssign) {
9048   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9049
9050   // Vector shifts promote their scalar inputs to vector type.
9051   if (LHS.get()->getType()->isVectorType() ||
9052       RHS.get()->getType()->isVectorType()) {
9053     if (LangOpts.ZVector) {
9054       // The shift operators for the z vector extensions work basically
9055       // like general shifts, except that neither the LHS nor the RHS is
9056       // allowed to be a "vector bool".
9057       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9058         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9059           return InvalidOperands(Loc, LHS, RHS);
9060       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9061         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9062           return InvalidOperands(Loc, LHS, RHS);
9063     }
9064     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9065   }
9066
9067   // Shifts don't perform usual arithmetic conversions, they just do integer
9068   // promotions on each operand. C99 6.5.7p3
9069
9070   // For the LHS, do usual unary conversions, but then reset them away
9071   // if this is a compound assignment.
9072   ExprResult OldLHS = LHS;
9073   LHS = UsualUnaryConversions(LHS.get());
9074   if (LHS.isInvalid())
9075     return QualType();
9076   QualType LHSType = LHS.get()->getType();
9077   if (IsCompAssign) LHS = OldLHS;
9078
9079   // The RHS is simpler.
9080   RHS = UsualUnaryConversions(RHS.get());
9081   if (RHS.isInvalid())
9082     return QualType();
9083   QualType RHSType = RHS.get()->getType();
9084
9085   // C99 6.5.7p2: Each of the operands shall have integer type.
9086   if (!LHSType->hasIntegerRepresentation() ||
9087       !RHSType->hasIntegerRepresentation())
9088     return InvalidOperands(Loc, LHS, RHS);
9089
9090   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9091   // hasIntegerRepresentation() above instead of this.
9092   if (isScopedEnumerationType(LHSType) ||
9093       isScopedEnumerationType(RHSType)) {
9094     return InvalidOperands(Loc, LHS, RHS);
9095   }
9096   // Sanity-check shift operands
9097   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9098
9099   // "The type of the result is that of the promoted left operand."
9100   return LHSType;
9101 }
9102
9103 static bool IsWithinTemplateSpecialization(Decl *D) {
9104   if (DeclContext *DC = D->getDeclContext()) {
9105     if (isa<ClassTemplateSpecializationDecl>(DC))
9106       return true;
9107     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
9108       return FD->isFunctionTemplateSpecialization();
9109   }
9110   return false;
9111 }
9112
9113 /// If two different enums are compared, raise a warning.
9114 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9115                                 Expr *RHS) {
9116   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9117   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9118
9119   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9120   if (!LHSEnumType)
9121     return;
9122   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9123   if (!RHSEnumType)
9124     return;
9125
9126   // Ignore anonymous enums.
9127   if (!LHSEnumType->getDecl()->getIdentifier())
9128     return;
9129   if (!RHSEnumType->getDecl()->getIdentifier())
9130     return;
9131
9132   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9133     return;
9134
9135   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9136       << LHSStrippedType << RHSStrippedType
9137       << LHS->getSourceRange() << RHS->getSourceRange();
9138 }
9139
9140 /// \brief Diagnose bad pointer comparisons.
9141 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9142                                               ExprResult &LHS, ExprResult &RHS,
9143                                               bool IsError) {
9144   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9145                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9146     << LHS.get()->getType() << RHS.get()->getType()
9147     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9148 }
9149
9150 /// \brief Returns false if the pointers are converted to a composite type,
9151 /// true otherwise.
9152 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9153                                            ExprResult &LHS, ExprResult &RHS) {
9154   // C++ [expr.rel]p2:
9155   //   [...] Pointer conversions (4.10) and qualification
9156   //   conversions (4.4) are performed on pointer operands (or on
9157   //   a pointer operand and a null pointer constant) to bring
9158   //   them to their composite pointer type. [...]
9159   //
9160   // C++ [expr.eq]p1 uses the same notion for (in)equality
9161   // comparisons of pointers.
9162
9163   QualType LHSType = LHS.get()->getType();
9164   QualType RHSType = RHS.get()->getType();
9165   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9166          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9167
9168   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9169   if (T.isNull()) {
9170     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9171         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9172       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9173     else
9174       S.InvalidOperands(Loc, LHS, RHS);
9175     return true;
9176   }
9177
9178   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9179   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9180   return false;
9181 }
9182
9183 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9184                                                     ExprResult &LHS,
9185                                                     ExprResult &RHS,
9186                                                     bool IsError) {
9187   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9188                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9189     << LHS.get()->getType() << RHS.get()->getType()
9190     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9191 }
9192
9193 static bool isObjCObjectLiteral(ExprResult &E) {
9194   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9195   case Stmt::ObjCArrayLiteralClass:
9196   case Stmt::ObjCDictionaryLiteralClass:
9197   case Stmt::ObjCStringLiteralClass:
9198   case Stmt::ObjCBoxedExprClass:
9199     return true;
9200   default:
9201     // Note that ObjCBoolLiteral is NOT an object literal!
9202     return false;
9203   }
9204 }
9205
9206 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9207   const ObjCObjectPointerType *Type =
9208     LHS->getType()->getAs<ObjCObjectPointerType>();
9209
9210   // If this is not actually an Objective-C object, bail out.
9211   if (!Type)
9212     return false;
9213
9214   // Get the LHS object's interface type.
9215   QualType InterfaceType = Type->getPointeeType();
9216
9217   // If the RHS isn't an Objective-C object, bail out.
9218   if (!RHS->getType()->isObjCObjectPointerType())
9219     return false;
9220
9221   // Try to find the -isEqual: method.
9222   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9223   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9224                                                       InterfaceType,
9225                                                       /*instance=*/true);
9226   if (!Method) {
9227     if (Type->isObjCIdType()) {
9228       // For 'id', just check the global pool.
9229       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9230                                                   /*receiverId=*/true);
9231     } else {
9232       // Check protocols.
9233       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9234                                              /*instance=*/true);
9235     }
9236   }
9237
9238   if (!Method)
9239     return false;
9240
9241   QualType T = Method->parameters()[0]->getType();
9242   if (!T->isObjCObjectPointerType())
9243     return false;
9244
9245   QualType R = Method->getReturnType();
9246   if (!R->isScalarType())
9247     return false;
9248
9249   return true;
9250 }
9251
9252 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9253   FromE = FromE->IgnoreParenImpCasts();
9254   switch (FromE->getStmtClass()) {
9255     default:
9256       break;
9257     case Stmt::ObjCStringLiteralClass:
9258       // "string literal"
9259       return LK_String;
9260     case Stmt::ObjCArrayLiteralClass:
9261       // "array literal"
9262       return LK_Array;
9263     case Stmt::ObjCDictionaryLiteralClass:
9264       // "dictionary literal"
9265       return LK_Dictionary;
9266     case Stmt::BlockExprClass:
9267       return LK_Block;
9268     case Stmt::ObjCBoxedExprClass: {
9269       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9270       switch (Inner->getStmtClass()) {
9271         case Stmt::IntegerLiteralClass:
9272         case Stmt::FloatingLiteralClass:
9273         case Stmt::CharacterLiteralClass:
9274         case Stmt::ObjCBoolLiteralExprClass:
9275         case Stmt::CXXBoolLiteralExprClass:
9276           // "numeric literal"
9277           return LK_Numeric;
9278         case Stmt::ImplicitCastExprClass: {
9279           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9280           // Boolean literals can be represented by implicit casts.
9281           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9282             return LK_Numeric;
9283           break;
9284         }
9285         default:
9286           break;
9287       }
9288       return LK_Boxed;
9289     }
9290   }
9291   return LK_None;
9292 }
9293
9294 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9295                                           ExprResult &LHS, ExprResult &RHS,
9296                                           BinaryOperator::Opcode Opc){
9297   Expr *Literal;
9298   Expr *Other;
9299   if (isObjCObjectLiteral(LHS)) {
9300     Literal = LHS.get();
9301     Other = RHS.get();
9302   } else {
9303     Literal = RHS.get();
9304     Other = LHS.get();
9305   }
9306
9307   // Don't warn on comparisons against nil.
9308   Other = Other->IgnoreParenCasts();
9309   if (Other->isNullPointerConstant(S.getASTContext(),
9310                                    Expr::NPC_ValueDependentIsNotNull))
9311     return;
9312
9313   // This should be kept in sync with warn_objc_literal_comparison.
9314   // LK_String should always be after the other literals, since it has its own
9315   // warning flag.
9316   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9317   assert(LiteralKind != Sema::LK_Block);
9318   if (LiteralKind == Sema::LK_None) {
9319     llvm_unreachable("Unknown Objective-C object literal kind");
9320   }
9321
9322   if (LiteralKind == Sema::LK_String)
9323     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9324       << Literal->getSourceRange();
9325   else
9326     S.Diag(Loc, diag::warn_objc_literal_comparison)
9327       << LiteralKind << Literal->getSourceRange();
9328
9329   if (BinaryOperator::isEqualityOp(Opc) &&
9330       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9331     SourceLocation Start = LHS.get()->getLocStart();
9332     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9333     CharSourceRange OpRange =
9334       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9335
9336     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9337       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9338       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9339       << FixItHint::CreateInsertion(End, "]");
9340   }
9341 }
9342
9343 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9344 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9345                                            ExprResult &RHS, SourceLocation Loc,
9346                                            BinaryOperatorKind Opc) {
9347   // Check that left hand side is !something.
9348   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9349   if (!UO || UO->getOpcode() != UO_LNot) return;
9350
9351   // Only check if the right hand side is non-bool arithmetic type.
9352   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9353
9354   // Make sure that the something in !something is not bool.
9355   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9356   if (SubExpr->isKnownToHaveBooleanValue()) return;
9357
9358   // Emit warning.
9359   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9360   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9361       << Loc << IsBitwiseOp;
9362
9363   // First note suggest !(x < y)
9364   SourceLocation FirstOpen = SubExpr->getLocStart();
9365   SourceLocation FirstClose = RHS.get()->getLocEnd();
9366   FirstClose = S.getLocForEndOfToken(FirstClose);
9367   if (FirstClose.isInvalid())
9368     FirstOpen = SourceLocation();
9369   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9370       << IsBitwiseOp
9371       << FixItHint::CreateInsertion(FirstOpen, "(")
9372       << FixItHint::CreateInsertion(FirstClose, ")");
9373
9374   // Second note suggests (!x) < y
9375   SourceLocation SecondOpen = LHS.get()->getLocStart();
9376   SourceLocation SecondClose = LHS.get()->getLocEnd();
9377   SecondClose = S.getLocForEndOfToken(SecondClose);
9378   if (SecondClose.isInvalid())
9379     SecondOpen = SourceLocation();
9380   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9381       << FixItHint::CreateInsertion(SecondOpen, "(")
9382       << FixItHint::CreateInsertion(SecondClose, ")");
9383 }
9384
9385 // Get the decl for a simple expression: a reference to a variable,
9386 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9387 static ValueDecl *getCompareDecl(Expr *E) {
9388   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9389     return DR->getDecl();
9390   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9391     if (Ivar->isFreeIvar())
9392       return Ivar->getDecl();
9393   }
9394   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9395     if (Mem->isImplicitAccess())
9396       return Mem->getMemberDecl();
9397   }
9398   return nullptr;
9399 }
9400
9401 // C99 6.5.8, C++ [expr.rel]
9402 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9403                                     SourceLocation Loc, BinaryOperatorKind Opc,
9404                                     bool IsRelational) {
9405   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9406
9407   // Handle vector comparisons separately.
9408   if (LHS.get()->getType()->isVectorType() ||
9409       RHS.get()->getType()->isVectorType())
9410     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9411
9412   QualType LHSType = LHS.get()->getType();
9413   QualType RHSType = RHS.get()->getType();
9414
9415   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9416   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9417
9418   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9419   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9420
9421   if (!LHSType->hasFloatingRepresentation() &&
9422       !(LHSType->isBlockPointerType() && IsRelational) &&
9423       !LHS.get()->getLocStart().isMacroID() &&
9424       !RHS.get()->getLocStart().isMacroID() &&
9425       !inTemplateInstantiation()) {
9426     // For non-floating point types, check for self-comparisons of the form
9427     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9428     // often indicate logic errors in the program.
9429     //
9430     // NOTE: Don't warn about comparison expressions resulting from macro
9431     // expansion. Also don't warn about comparisons which are only self
9432     // comparisons within a template specialization. The warnings should catch
9433     // obvious cases in the definition of the template anyways. The idea is to
9434     // warn when the typed comparison operator will always evaluate to the same
9435     // result.
9436     ValueDecl *DL = getCompareDecl(LHSStripped);
9437     ValueDecl *DR = getCompareDecl(RHSStripped);
9438     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9439       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9440                           << 0 // self-
9441                           << (Opc == BO_EQ
9442                               || Opc == BO_LE
9443                               || Opc == BO_GE));
9444     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9445                !DL->getType()->isReferenceType() &&
9446                !DR->getType()->isReferenceType()) {
9447         // what is it always going to eval to?
9448         char always_evals_to;
9449         switch(Opc) {
9450         case BO_EQ: // e.g. array1 == array2
9451           always_evals_to = 0; // false
9452           break;
9453         case BO_NE: // e.g. array1 != array2
9454           always_evals_to = 1; // true
9455           break;
9456         default:
9457           // best we can say is 'a constant'
9458           always_evals_to = 2; // e.g. array1 <= array2
9459           break;
9460         }
9461         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9462                             << 1 // array
9463                             << always_evals_to);
9464     }
9465
9466     if (isa<CastExpr>(LHSStripped))
9467       LHSStripped = LHSStripped->IgnoreParenCasts();
9468     if (isa<CastExpr>(RHSStripped))
9469       RHSStripped = RHSStripped->IgnoreParenCasts();
9470
9471     // Warn about comparisons against a string constant (unless the other
9472     // operand is null), the user probably wants strcmp.
9473     Expr *literalString = nullptr;
9474     Expr *literalStringStripped = nullptr;
9475     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9476         !RHSStripped->isNullPointerConstant(Context,
9477                                             Expr::NPC_ValueDependentIsNull)) {
9478       literalString = LHS.get();
9479       literalStringStripped = LHSStripped;
9480     } else if ((isa<StringLiteral>(RHSStripped) ||
9481                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9482                !LHSStripped->isNullPointerConstant(Context,
9483                                             Expr::NPC_ValueDependentIsNull)) {
9484       literalString = RHS.get();
9485       literalStringStripped = RHSStripped;
9486     }
9487
9488     if (literalString) {
9489       DiagRuntimeBehavior(Loc, nullptr,
9490         PDiag(diag::warn_stringcompare)
9491           << isa<ObjCEncodeExpr>(literalStringStripped)
9492           << literalString->getSourceRange());
9493     }
9494   }
9495
9496   // C99 6.5.8p3 / C99 6.5.9p4
9497   UsualArithmeticConversions(LHS, RHS);
9498   if (LHS.isInvalid() || RHS.isInvalid())
9499     return QualType();
9500
9501   LHSType = LHS.get()->getType();
9502   RHSType = RHS.get()->getType();
9503
9504   // The result of comparisons is 'bool' in C++, 'int' in C.
9505   QualType ResultTy = Context.getLogicalOperationType();
9506
9507   if (IsRelational) {
9508     if (LHSType->isRealType() && RHSType->isRealType())
9509       return ResultTy;
9510   } else {
9511     // Check for comparisons of floating point operands using != and ==.
9512     if (LHSType->hasFloatingRepresentation())
9513       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9514
9515     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9516       return ResultTy;
9517   }
9518
9519   const Expr::NullPointerConstantKind LHSNullKind =
9520       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9521   const Expr::NullPointerConstantKind RHSNullKind =
9522       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9523   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9524   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9525
9526   if (!IsRelational && LHSIsNull != RHSIsNull) {
9527     bool IsEquality = Opc == BO_EQ;
9528     if (RHSIsNull)
9529       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9530                                    RHS.get()->getSourceRange());
9531     else
9532       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9533                                    LHS.get()->getSourceRange());
9534   }
9535
9536   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9537       (RHSType->isIntegerType() && !RHSIsNull)) {
9538     // Skip normal pointer conversion checks in this case; we have better
9539     // diagnostics for this below.
9540   } else if (getLangOpts().CPlusPlus) {
9541     // Equality comparison of a function pointer to a void pointer is invalid,
9542     // but we allow it as an extension.
9543     // FIXME: If we really want to allow this, should it be part of composite
9544     // pointer type computation so it works in conditionals too?
9545     if (!IsRelational &&
9546         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9547          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9548       // This is a gcc extension compatibility comparison.
9549       // In a SFINAE context, we treat this as a hard error to maintain
9550       // conformance with the C++ standard.
9551       diagnoseFunctionPointerToVoidComparison(
9552           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9553       
9554       if (isSFINAEContext())
9555         return QualType();
9556       
9557       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9558       return ResultTy;
9559     }
9560
9561     // C++ [expr.eq]p2:
9562     //   If at least one operand is a pointer [...] bring them to their
9563     //   composite pointer type.
9564     // C++ [expr.rel]p2:
9565     //   If both operands are pointers, [...] bring them to their composite
9566     //   pointer type.
9567     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9568             (IsRelational ? 2 : 1) &&
9569         (!LangOpts.ObjCAutoRefCount ||
9570          !(LHSType->isObjCObjectPointerType() ||
9571            RHSType->isObjCObjectPointerType()))) {
9572       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9573         return QualType();
9574       else
9575         return ResultTy;
9576     }
9577   } else if (LHSType->isPointerType() &&
9578              RHSType->isPointerType()) { // C99 6.5.8p2
9579     // All of the following pointer-related warnings are GCC extensions, except
9580     // when handling null pointer constants.
9581     QualType LCanPointeeTy =
9582       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9583     QualType RCanPointeeTy =
9584       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9585
9586     // C99 6.5.9p2 and C99 6.5.8p2
9587     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9588                                    RCanPointeeTy.getUnqualifiedType())) {
9589       // Valid unless a relational comparison of function pointers
9590       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9591         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9592           << LHSType << RHSType << LHS.get()->getSourceRange()
9593           << RHS.get()->getSourceRange();
9594       }
9595     } else if (!IsRelational &&
9596                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9597       // Valid unless comparison between non-null pointer and function pointer
9598       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9599           && !LHSIsNull && !RHSIsNull)
9600         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9601                                                 /*isError*/false);
9602     } else {
9603       // Invalid
9604       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9605     }
9606     if (LCanPointeeTy != RCanPointeeTy) {
9607       // Treat NULL constant as a special case in OpenCL.
9608       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9609         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9610         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9611           Diag(Loc,
9612                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9613               << LHSType << RHSType << 0 /* comparison */
9614               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9615         }
9616       }
9617       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9618       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9619       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9620                                                : CK_BitCast;
9621       if (LHSIsNull && !RHSIsNull)
9622         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9623       else
9624         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9625     }
9626     return ResultTy;
9627   }
9628
9629   if (getLangOpts().CPlusPlus) {
9630     // C++ [expr.eq]p4:
9631     //   Two operands of type std::nullptr_t or one operand of type
9632     //   std::nullptr_t and the other a null pointer constant compare equal.
9633     if (!IsRelational && LHSIsNull && RHSIsNull) {
9634       if (LHSType->isNullPtrType()) {
9635         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9636         return ResultTy;
9637       }
9638       if (RHSType->isNullPtrType()) {
9639         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9640         return ResultTy;
9641       }
9642     }
9643
9644     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9645     // These aren't covered by the composite pointer type rules.
9646     if (!IsRelational && RHSType->isNullPtrType() &&
9647         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9648       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9649       return ResultTy;
9650     }
9651     if (!IsRelational && LHSType->isNullPtrType() &&
9652         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9653       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9654       return ResultTy;
9655     }
9656
9657     if (IsRelational &&
9658         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9659          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9660       // HACK: Relational comparison of nullptr_t against a pointer type is
9661       // invalid per DR583, but we allow it within std::less<> and friends,
9662       // since otherwise common uses of it break.
9663       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9664       // friends to have std::nullptr_t overload candidates.
9665       DeclContext *DC = CurContext;
9666       if (isa<FunctionDecl>(DC))
9667         DC = DC->getParent();
9668       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9669         if (CTSD->isInStdNamespace() &&
9670             llvm::StringSwitch<bool>(CTSD->getName())
9671                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9672                 .Default(false)) {
9673           if (RHSType->isNullPtrType())
9674             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9675           else
9676             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9677           return ResultTy;
9678         }
9679       }
9680     }
9681
9682     // C++ [expr.eq]p2:
9683     //   If at least one operand is a pointer to member, [...] bring them to
9684     //   their composite pointer type.
9685     if (!IsRelational &&
9686         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9687       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9688         return QualType();
9689       else
9690         return ResultTy;
9691     }
9692
9693     // Handle scoped enumeration types specifically, since they don't promote
9694     // to integers.
9695     if (LHS.get()->getType()->isEnumeralType() &&
9696         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9697                                        RHS.get()->getType()))
9698       return ResultTy;
9699   }
9700
9701   // Handle block pointer types.
9702   if (!IsRelational && LHSType->isBlockPointerType() &&
9703       RHSType->isBlockPointerType()) {
9704     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9705     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9706
9707     if (!LHSIsNull && !RHSIsNull &&
9708         !Context.typesAreCompatible(lpointee, rpointee)) {
9709       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9710         << LHSType << RHSType << LHS.get()->getSourceRange()
9711         << RHS.get()->getSourceRange();
9712     }
9713     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9714     return ResultTy;
9715   }
9716
9717   // Allow block pointers to be compared with null pointer constants.
9718   if (!IsRelational
9719       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9720           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9721     if (!LHSIsNull && !RHSIsNull) {
9722       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9723              ->getPointeeType()->isVoidType())
9724             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9725                 ->getPointeeType()->isVoidType())))
9726         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9727           << LHSType << RHSType << LHS.get()->getSourceRange()
9728           << RHS.get()->getSourceRange();
9729     }
9730     if (LHSIsNull && !RHSIsNull)
9731       LHS = ImpCastExprToType(LHS.get(), RHSType,
9732                               RHSType->isPointerType() ? CK_BitCast
9733                                 : CK_AnyPointerToBlockPointerCast);
9734     else
9735       RHS = ImpCastExprToType(RHS.get(), LHSType,
9736                               LHSType->isPointerType() ? CK_BitCast
9737                                 : CK_AnyPointerToBlockPointerCast);
9738     return ResultTy;
9739   }
9740
9741   if (LHSType->isObjCObjectPointerType() ||
9742       RHSType->isObjCObjectPointerType()) {
9743     const PointerType *LPT = LHSType->getAs<PointerType>();
9744     const PointerType *RPT = RHSType->getAs<PointerType>();
9745     if (LPT || RPT) {
9746       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9747       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9748
9749       if (!LPtrToVoid && !RPtrToVoid &&
9750           !Context.typesAreCompatible(LHSType, RHSType)) {
9751         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9752                                           /*isError*/false);
9753       }
9754       if (LHSIsNull && !RHSIsNull) {
9755         Expr *E = LHS.get();
9756         if (getLangOpts().ObjCAutoRefCount)
9757           CheckObjCConversion(SourceRange(), RHSType, E,
9758                               CCK_ImplicitConversion);
9759         LHS = ImpCastExprToType(E, RHSType,
9760                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9761       }
9762       else {
9763         Expr *E = RHS.get();
9764         if (getLangOpts().ObjCAutoRefCount)
9765           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9766                               /*Diagnose=*/true,
9767                               /*DiagnoseCFAudited=*/false, Opc);
9768         RHS = ImpCastExprToType(E, LHSType,
9769                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9770       }
9771       return ResultTy;
9772     }
9773     if (LHSType->isObjCObjectPointerType() &&
9774         RHSType->isObjCObjectPointerType()) {
9775       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9776         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9777                                           /*isError*/false);
9778       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9779         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9780
9781       if (LHSIsNull && !RHSIsNull)
9782         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9783       else
9784         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9785       return ResultTy;
9786     }
9787   }
9788   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9789       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9790     unsigned DiagID = 0;
9791     bool isError = false;
9792     if (LangOpts.DebuggerSupport) {
9793       // Under a debugger, allow the comparison of pointers to integers,
9794       // since users tend to want to compare addresses.
9795     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9796                (RHSIsNull && RHSType->isIntegerType())) {
9797       if (IsRelational) {
9798         isError = getLangOpts().CPlusPlus;
9799         DiagID =
9800           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9801                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9802       }
9803     } else if (getLangOpts().CPlusPlus) {
9804       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9805       isError = true;
9806     } else if (IsRelational)
9807       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9808     else
9809       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9810
9811     if (DiagID) {
9812       Diag(Loc, DiagID)
9813         << LHSType << RHSType << LHS.get()->getSourceRange()
9814         << RHS.get()->getSourceRange();
9815       if (isError)
9816         return QualType();
9817     }
9818     
9819     if (LHSType->isIntegerType())
9820       LHS = ImpCastExprToType(LHS.get(), RHSType,
9821                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9822     else
9823       RHS = ImpCastExprToType(RHS.get(), LHSType,
9824                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9825     return ResultTy;
9826   }
9827   
9828   // Handle block pointers.
9829   if (!IsRelational && RHSIsNull
9830       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9831     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9832     return ResultTy;
9833   }
9834   if (!IsRelational && LHSIsNull
9835       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9836     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9837     return ResultTy;
9838   }
9839
9840   if (getLangOpts().OpenCLVersion >= 200) {
9841     if (LHSIsNull && RHSType->isQueueT()) {
9842       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9843       return ResultTy;
9844     }
9845
9846     if (LHSType->isQueueT() && RHSIsNull) {
9847       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9848       return ResultTy;
9849     }
9850   }
9851
9852   return InvalidOperands(Loc, LHS, RHS);
9853 }
9854
9855 // Return a signed ext_vector_type that is of identical size and number of
9856 // elements. For floating point vectors, return an integer type of identical
9857 // size and number of elements. In the non ext_vector_type case, search from
9858 // the largest type to the smallest type to avoid cases where long long == long,
9859 // where long gets picked over long long.
9860 QualType Sema::GetSignedVectorType(QualType V) {
9861   const VectorType *VTy = V->getAs<VectorType>();
9862   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9863
9864   if (isa<ExtVectorType>(VTy)) {
9865     if (TypeSize == Context.getTypeSize(Context.CharTy))
9866       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9867     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9868       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9869     else if (TypeSize == Context.getTypeSize(Context.IntTy))
9870       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9871     else if (TypeSize == Context.getTypeSize(Context.LongTy))
9872       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9873     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9874            "Unhandled vector element size in vector compare");
9875     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9876   }
9877
9878   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9879     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9880                                  VectorType::GenericVector);
9881   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9882     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9883                                  VectorType::GenericVector);
9884   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9885     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9886                                  VectorType::GenericVector);
9887   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9888     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9889                                  VectorType::GenericVector);
9890   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9891          "Unhandled vector element size in vector compare");
9892   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9893                                VectorType::GenericVector);
9894 }
9895
9896 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9897 /// operates on extended vector types.  Instead of producing an IntTy result,
9898 /// like a scalar comparison, a vector comparison produces a vector of integer
9899 /// types.
9900 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9901                                           SourceLocation Loc,
9902                                           bool IsRelational) {
9903   // Check to make sure we're operating on vectors of the same type and width,
9904   // Allowing one side to be a scalar of element type.
9905   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9906                               /*AllowBothBool*/true,
9907                               /*AllowBoolConversions*/getLangOpts().ZVector);
9908   if (vType.isNull())
9909     return vType;
9910
9911   QualType LHSType = LHS.get()->getType();
9912
9913   // If AltiVec, the comparison results in a numeric type, i.e.
9914   // bool for C++, int for C
9915   if (getLangOpts().AltiVec &&
9916       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9917     return Context.getLogicalOperationType();
9918
9919   // For non-floating point types, check for self-comparisons of the form
9920   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9921   // often indicate logic errors in the program.
9922   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9923     if (DeclRefExpr* DRL
9924           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9925       if (DeclRefExpr* DRR
9926             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9927         if (DRL->getDecl() == DRR->getDecl())
9928           DiagRuntimeBehavior(Loc, nullptr,
9929                               PDiag(diag::warn_comparison_always)
9930                                 << 0 // self-
9931                                 << 2 // "a constant"
9932                               );
9933   }
9934
9935   // Check for comparisons of floating point operands using != and ==.
9936   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9937     assert (RHS.get()->getType()->hasFloatingRepresentation());
9938     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9939   }
9940
9941   // Return a signed type for the vector.
9942   return GetSignedVectorType(vType);
9943 }
9944
9945 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9946                                           SourceLocation Loc) {
9947   // Ensure that either both operands are of the same vector type, or
9948   // one operand is of a vector type and the other is of its element type.
9949   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9950                                        /*AllowBothBool*/true,
9951                                        /*AllowBoolConversions*/false);
9952   if (vType.isNull())
9953     return InvalidOperands(Loc, LHS, RHS);
9954   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9955       vType->hasFloatingRepresentation())
9956     return InvalidOperands(Loc, LHS, RHS);
9957   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
9958   //        usage of the logical operators && and || with vectors in C. This
9959   //        check could be notionally dropped.
9960   if (!getLangOpts().CPlusPlus &&
9961       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
9962     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
9963
9964   return GetSignedVectorType(LHS.get()->getType());
9965 }
9966
9967 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9968                                            SourceLocation Loc,
9969                                            BinaryOperatorKind Opc) {
9970   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9971
9972   bool IsCompAssign =
9973       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9974
9975   if (LHS.get()->getType()->isVectorType() ||
9976       RHS.get()->getType()->isVectorType()) {
9977     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9978         RHS.get()->getType()->hasIntegerRepresentation())
9979       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9980                         /*AllowBothBool*/true,
9981                         /*AllowBoolConversions*/getLangOpts().ZVector);
9982     return InvalidOperands(Loc, LHS, RHS);
9983   }
9984
9985   if (Opc == BO_And)
9986     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9987
9988   ExprResult LHSResult = LHS, RHSResult = RHS;
9989   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9990                                                  IsCompAssign);
9991   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9992     return QualType();
9993   LHS = LHSResult.get();
9994   RHS = RHSResult.get();
9995
9996   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9997     return compType;
9998   return InvalidOperands(Loc, LHS, RHS);
9999 }
10000
10001 // C99 6.5.[13,14]
10002 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10003                                            SourceLocation Loc,
10004                                            BinaryOperatorKind Opc) {
10005   // Check vector operands differently.
10006   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10007     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10008   
10009   // Diagnose cases where the user write a logical and/or but probably meant a
10010   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10011   // is a constant.
10012   if (LHS.get()->getType()->isIntegerType() &&
10013       !LHS.get()->getType()->isBooleanType() &&
10014       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10015       // Don't warn in macros or template instantiations.
10016       !Loc.isMacroID() && !inTemplateInstantiation()) {
10017     // If the RHS can be constant folded, and if it constant folds to something
10018     // that isn't 0 or 1 (which indicate a potential logical operation that
10019     // happened to fold to true/false) then warn.
10020     // Parens on the RHS are ignored.
10021     llvm::APSInt Result;
10022     if (RHS.get()->EvaluateAsInt(Result, Context))
10023       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10024            !RHS.get()->getExprLoc().isMacroID()) ||
10025           (Result != 0 && Result != 1)) {
10026         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10027           << RHS.get()->getSourceRange()
10028           << (Opc == BO_LAnd ? "&&" : "||");
10029         // Suggest replacing the logical operator with the bitwise version
10030         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10031             << (Opc == BO_LAnd ? "&" : "|")
10032             << FixItHint::CreateReplacement(SourceRange(
10033                                                  Loc, getLocForEndOfToken(Loc)),
10034                                             Opc == BO_LAnd ? "&" : "|");
10035         if (Opc == BO_LAnd)
10036           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10037           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10038               << FixItHint::CreateRemoval(
10039                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10040                               RHS.get()->getLocEnd()));
10041       }
10042   }
10043
10044   if (!Context.getLangOpts().CPlusPlus) {
10045     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10046     // not operate on the built-in scalar and vector float types.
10047     if (Context.getLangOpts().OpenCL &&
10048         Context.getLangOpts().OpenCLVersion < 120) {
10049       if (LHS.get()->getType()->isFloatingType() ||
10050           RHS.get()->getType()->isFloatingType())
10051         return InvalidOperands(Loc, LHS, RHS);
10052     }
10053
10054     LHS = UsualUnaryConversions(LHS.get());
10055     if (LHS.isInvalid())
10056       return QualType();
10057
10058     RHS = UsualUnaryConversions(RHS.get());
10059     if (RHS.isInvalid())
10060       return QualType();
10061
10062     if (!LHS.get()->getType()->isScalarType() ||
10063         !RHS.get()->getType()->isScalarType())
10064       return InvalidOperands(Loc, LHS, RHS);
10065
10066     return Context.IntTy;
10067   }
10068
10069   // The following is safe because we only use this method for
10070   // non-overloadable operands.
10071
10072   // C++ [expr.log.and]p1
10073   // C++ [expr.log.or]p1
10074   // The operands are both contextually converted to type bool.
10075   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10076   if (LHSRes.isInvalid())
10077     return InvalidOperands(Loc, LHS, RHS);
10078   LHS = LHSRes;
10079
10080   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10081   if (RHSRes.isInvalid())
10082     return InvalidOperands(Loc, LHS, RHS);
10083   RHS = RHSRes;
10084
10085   // C++ [expr.log.and]p2
10086   // C++ [expr.log.or]p2
10087   // The result is a bool.
10088   return Context.BoolTy;
10089 }
10090
10091 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10092   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10093   if (!ME) return false;
10094   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10095   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10096       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10097   if (!Base) return false;
10098   return Base->getMethodDecl() != nullptr;
10099 }
10100
10101 /// Is the given expression (which must be 'const') a reference to a
10102 /// variable which was originally non-const, but which has become
10103 /// 'const' due to being captured within a block?
10104 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10105 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10106   assert(E->isLValue() && E->getType().isConstQualified());
10107   E = E->IgnoreParens();
10108
10109   // Must be a reference to a declaration from an enclosing scope.
10110   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10111   if (!DRE) return NCCK_None;
10112   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10113
10114   // The declaration must be a variable which is not declared 'const'.
10115   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10116   if (!var) return NCCK_None;
10117   if (var->getType().isConstQualified()) return NCCK_None;
10118   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10119
10120   // Decide whether the first capture was for a block or a lambda.
10121   DeclContext *DC = S.CurContext, *Prev = nullptr;
10122   // Decide whether the first capture was for a block or a lambda.
10123   while (DC) {
10124     // For init-capture, it is possible that the variable belongs to the
10125     // template pattern of the current context.
10126     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10127       if (var->isInitCapture() &&
10128           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10129         break;
10130     if (DC == var->getDeclContext())
10131       break;
10132     Prev = DC;
10133     DC = DC->getParent();
10134   }
10135   // Unless we have an init-capture, we've gone one step too far.
10136   if (!var->isInitCapture())
10137     DC = Prev;
10138   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10139 }
10140
10141 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10142   Ty = Ty.getNonReferenceType();
10143   if (IsDereference && Ty->isPointerType())
10144     Ty = Ty->getPointeeType();
10145   return !Ty.isConstQualified();
10146 }
10147
10148 /// Emit the "read-only variable not assignable" error and print notes to give
10149 /// more information about why the variable is not assignable, such as pointing
10150 /// to the declaration of a const variable, showing that a method is const, or
10151 /// that the function is returning a const reference.
10152 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10153                                     SourceLocation Loc) {
10154   // Update err_typecheck_assign_const and note_typecheck_assign_const
10155   // when this enum is changed.
10156   enum {
10157     ConstFunction,
10158     ConstVariable,
10159     ConstMember,
10160     ConstMethod,
10161     ConstUnknown,  // Keep as last element
10162   };
10163
10164   SourceRange ExprRange = E->getSourceRange();
10165
10166   // Only emit one error on the first const found.  All other consts will emit
10167   // a note to the error.
10168   bool DiagnosticEmitted = false;
10169
10170   // Track if the current expression is the result of a dereference, and if the
10171   // next checked expression is the result of a dereference.
10172   bool IsDereference = false;
10173   bool NextIsDereference = false;
10174
10175   // Loop to process MemberExpr chains.
10176   while (true) {
10177     IsDereference = NextIsDereference;
10178
10179     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10180     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10181       NextIsDereference = ME->isArrow();
10182       const ValueDecl *VD = ME->getMemberDecl();
10183       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10184         // Mutable fields can be modified even if the class is const.
10185         if (Field->isMutable()) {
10186           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10187           break;
10188         }
10189
10190         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10191           if (!DiagnosticEmitted) {
10192             S.Diag(Loc, diag::err_typecheck_assign_const)
10193                 << ExprRange << ConstMember << false /*static*/ << Field
10194                 << Field->getType();
10195             DiagnosticEmitted = true;
10196           }
10197           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10198               << ConstMember << false /*static*/ << Field << Field->getType()
10199               << Field->getSourceRange();
10200         }
10201         E = ME->getBase();
10202         continue;
10203       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10204         if (VDecl->getType().isConstQualified()) {
10205           if (!DiagnosticEmitted) {
10206             S.Diag(Loc, diag::err_typecheck_assign_const)
10207                 << ExprRange << ConstMember << true /*static*/ << VDecl
10208                 << VDecl->getType();
10209             DiagnosticEmitted = true;
10210           }
10211           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10212               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10213               << VDecl->getSourceRange();
10214         }
10215         // Static fields do not inherit constness from parents.
10216         break;
10217       }
10218       break;
10219     } // End MemberExpr
10220     break;
10221   }
10222
10223   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10224     // Function calls
10225     const FunctionDecl *FD = CE->getDirectCallee();
10226     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10227       if (!DiagnosticEmitted) {
10228         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10229                                                       << ConstFunction << FD;
10230         DiagnosticEmitted = true;
10231       }
10232       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10233              diag::note_typecheck_assign_const)
10234           << ConstFunction << FD << FD->getReturnType()
10235           << FD->getReturnTypeSourceRange();
10236     }
10237   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10238     // Point to variable declaration.
10239     if (const ValueDecl *VD = DRE->getDecl()) {
10240       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10241         if (!DiagnosticEmitted) {
10242           S.Diag(Loc, diag::err_typecheck_assign_const)
10243               << ExprRange << ConstVariable << VD << VD->getType();
10244           DiagnosticEmitted = true;
10245         }
10246         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10247             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10248       }
10249     }
10250   } else if (isa<CXXThisExpr>(E)) {
10251     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10252       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10253         if (MD->isConst()) {
10254           if (!DiagnosticEmitted) {
10255             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10256                                                           << ConstMethod << MD;
10257             DiagnosticEmitted = true;
10258           }
10259           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10260               << ConstMethod << MD << MD->getSourceRange();
10261         }
10262       }
10263     }
10264   }
10265
10266   if (DiagnosticEmitted)
10267     return;
10268
10269   // Can't determine a more specific message, so display the generic error.
10270   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10271 }
10272
10273 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10274 /// emit an error and return true.  If so, return false.
10275 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10276   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10277
10278   S.CheckShadowingDeclModification(E, Loc);
10279
10280   SourceLocation OrigLoc = Loc;
10281   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10282                                                               &Loc);
10283   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10284     IsLV = Expr::MLV_InvalidMessageExpression;
10285   if (IsLV == Expr::MLV_Valid)
10286     return false;
10287
10288   unsigned DiagID = 0;
10289   bool NeedType = false;
10290   switch (IsLV) { // C99 6.5.16p2
10291   case Expr::MLV_ConstQualified:
10292     // Use a specialized diagnostic when we're assigning to an object
10293     // from an enclosing function or block.
10294     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10295       if (NCCK == NCCK_Block)
10296         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10297       else
10298         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10299       break;
10300     }
10301
10302     // In ARC, use some specialized diagnostics for occasions where we
10303     // infer 'const'.  These are always pseudo-strong variables.
10304     if (S.getLangOpts().ObjCAutoRefCount) {
10305       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10306       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10307         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10308
10309         // Use the normal diagnostic if it's pseudo-__strong but the
10310         // user actually wrote 'const'.
10311         if (var->isARCPseudoStrong() &&
10312             (!var->getTypeSourceInfo() ||
10313              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10314           // There are two pseudo-strong cases:
10315           //  - self
10316           ObjCMethodDecl *method = S.getCurMethodDecl();
10317           if (method && var == method->getSelfDecl())
10318             DiagID = method->isClassMethod()
10319               ? diag::err_typecheck_arc_assign_self_class_method
10320               : diag::err_typecheck_arc_assign_self;
10321
10322           //  - fast enumeration variables
10323           else
10324             DiagID = diag::err_typecheck_arr_assign_enumeration;
10325
10326           SourceRange Assign;
10327           if (Loc != OrigLoc)
10328             Assign = SourceRange(OrigLoc, OrigLoc);
10329           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10330           // We need to preserve the AST regardless, so migration tool
10331           // can do its job.
10332           return false;
10333         }
10334       }
10335     }
10336
10337     // If none of the special cases above are triggered, then this is a
10338     // simple const assignment.
10339     if (DiagID == 0) {
10340       DiagnoseConstAssignment(S, E, Loc);
10341       return true;
10342     }
10343
10344     break;
10345   case Expr::MLV_ConstAddrSpace:
10346     DiagnoseConstAssignment(S, E, Loc);
10347     return true;
10348   case Expr::MLV_ArrayType:
10349   case Expr::MLV_ArrayTemporary:
10350     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10351     NeedType = true;
10352     break;
10353   case Expr::MLV_NotObjectType:
10354     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10355     NeedType = true;
10356     break;
10357   case Expr::MLV_LValueCast:
10358     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10359     break;
10360   case Expr::MLV_Valid:
10361     llvm_unreachable("did not take early return for MLV_Valid");
10362   case Expr::MLV_InvalidExpression:
10363   case Expr::MLV_MemberFunction:
10364   case Expr::MLV_ClassTemporary:
10365     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10366     break;
10367   case Expr::MLV_IncompleteType:
10368   case Expr::MLV_IncompleteVoidType:
10369     return S.RequireCompleteType(Loc, E->getType(),
10370              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10371   case Expr::MLV_DuplicateVectorComponents:
10372     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10373     break;
10374   case Expr::MLV_NoSetterProperty:
10375     llvm_unreachable("readonly properties should be processed differently");
10376   case Expr::MLV_InvalidMessageExpression:
10377     DiagID = diag::err_readonly_message_assignment;
10378     break;
10379   case Expr::MLV_SubObjCPropertySetting:
10380     DiagID = diag::err_no_subobject_property_setting;
10381     break;
10382   }
10383
10384   SourceRange Assign;
10385   if (Loc != OrigLoc)
10386     Assign = SourceRange(OrigLoc, OrigLoc);
10387   if (NeedType)
10388     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10389   else
10390     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10391   return true;
10392 }
10393
10394 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10395                                          SourceLocation Loc,
10396                                          Sema &Sema) {
10397   // C / C++ fields
10398   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10399   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10400   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10401     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10402       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10403   }
10404
10405   // Objective-C instance variables
10406   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10407   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10408   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10409     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10410     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10411     if (RL && RR && RL->getDecl() == RR->getDecl())
10412       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10413   }
10414 }
10415
10416 // C99 6.5.16.1
10417 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10418                                        SourceLocation Loc,
10419                                        QualType CompoundType) {
10420   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10421
10422   // Verify that LHS is a modifiable lvalue, and emit error if not.
10423   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10424     return QualType();
10425
10426   QualType LHSType = LHSExpr->getType();
10427   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10428                                              CompoundType;
10429   // OpenCL v1.2 s6.1.1.1 p2:
10430   // The half data type can only be used to declare a pointer to a buffer that
10431   // contains half values
10432   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10433     LHSType->isHalfType()) {
10434     Diag(Loc, diag::err_opencl_half_load_store) << 1
10435         << LHSType.getUnqualifiedType();
10436     return QualType();
10437   }
10438     
10439   AssignConvertType ConvTy;
10440   if (CompoundType.isNull()) {
10441     Expr *RHSCheck = RHS.get();
10442
10443     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10444
10445     QualType LHSTy(LHSType);
10446     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10447     if (RHS.isInvalid())
10448       return QualType();
10449     // Special case of NSObject attributes on c-style pointer types.
10450     if (ConvTy == IncompatiblePointer &&
10451         ((Context.isObjCNSObjectType(LHSType) &&
10452           RHSType->isObjCObjectPointerType()) ||
10453          (Context.isObjCNSObjectType(RHSType) &&
10454           LHSType->isObjCObjectPointerType())))
10455       ConvTy = Compatible;
10456
10457     if (ConvTy == Compatible &&
10458         LHSType->isObjCObjectType())
10459         Diag(Loc, diag::err_objc_object_assignment)
10460           << LHSType;
10461
10462     // If the RHS is a unary plus or minus, check to see if they = and + are
10463     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10464     // instead of "x += 4".
10465     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10466       RHSCheck = ICE->getSubExpr();
10467     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10468       if ((UO->getOpcode() == UO_Plus ||
10469            UO->getOpcode() == UO_Minus) &&
10470           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10471           // Only if the two operators are exactly adjacent.
10472           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10473           // And there is a space or other character before the subexpr of the
10474           // unary +/-.  We don't want to warn on "x=-1".
10475           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10476           UO->getSubExpr()->getLocStart().isFileID()) {
10477         Diag(Loc, diag::warn_not_compound_assign)
10478           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10479           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10480       }
10481     }
10482
10483     if (ConvTy == Compatible) {
10484       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10485         // Warn about retain cycles where a block captures the LHS, but
10486         // not if the LHS is a simple variable into which the block is
10487         // being stored...unless that variable can be captured by reference!
10488         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10489         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10490         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10491           checkRetainCycles(LHSExpr, RHS.get());
10492       }
10493
10494       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10495           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10496         // It is safe to assign a weak reference into a strong variable.
10497         // Although this code can still have problems:
10498         //   id x = self.weakProp;
10499         //   id y = self.weakProp;
10500         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10501         // paths through the function. This should be revisited if
10502         // -Wrepeated-use-of-weak is made flow-sensitive.
10503         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10504         // variable, which will be valid for the current autorelease scope.
10505         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10506                              RHS.get()->getLocStart()))
10507           getCurFunction()->markSafeWeakUse(RHS.get());
10508
10509       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10510         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10511       }
10512     }
10513   } else {
10514     // Compound assignment "x += y"
10515     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10516   }
10517
10518   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10519                                RHS.get(), AA_Assigning))
10520     return QualType();
10521
10522   CheckForNullPointerDereference(*this, LHSExpr);
10523
10524   // C99 6.5.16p3: The type of an assignment expression is the type of the
10525   // left operand unless the left operand has qualified type, in which case
10526   // it is the unqualified version of the type of the left operand.
10527   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10528   // is converted to the type of the assignment expression (above).
10529   // C++ 5.17p1: the type of the assignment expression is that of its left
10530   // operand.
10531   return (getLangOpts().CPlusPlus
10532           ? LHSType : LHSType.getUnqualifiedType());
10533 }
10534
10535 // Only ignore explicit casts to void.
10536 static bool IgnoreCommaOperand(const Expr *E) {
10537   E = E->IgnoreParens();
10538
10539   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10540     if (CE->getCastKind() == CK_ToVoid) {
10541       return true;
10542     }
10543   }
10544
10545   return false;
10546 }
10547
10548 // Look for instances where it is likely the comma operator is confused with
10549 // another operator.  There is a whitelist of acceptable expressions for the
10550 // left hand side of the comma operator, otherwise emit a warning.
10551 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10552   // No warnings in macros
10553   if (Loc.isMacroID())
10554     return;
10555
10556   // Don't warn in template instantiations.
10557   if (inTemplateInstantiation())
10558     return;
10559
10560   // Scope isn't fine-grained enough to whitelist the specific cases, so
10561   // instead, skip more than needed, then call back into here with the
10562   // CommaVisitor in SemaStmt.cpp.
10563   // The whitelisted locations are the initialization and increment portions
10564   // of a for loop.  The additional checks are on the condition of
10565   // if statements, do/while loops, and for loops.
10566   const unsigned ForIncrementFlags =
10567       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10568   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10569   const unsigned ScopeFlags = getCurScope()->getFlags();
10570   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10571       (ScopeFlags & ForInitFlags) == ForInitFlags)
10572     return;
10573
10574   // If there are multiple comma operators used together, get the RHS of the
10575   // of the comma operator as the LHS.
10576   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10577     if (BO->getOpcode() != BO_Comma)
10578       break;
10579     LHS = BO->getRHS();
10580   }
10581
10582   // Only allow some expressions on LHS to not warn.
10583   if (IgnoreCommaOperand(LHS))
10584     return;
10585
10586   Diag(Loc, diag::warn_comma_operator);
10587   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10588       << LHS->getSourceRange()
10589       << FixItHint::CreateInsertion(LHS->getLocStart(),
10590                                     LangOpts.CPlusPlus ? "static_cast<void>("
10591                                                        : "(void)(")
10592       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10593                                     ")");
10594 }
10595
10596 // C99 6.5.17
10597 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10598                                    SourceLocation Loc) {
10599   LHS = S.CheckPlaceholderExpr(LHS.get());
10600   RHS = S.CheckPlaceholderExpr(RHS.get());
10601   if (LHS.isInvalid() || RHS.isInvalid())
10602     return QualType();
10603
10604   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10605   // operands, but not unary promotions.
10606   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10607
10608   // So we treat the LHS as a ignored value, and in C++ we allow the
10609   // containing site to determine what should be done with the RHS.
10610   LHS = S.IgnoredValueConversions(LHS.get());
10611   if (LHS.isInvalid())
10612     return QualType();
10613
10614   S.DiagnoseUnusedExprResult(LHS.get());
10615
10616   if (!S.getLangOpts().CPlusPlus) {
10617     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10618     if (RHS.isInvalid())
10619       return QualType();
10620     if (!RHS.get()->getType()->isVoidType())
10621       S.RequireCompleteType(Loc, RHS.get()->getType(),
10622                             diag::err_incomplete_type);
10623   }
10624
10625   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10626     S.DiagnoseCommaOperator(LHS.get(), Loc);
10627
10628   return RHS.get()->getType();
10629 }
10630
10631 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10632 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10633 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10634                                                ExprValueKind &VK,
10635                                                ExprObjectKind &OK,
10636                                                SourceLocation OpLoc,
10637                                                bool IsInc, bool IsPrefix) {
10638   if (Op->isTypeDependent())
10639     return S.Context.DependentTy;
10640
10641   QualType ResType = Op->getType();
10642   // Atomic types can be used for increment / decrement where the non-atomic
10643   // versions can, so ignore the _Atomic() specifier for the purpose of
10644   // checking.
10645   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10646     ResType = ResAtomicType->getValueType();
10647
10648   assert(!ResType.isNull() && "no type for increment/decrement expression");
10649
10650   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10651     // Decrement of bool is not allowed.
10652     if (!IsInc) {
10653       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10654       return QualType();
10655     }
10656     // Increment of bool sets it to true, but is deprecated.
10657     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10658                                               : diag::warn_increment_bool)
10659       << Op->getSourceRange();
10660   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10661     // Error on enum increments and decrements in C++ mode
10662     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10663     return QualType();
10664   } else if (ResType->isRealType()) {
10665     // OK!
10666   } else if (ResType->isPointerType()) {
10667     // C99 6.5.2.4p2, 6.5.6p2
10668     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10669       return QualType();
10670   } else if (ResType->isObjCObjectPointerType()) {
10671     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10672     // Otherwise, we just need a complete type.
10673     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10674         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10675       return QualType();    
10676   } else if (ResType->isAnyComplexType()) {
10677     // C99 does not support ++/-- on complex types, we allow as an extension.
10678     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10679       << ResType << Op->getSourceRange();
10680   } else if (ResType->isPlaceholderType()) {
10681     ExprResult PR = S.CheckPlaceholderExpr(Op);
10682     if (PR.isInvalid()) return QualType();
10683     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10684                                           IsInc, IsPrefix);
10685   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10686     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10687   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10688              (ResType->getAs<VectorType>()->getVectorKind() !=
10689               VectorType::AltiVecBool)) {
10690     // The z vector extensions allow ++ and -- for non-bool vectors.
10691   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10692             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10693     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10694   } else {
10695     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10696       << ResType << int(IsInc) << Op->getSourceRange();
10697     return QualType();
10698   }
10699   // At this point, we know we have a real, complex or pointer type.
10700   // Now make sure the operand is a modifiable lvalue.
10701   if (CheckForModifiableLvalue(Op, OpLoc, S))
10702     return QualType();
10703   // In C++, a prefix increment is the same type as the operand. Otherwise
10704   // (in C or with postfix), the increment is the unqualified type of the
10705   // operand.
10706   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10707     VK = VK_LValue;
10708     OK = Op->getObjectKind();
10709     return ResType;
10710   } else {
10711     VK = VK_RValue;
10712     return ResType.getUnqualifiedType();
10713   }
10714 }
10715   
10716
10717 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10718 /// This routine allows us to typecheck complex/recursive expressions
10719 /// where the declaration is needed for type checking. We only need to
10720 /// handle cases when the expression references a function designator
10721 /// or is an lvalue. Here are some examples:
10722 ///  - &(x) => x
10723 ///  - &*****f => f for f a function designator.
10724 ///  - &s.xx => s
10725 ///  - &s.zz[1].yy -> s, if zz is an array
10726 ///  - *(x + 1) -> x, if x is an array
10727 ///  - &"123"[2] -> 0
10728 ///  - & __real__ x -> x
10729 static ValueDecl *getPrimaryDecl(Expr *E) {
10730   switch (E->getStmtClass()) {
10731   case Stmt::DeclRefExprClass:
10732     return cast<DeclRefExpr>(E)->getDecl();
10733   case Stmt::MemberExprClass:
10734     // If this is an arrow operator, the address is an offset from
10735     // the base's value, so the object the base refers to is
10736     // irrelevant.
10737     if (cast<MemberExpr>(E)->isArrow())
10738       return nullptr;
10739     // Otherwise, the expression refers to a part of the base
10740     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10741   case Stmt::ArraySubscriptExprClass: {
10742     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10743     // promotion of register arrays earlier.
10744     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10745     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10746       if (ICE->getSubExpr()->getType()->isArrayType())
10747         return getPrimaryDecl(ICE->getSubExpr());
10748     }
10749     return nullptr;
10750   }
10751   case Stmt::UnaryOperatorClass: {
10752     UnaryOperator *UO = cast<UnaryOperator>(E);
10753
10754     switch(UO->getOpcode()) {
10755     case UO_Real:
10756     case UO_Imag:
10757     case UO_Extension:
10758       return getPrimaryDecl(UO->getSubExpr());
10759     default:
10760       return nullptr;
10761     }
10762   }
10763   case Stmt::ParenExprClass:
10764     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10765   case Stmt::ImplicitCastExprClass:
10766     // If the result of an implicit cast is an l-value, we care about
10767     // the sub-expression; otherwise, the result here doesn't matter.
10768     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10769   default:
10770     return nullptr;
10771   }
10772 }
10773
10774 namespace {
10775   enum {
10776     AO_Bit_Field = 0,
10777     AO_Vector_Element = 1,
10778     AO_Property_Expansion = 2,
10779     AO_Register_Variable = 3,
10780     AO_No_Error = 4
10781   };
10782 }
10783 /// \brief Diagnose invalid operand for address of operations.
10784 ///
10785 /// \param Type The type of operand which cannot have its address taken.
10786 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10787                                          Expr *E, unsigned Type) {
10788   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10789 }
10790
10791 /// CheckAddressOfOperand - The operand of & must be either a function
10792 /// designator or an lvalue designating an object. If it is an lvalue, the
10793 /// object cannot be declared with storage class register or be a bit field.
10794 /// Note: The usual conversions are *not* applied to the operand of the &
10795 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10796 /// In C++, the operand might be an overloaded function name, in which case
10797 /// we allow the '&' but retain the overloaded-function type.
10798 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10799   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10800     if (PTy->getKind() == BuiltinType::Overload) {
10801       Expr *E = OrigOp.get()->IgnoreParens();
10802       if (!isa<OverloadExpr>(E)) {
10803         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10804         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10805           << OrigOp.get()->getSourceRange();
10806         return QualType();
10807       }
10808
10809       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10810       if (isa<UnresolvedMemberExpr>(Ovl))
10811         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10812           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10813             << OrigOp.get()->getSourceRange();
10814           return QualType();
10815         }
10816
10817       return Context.OverloadTy;
10818     }
10819
10820     if (PTy->getKind() == BuiltinType::UnknownAny)
10821       return Context.UnknownAnyTy;
10822
10823     if (PTy->getKind() == BuiltinType::BoundMember) {
10824       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10825         << OrigOp.get()->getSourceRange();
10826       return QualType();
10827     }
10828
10829     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10830     if (OrigOp.isInvalid()) return QualType();
10831   }
10832
10833   if (OrigOp.get()->isTypeDependent())
10834     return Context.DependentTy;
10835
10836   assert(!OrigOp.get()->getType()->isPlaceholderType());
10837
10838   // Make sure to ignore parentheses in subsequent checks
10839   Expr *op = OrigOp.get()->IgnoreParens();
10840
10841   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10842   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10843     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10844     return QualType();
10845   }
10846
10847   if (getLangOpts().C99) {
10848     // Implement C99-only parts of addressof rules.
10849     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10850       if (uOp->getOpcode() == UO_Deref)
10851         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10852         // (assuming the deref expression is valid).
10853         return uOp->getSubExpr()->getType();
10854     }
10855     // Technically, there should be a check for array subscript
10856     // expressions here, but the result of one is always an lvalue anyway.
10857   }
10858   ValueDecl *dcl = getPrimaryDecl(op);
10859
10860   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10861     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10862                                            op->getLocStart()))
10863       return QualType();
10864
10865   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10866   unsigned AddressOfError = AO_No_Error;
10867
10868   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
10869     bool sfinae = (bool)isSFINAEContext();
10870     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10871                                   : diag::ext_typecheck_addrof_temporary)
10872       << op->getType() << op->getSourceRange();
10873     if (sfinae)
10874       return QualType();
10875     // Materialize the temporary as an lvalue so that we can take its address.
10876     OrigOp = op =
10877         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10878   } else if (isa<ObjCSelectorExpr>(op)) {
10879     return Context.getPointerType(op->getType());
10880   } else if (lval == Expr::LV_MemberFunction) {
10881     // If it's an instance method, make a member pointer.
10882     // The expression must have exactly the form &A::foo.
10883
10884     // If the underlying expression isn't a decl ref, give up.
10885     if (!isa<DeclRefExpr>(op)) {
10886       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10887         << OrigOp.get()->getSourceRange();
10888       return QualType();
10889     }
10890     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10891     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10892
10893     // The id-expression was parenthesized.
10894     if (OrigOp.get() != DRE) {
10895       Diag(OpLoc, diag::err_parens_pointer_member_function)
10896         << OrigOp.get()->getSourceRange();
10897
10898     // The method was named without a qualifier.
10899     } else if (!DRE->getQualifier()) {
10900       if (MD->getParent()->getName().empty())
10901         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10902           << op->getSourceRange();
10903       else {
10904         SmallString<32> Str;
10905         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10906         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10907           << op->getSourceRange()
10908           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10909       }
10910     }
10911
10912     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10913     if (isa<CXXDestructorDecl>(MD))
10914       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10915
10916     QualType MPTy = Context.getMemberPointerType(
10917         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10918     // Under the MS ABI, lock down the inheritance model now.
10919     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10920       (void)isCompleteType(OpLoc, MPTy);
10921     return MPTy;
10922   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10923     // C99 6.5.3.2p1
10924     // The operand must be either an l-value or a function designator
10925     if (!op->getType()->isFunctionType()) {
10926       // Use a special diagnostic for loads from property references.
10927       if (isa<PseudoObjectExpr>(op)) {
10928         AddressOfError = AO_Property_Expansion;
10929       } else {
10930         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10931           << op->getType() << op->getSourceRange();
10932         return QualType();
10933       }
10934     }
10935   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10936     // The operand cannot be a bit-field
10937     AddressOfError = AO_Bit_Field;
10938   } else if (op->getObjectKind() == OK_VectorComponent) {
10939     // The operand cannot be an element of a vector
10940     AddressOfError = AO_Vector_Element;
10941   } else if (dcl) { // C99 6.5.3.2p1
10942     // We have an lvalue with a decl. Make sure the decl is not declared
10943     // with the register storage-class specifier.
10944     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10945       // in C++ it is not error to take address of a register
10946       // variable (c++03 7.1.1P3)
10947       if (vd->getStorageClass() == SC_Register &&
10948           !getLangOpts().CPlusPlus) {
10949         AddressOfError = AO_Register_Variable;
10950       }
10951     } else if (isa<MSPropertyDecl>(dcl)) {
10952       AddressOfError = AO_Property_Expansion;
10953     } else if (isa<FunctionTemplateDecl>(dcl)) {
10954       return Context.OverloadTy;
10955     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10956       // Okay: we can take the address of a field.
10957       // Could be a pointer to member, though, if there is an explicit
10958       // scope qualifier for the class.
10959       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10960         DeclContext *Ctx = dcl->getDeclContext();
10961         if (Ctx && Ctx->isRecord()) {
10962           if (dcl->getType()->isReferenceType()) {
10963             Diag(OpLoc,
10964                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10965               << dcl->getDeclName() << dcl->getType();
10966             return QualType();
10967           }
10968
10969           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10970             Ctx = Ctx->getParent();
10971
10972           QualType MPTy = Context.getMemberPointerType(
10973               op->getType(),
10974               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10975           // Under the MS ABI, lock down the inheritance model now.
10976           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10977             (void)isCompleteType(OpLoc, MPTy);
10978           return MPTy;
10979         }
10980       }
10981     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10982                !isa<BindingDecl>(dcl))
10983       llvm_unreachable("Unknown/unexpected decl type");
10984   }
10985
10986   if (AddressOfError != AO_No_Error) {
10987     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10988     return QualType();
10989   }
10990
10991   if (lval == Expr::LV_IncompleteVoidType) {
10992     // Taking the address of a void variable is technically illegal, but we
10993     // allow it in cases which are otherwise valid.
10994     // Example: "extern void x; void* y = &x;".
10995     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10996   }
10997
10998   // If the operand has type "type", the result has type "pointer to type".
10999   if (op->getType()->isObjCObjectType())
11000     return Context.getObjCObjectPointerType(op->getType());
11001
11002   CheckAddressOfPackedMember(op);
11003
11004   return Context.getPointerType(op->getType());
11005 }
11006
11007 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11008   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11009   if (!DRE)
11010     return;
11011   const Decl *D = DRE->getDecl();
11012   if (!D)
11013     return;
11014   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11015   if (!Param)
11016     return;
11017   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11018     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11019       return;
11020   if (FunctionScopeInfo *FD = S.getCurFunction())
11021     if (!FD->ModifiedNonNullParams.count(Param))
11022       FD->ModifiedNonNullParams.insert(Param);
11023 }
11024
11025 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11026 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11027                                         SourceLocation OpLoc) {
11028   if (Op->isTypeDependent())
11029     return S.Context.DependentTy;
11030
11031   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11032   if (ConvResult.isInvalid())
11033     return QualType();
11034   Op = ConvResult.get();
11035   QualType OpTy = Op->getType();
11036   QualType Result;
11037
11038   if (isa<CXXReinterpretCastExpr>(Op)) {
11039     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11040     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11041                                      Op->getSourceRange());
11042   }
11043
11044   if (const PointerType *PT = OpTy->getAs<PointerType>())
11045   {
11046     Result = PT->getPointeeType();
11047   }
11048   else if (const ObjCObjectPointerType *OPT =
11049              OpTy->getAs<ObjCObjectPointerType>())
11050     Result = OPT->getPointeeType();
11051   else {
11052     ExprResult PR = S.CheckPlaceholderExpr(Op);
11053     if (PR.isInvalid()) return QualType();
11054     if (PR.get() != Op)
11055       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11056   }
11057
11058   if (Result.isNull()) {
11059     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11060       << OpTy << Op->getSourceRange();
11061     return QualType();
11062   }
11063
11064   // Note that per both C89 and C99, indirection is always legal, even if Result
11065   // is an incomplete type or void.  It would be possible to warn about
11066   // dereferencing a void pointer, but it's completely well-defined, and such a
11067   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11068   // for pointers to 'void' but is fine for any other pointer type:
11069   //
11070   // C++ [expr.unary.op]p1:
11071   //   [...] the expression to which [the unary * operator] is applied shall
11072   //   be a pointer to an object type, or a pointer to a function type
11073   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11074     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11075       << OpTy << Op->getSourceRange();
11076
11077   // Dereferences are usually l-values...
11078   VK = VK_LValue;
11079
11080   // ...except that certain expressions are never l-values in C.
11081   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11082     VK = VK_RValue;
11083   
11084   return Result;
11085 }
11086
11087 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11088   BinaryOperatorKind Opc;
11089   switch (Kind) {
11090   default: llvm_unreachable("Unknown binop!");
11091   case tok::periodstar:           Opc = BO_PtrMemD; break;
11092   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11093   case tok::star:                 Opc = BO_Mul; break;
11094   case tok::slash:                Opc = BO_Div; break;
11095   case tok::percent:              Opc = BO_Rem; break;
11096   case tok::plus:                 Opc = BO_Add; break;
11097   case tok::minus:                Opc = BO_Sub; break;
11098   case tok::lessless:             Opc = BO_Shl; break;
11099   case tok::greatergreater:       Opc = BO_Shr; break;
11100   case tok::lessequal:            Opc = BO_LE; break;
11101   case tok::less:                 Opc = BO_LT; break;
11102   case tok::greaterequal:         Opc = BO_GE; break;
11103   case tok::greater:              Opc = BO_GT; break;
11104   case tok::exclaimequal:         Opc = BO_NE; break;
11105   case tok::equalequal:           Opc = BO_EQ; break;
11106   case tok::amp:                  Opc = BO_And; break;
11107   case tok::caret:                Opc = BO_Xor; break;
11108   case tok::pipe:                 Opc = BO_Or; break;
11109   case tok::ampamp:               Opc = BO_LAnd; break;
11110   case tok::pipepipe:             Opc = BO_LOr; break;
11111   case tok::equal:                Opc = BO_Assign; break;
11112   case tok::starequal:            Opc = BO_MulAssign; break;
11113   case tok::slashequal:           Opc = BO_DivAssign; break;
11114   case tok::percentequal:         Opc = BO_RemAssign; break;
11115   case tok::plusequal:            Opc = BO_AddAssign; break;
11116   case tok::minusequal:           Opc = BO_SubAssign; break;
11117   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11118   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11119   case tok::ampequal:             Opc = BO_AndAssign; break;
11120   case tok::caretequal:           Opc = BO_XorAssign; break;
11121   case tok::pipeequal:            Opc = BO_OrAssign; break;
11122   case tok::comma:                Opc = BO_Comma; break;
11123   }
11124   return Opc;
11125 }
11126
11127 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11128   tok::TokenKind Kind) {
11129   UnaryOperatorKind Opc;
11130   switch (Kind) {
11131   default: llvm_unreachable("Unknown unary op!");
11132   case tok::plusplus:     Opc = UO_PreInc; break;
11133   case tok::minusminus:   Opc = UO_PreDec; break;
11134   case tok::amp:          Opc = UO_AddrOf; break;
11135   case tok::star:         Opc = UO_Deref; break;
11136   case tok::plus:         Opc = UO_Plus; break;
11137   case tok::minus:        Opc = UO_Minus; break;
11138   case tok::tilde:        Opc = UO_Not; break;
11139   case tok::exclaim:      Opc = UO_LNot; break;
11140   case tok::kw___real:    Opc = UO_Real; break;
11141   case tok::kw___imag:    Opc = UO_Imag; break;
11142   case tok::kw___extension__: Opc = UO_Extension; break;
11143   }
11144   return Opc;
11145 }
11146
11147 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11148 /// This warning is only emitted for builtin assignment operations. It is also
11149 /// suppressed in the event of macro expansions.
11150 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11151                                    SourceLocation OpLoc) {
11152   if (S.inTemplateInstantiation())
11153     return;
11154   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11155     return;
11156   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11157   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11158   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11159   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11160   if (!LHSDeclRef || !RHSDeclRef ||
11161       LHSDeclRef->getLocation().isMacroID() ||
11162       RHSDeclRef->getLocation().isMacroID())
11163     return;
11164   const ValueDecl *LHSDecl =
11165     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11166   const ValueDecl *RHSDecl =
11167     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11168   if (LHSDecl != RHSDecl)
11169     return;
11170   if (LHSDecl->getType().isVolatileQualified())
11171     return;
11172   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11173     if (RefTy->getPointeeType().isVolatileQualified())
11174       return;
11175
11176   S.Diag(OpLoc, diag::warn_self_assignment)
11177       << LHSDeclRef->getType()
11178       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11179 }
11180
11181 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11182 /// is usually indicative of introspection within the Objective-C pointer.
11183 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11184                                           SourceLocation OpLoc) {
11185   if (!S.getLangOpts().ObjC1)
11186     return;
11187
11188   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11189   const Expr *LHS = L.get();
11190   const Expr *RHS = R.get();
11191
11192   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11193     ObjCPointerExpr = LHS;
11194     OtherExpr = RHS;
11195   }
11196   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11197     ObjCPointerExpr = RHS;
11198     OtherExpr = LHS;
11199   }
11200
11201   // This warning is deliberately made very specific to reduce false
11202   // positives with logic that uses '&' for hashing.  This logic mainly
11203   // looks for code trying to introspect into tagged pointers, which
11204   // code should generally never do.
11205   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11206     unsigned Diag = diag::warn_objc_pointer_masking;
11207     // Determine if we are introspecting the result of performSelectorXXX.
11208     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11209     // Special case messages to -performSelector and friends, which
11210     // can return non-pointer values boxed in a pointer value.
11211     // Some clients may wish to silence warnings in this subcase.
11212     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11213       Selector S = ME->getSelector();
11214       StringRef SelArg0 = S.getNameForSlot(0);
11215       if (SelArg0.startswith("performSelector"))
11216         Diag = diag::warn_objc_pointer_masking_performSelector;
11217     }
11218     
11219     S.Diag(OpLoc, Diag)
11220       << ObjCPointerExpr->getSourceRange();
11221   }
11222 }
11223
11224 static NamedDecl *getDeclFromExpr(Expr *E) {
11225   if (!E)
11226     return nullptr;
11227   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11228     return DRE->getDecl();
11229   if (auto *ME = dyn_cast<MemberExpr>(E))
11230     return ME->getMemberDecl();
11231   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11232     return IRE->getDecl();
11233   return nullptr;
11234 }
11235
11236 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11237 /// operator @p Opc at location @c TokLoc. This routine only supports
11238 /// built-in operations; ActOnBinOp handles overloaded operators.
11239 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11240                                     BinaryOperatorKind Opc,
11241                                     Expr *LHSExpr, Expr *RHSExpr) {
11242   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11243     // The syntax only allows initializer lists on the RHS of assignment,
11244     // so we don't need to worry about accepting invalid code for
11245     // non-assignment operators.
11246     // C++11 5.17p9:
11247     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11248     //   of x = {} is x = T().
11249     InitializationKind Kind =
11250         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11251     InitializedEntity Entity =
11252         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11253     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11254     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11255     if (Init.isInvalid())
11256       return Init;
11257     RHSExpr = Init.get();
11258   }
11259
11260   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11261   QualType ResultTy;     // Result type of the binary operator.
11262   // The following two variables are used for compound assignment operators
11263   QualType CompLHSTy;    // Type of LHS after promotions for computation
11264   QualType CompResultTy; // Type of computation result
11265   ExprValueKind VK = VK_RValue;
11266   ExprObjectKind OK = OK_Ordinary;
11267
11268   if (!getLangOpts().CPlusPlus) {
11269     // C cannot handle TypoExpr nodes on either side of a binop because it
11270     // doesn't handle dependent types properly, so make sure any TypoExprs have
11271     // been dealt with before checking the operands.
11272     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11273     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11274       if (Opc != BO_Assign)
11275         return ExprResult(E);
11276       // Avoid correcting the RHS to the same Expr as the LHS.
11277       Decl *D = getDeclFromExpr(E);
11278       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11279     });
11280     if (!LHS.isUsable() || !RHS.isUsable())
11281       return ExprError();
11282   }
11283
11284   if (getLangOpts().OpenCL) {
11285     QualType LHSTy = LHSExpr->getType();
11286     QualType RHSTy = RHSExpr->getType();
11287     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11288     // the ATOMIC_VAR_INIT macro.
11289     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11290       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11291       if (BO_Assign == Opc)
11292         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11293       else
11294         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11295       return ExprError();
11296     }
11297
11298     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11299     // only with a builtin functions and therefore should be disallowed here.
11300     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11301         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11302         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11303         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11304       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11305       return ExprError();
11306     }
11307   }
11308
11309   switch (Opc) {
11310   case BO_Assign:
11311     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11312     if (getLangOpts().CPlusPlus &&
11313         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11314       VK = LHS.get()->getValueKind();
11315       OK = LHS.get()->getObjectKind();
11316     }
11317     if (!ResultTy.isNull()) {
11318       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11319       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11320     }
11321     RecordModifiableNonNullParam(*this, LHS.get());
11322     break;
11323   case BO_PtrMemD:
11324   case BO_PtrMemI:
11325     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11326                                             Opc == BO_PtrMemI);
11327     break;
11328   case BO_Mul:
11329   case BO_Div:
11330     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11331                                            Opc == BO_Div);
11332     break;
11333   case BO_Rem:
11334     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11335     break;
11336   case BO_Add:
11337     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11338     break;
11339   case BO_Sub:
11340     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11341     break;
11342   case BO_Shl:
11343   case BO_Shr:
11344     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11345     break;
11346   case BO_LE:
11347   case BO_LT:
11348   case BO_GE:
11349   case BO_GT:
11350     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11351     break;
11352   case BO_EQ:
11353   case BO_NE:
11354     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11355     break;
11356   case BO_And:
11357     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11358     LLVM_FALLTHROUGH;
11359   case BO_Xor:
11360   case BO_Or:
11361     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11362     break;
11363   case BO_LAnd:
11364   case BO_LOr:
11365     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11366     break;
11367   case BO_MulAssign:
11368   case BO_DivAssign:
11369     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11370                                                Opc == BO_DivAssign);
11371     CompLHSTy = CompResultTy;
11372     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11373       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11374     break;
11375   case BO_RemAssign:
11376     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11377     CompLHSTy = CompResultTy;
11378     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11379       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11380     break;
11381   case BO_AddAssign:
11382     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11383     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11384       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11385     break;
11386   case BO_SubAssign:
11387     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11388     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11389       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11390     break;
11391   case BO_ShlAssign:
11392   case BO_ShrAssign:
11393     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11394     CompLHSTy = CompResultTy;
11395     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11396       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11397     break;
11398   case BO_AndAssign:
11399   case BO_OrAssign: // fallthrough
11400     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11401     LLVM_FALLTHROUGH;
11402   case BO_XorAssign:
11403     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11404     CompLHSTy = CompResultTy;
11405     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11406       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11407     break;
11408   case BO_Comma:
11409     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11410     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11411       VK = RHS.get()->getValueKind();
11412       OK = RHS.get()->getObjectKind();
11413     }
11414     break;
11415   }
11416   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11417     return ExprError();
11418
11419   // Check for array bounds violations for both sides of the BinaryOperator
11420   CheckArrayAccess(LHS.get());
11421   CheckArrayAccess(RHS.get());
11422
11423   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11424     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11425                                                  &Context.Idents.get("object_setClass"),
11426                                                  SourceLocation(), LookupOrdinaryName);
11427     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11428       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11429       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11430       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11431       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11432       FixItHint::CreateInsertion(RHSLocEnd, ")");
11433     }
11434     else
11435       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11436   }
11437   else if (const ObjCIvarRefExpr *OIRE =
11438            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11439     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11440   
11441   if (CompResultTy.isNull())
11442     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11443                                         OK, OpLoc, FPFeatures);
11444   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11445       OK_ObjCProperty) {
11446     VK = VK_LValue;
11447     OK = LHS.get()->getObjectKind();
11448   }
11449   return new (Context) CompoundAssignOperator(
11450       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11451       OpLoc, FPFeatures);
11452 }
11453
11454 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11455 /// operators are mixed in a way that suggests that the programmer forgot that
11456 /// comparison operators have higher precedence. The most typical example of
11457 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11458 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11459                                       SourceLocation OpLoc, Expr *LHSExpr,
11460                                       Expr *RHSExpr) {
11461   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11462   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11463
11464   // Check that one of the sides is a comparison operator and the other isn't.
11465   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11466   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11467   if (isLeftComp == isRightComp)
11468     return;
11469
11470   // Bitwise operations are sometimes used as eager logical ops.
11471   // Don't diagnose this.
11472   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11473   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11474   if (isLeftBitwise || isRightBitwise)
11475     return;
11476
11477   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11478                                                    OpLoc)
11479                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11480   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11481   SourceRange ParensRange = isLeftComp ?
11482       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11483     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11484
11485   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11486     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11487   SuggestParentheses(Self, OpLoc,
11488     Self.PDiag(diag::note_precedence_silence) << OpStr,
11489     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11490   SuggestParentheses(Self, OpLoc,
11491     Self.PDiag(diag::note_precedence_bitwise_first)
11492       << BinaryOperator::getOpcodeStr(Opc),
11493     ParensRange);
11494 }
11495
11496 /// \brief It accepts a '&&' expr that is inside a '||' one.
11497 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11498 /// in parentheses.
11499 static void
11500 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11501                                        BinaryOperator *Bop) {
11502   assert(Bop->getOpcode() == BO_LAnd);
11503   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11504       << Bop->getSourceRange() << OpLoc;
11505   SuggestParentheses(Self, Bop->getOperatorLoc(),
11506     Self.PDiag(diag::note_precedence_silence)
11507       << Bop->getOpcodeStr(),
11508     Bop->getSourceRange());
11509 }
11510
11511 /// \brief Returns true if the given expression can be evaluated as a constant
11512 /// 'true'.
11513 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11514   bool Res;
11515   return !E->isValueDependent() &&
11516          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11517 }
11518
11519 /// \brief Returns true if the given expression can be evaluated as a constant
11520 /// 'false'.
11521 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11522   bool Res;
11523   return !E->isValueDependent() &&
11524          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11525 }
11526
11527 /// \brief Look for '&&' in the left hand of a '||' expr.
11528 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11529                                              Expr *LHSExpr, Expr *RHSExpr) {
11530   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11531     if (Bop->getOpcode() == BO_LAnd) {
11532       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11533       if (EvaluatesAsFalse(S, RHSExpr))
11534         return;
11535       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11536       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11537         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11538     } else if (Bop->getOpcode() == BO_LOr) {
11539       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11540         // If it's "a || b && 1 || c" we didn't warn earlier for
11541         // "a || b && 1", but warn now.
11542         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11543           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11544       }
11545     }
11546   }
11547 }
11548
11549 /// \brief Look for '&&' in the right hand of a '||' expr.
11550 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11551                                              Expr *LHSExpr, Expr *RHSExpr) {
11552   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11553     if (Bop->getOpcode() == BO_LAnd) {
11554       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11555       if (EvaluatesAsFalse(S, LHSExpr))
11556         return;
11557       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11558       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11559         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11560     }
11561   }
11562 }
11563
11564 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11565 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11566 /// the '&' expression in parentheses.
11567 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11568                                          SourceLocation OpLoc, Expr *SubExpr) {
11569   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11570     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11571       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11572         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11573         << Bop->getSourceRange() << OpLoc;
11574       SuggestParentheses(S, Bop->getOperatorLoc(),
11575         S.PDiag(diag::note_precedence_silence)
11576           << Bop->getOpcodeStr(),
11577         Bop->getSourceRange());
11578     }
11579   }
11580 }
11581
11582 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11583                                     Expr *SubExpr, StringRef Shift) {
11584   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11585     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11586       StringRef Op = Bop->getOpcodeStr();
11587       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11588           << Bop->getSourceRange() << OpLoc << Shift << Op;
11589       SuggestParentheses(S, Bop->getOperatorLoc(),
11590           S.PDiag(diag::note_precedence_silence) << Op,
11591           Bop->getSourceRange());
11592     }
11593   }
11594 }
11595
11596 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11597                                  Expr *LHSExpr, Expr *RHSExpr) {
11598   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11599   if (!OCE)
11600     return;
11601
11602   FunctionDecl *FD = OCE->getDirectCallee();
11603   if (!FD || !FD->isOverloadedOperator())
11604     return;
11605
11606   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11607   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11608     return;
11609
11610   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11611       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11612       << (Kind == OO_LessLess);
11613   SuggestParentheses(S, OCE->getOperatorLoc(),
11614                      S.PDiag(diag::note_precedence_silence)
11615                          << (Kind == OO_LessLess ? "<<" : ">>"),
11616                      OCE->getSourceRange());
11617   SuggestParentheses(S, OpLoc,
11618                      S.PDiag(diag::note_evaluate_comparison_first),
11619                      SourceRange(OCE->getArg(1)->getLocStart(),
11620                                  RHSExpr->getLocEnd()));
11621 }
11622
11623 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11624 /// precedence.
11625 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11626                                     SourceLocation OpLoc, Expr *LHSExpr,
11627                                     Expr *RHSExpr){
11628   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11629   if (BinaryOperator::isBitwiseOp(Opc))
11630     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11631
11632   // Diagnose "arg1 & arg2 | arg3"
11633   if ((Opc == BO_Or || Opc == BO_Xor) &&
11634       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11635     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11636     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11637   }
11638
11639   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11640   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11641   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11642     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11643     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11644   }
11645
11646   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11647       || Opc == BO_Shr) {
11648     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11649     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11650     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11651   }
11652
11653   // Warn on overloaded shift operators and comparisons, such as:
11654   // cout << 5 == 4;
11655   if (BinaryOperator::isComparisonOp(Opc))
11656     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11657 }
11658
11659 // Binary Operators.  'Tok' is the token for the operator.
11660 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11661                             tok::TokenKind Kind,
11662                             Expr *LHSExpr, Expr *RHSExpr) {
11663   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11664   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11665   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11666
11667   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11668   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11669
11670   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11671 }
11672
11673 /// Build an overloaded binary operator expression in the given scope.
11674 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11675                                        BinaryOperatorKind Opc,
11676                                        Expr *LHS, Expr *RHS) {
11677   // Find all of the overloaded operators visible from this
11678   // point. We perform both an operator-name lookup from the local
11679   // scope and an argument-dependent lookup based on the types of
11680   // the arguments.
11681   UnresolvedSet<16> Functions;
11682   OverloadedOperatorKind OverOp
11683     = BinaryOperator::getOverloadedOperator(Opc);
11684   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11685     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11686                                    RHS->getType(), Functions);
11687
11688   // Build the (potentially-overloaded, potentially-dependent)
11689   // binary operation.
11690   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11691 }
11692
11693 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11694                             BinaryOperatorKind Opc,
11695                             Expr *LHSExpr, Expr *RHSExpr) {
11696   // We want to end up calling one of checkPseudoObjectAssignment
11697   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11698   // both expressions are overloadable or either is type-dependent),
11699   // or CreateBuiltinBinOp (in any other case).  We also want to get
11700   // any placeholder types out of the way.
11701
11702   // Handle pseudo-objects in the LHS.
11703   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11704     // Assignments with a pseudo-object l-value need special analysis.
11705     if (pty->getKind() == BuiltinType::PseudoObject &&
11706         BinaryOperator::isAssignmentOp(Opc))
11707       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11708
11709     // Don't resolve overloads if the other type is overloadable.
11710     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11711       // We can't actually test that if we still have a placeholder,
11712       // though.  Fortunately, none of the exceptions we see in that
11713       // code below are valid when the LHS is an overload set.  Note
11714       // that an overload set can be dependently-typed, but it never
11715       // instantiates to having an overloadable type.
11716       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11717       if (resolvedRHS.isInvalid()) return ExprError();
11718       RHSExpr = resolvedRHS.get();
11719
11720       if (RHSExpr->isTypeDependent() ||
11721           RHSExpr->getType()->isOverloadableType())
11722         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11723     }
11724
11725     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
11726     // template, diagnose the missing 'template' keyword instead of diagnosing
11727     // an invalid use of a bound member function.
11728     //
11729     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
11730     // to C++1z [over.over]/1.4, but we already checked for that case above.
11731     if (Opc == BO_LT && inTemplateInstantiation() &&
11732         (pty->getKind() == BuiltinType::BoundMember ||
11733          pty->getKind() == BuiltinType::Overload)) {
11734       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
11735       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
11736           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
11737             return isa<FunctionTemplateDecl>(ND);
11738           })) {
11739         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
11740                                 : OE->getNameLoc(),
11741              diag::err_template_kw_missing)
11742           << OE->getName().getAsString() << "";
11743         return ExprError();
11744       }
11745     }
11746         
11747     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11748     if (LHS.isInvalid()) return ExprError();
11749     LHSExpr = LHS.get();
11750   }
11751
11752   // Handle pseudo-objects in the RHS.
11753   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11754     // An overload in the RHS can potentially be resolved by the type
11755     // being assigned to.
11756     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11757       if (getLangOpts().CPlusPlus &&
11758           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11759            LHSExpr->getType()->isOverloadableType()))
11760         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11761
11762       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11763     }
11764
11765     // Don't resolve overloads if the other type is overloadable.
11766     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11767         LHSExpr->getType()->isOverloadableType())
11768       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11769
11770     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11771     if (!resolvedRHS.isUsable()) return ExprError();
11772     RHSExpr = resolvedRHS.get();
11773   }
11774
11775   if (getLangOpts().CPlusPlus) {
11776     // If either expression is type-dependent, always build an
11777     // overloaded op.
11778     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11779       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11780
11781     // Otherwise, build an overloaded op if either expression has an
11782     // overloadable type.
11783     if (LHSExpr->getType()->isOverloadableType() ||
11784         RHSExpr->getType()->isOverloadableType())
11785       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11786   }
11787
11788   // Build a built-in binary operation.
11789   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11790 }
11791
11792 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11793                                       UnaryOperatorKind Opc,
11794                                       Expr *InputExpr) {
11795   ExprResult Input = InputExpr;
11796   ExprValueKind VK = VK_RValue;
11797   ExprObjectKind OK = OK_Ordinary;
11798   QualType resultType;
11799   if (getLangOpts().OpenCL) {
11800     QualType Ty = InputExpr->getType();
11801     // The only legal unary operation for atomics is '&'.
11802     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11803     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11804     // only with a builtin functions and therefore should be disallowed here.
11805         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11806         || Ty->isBlockPointerType())) {
11807       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11808                        << InputExpr->getType()
11809                        << Input.get()->getSourceRange());
11810     }
11811   }
11812   switch (Opc) {
11813   case UO_PreInc:
11814   case UO_PreDec:
11815   case UO_PostInc:
11816   case UO_PostDec:
11817     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11818                                                 OpLoc,
11819                                                 Opc == UO_PreInc ||
11820                                                 Opc == UO_PostInc,
11821                                                 Opc == UO_PreInc ||
11822                                                 Opc == UO_PreDec);
11823     break;
11824   case UO_AddrOf:
11825     resultType = CheckAddressOfOperand(Input, OpLoc);
11826     RecordModifiableNonNullParam(*this, InputExpr);
11827     break;
11828   case UO_Deref: {
11829     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11830     if (Input.isInvalid()) return ExprError();
11831     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11832     break;
11833   }
11834   case UO_Plus:
11835   case UO_Minus:
11836     Input = UsualUnaryConversions(Input.get());
11837     if (Input.isInvalid()) return ExprError();
11838     resultType = Input.get()->getType();
11839     if (resultType->isDependentType())
11840       break;
11841     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11842       break;
11843     else if (resultType->isVectorType() &&
11844              // The z vector extensions don't allow + or - with bool vectors.
11845              (!Context.getLangOpts().ZVector ||
11846               resultType->getAs<VectorType>()->getVectorKind() !=
11847               VectorType::AltiVecBool))
11848       break;
11849     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11850              Opc == UO_Plus &&
11851              resultType->isPointerType())
11852       break;
11853
11854     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11855       << resultType << Input.get()->getSourceRange());
11856
11857   case UO_Not: // bitwise complement
11858     Input = UsualUnaryConversions(Input.get());
11859     if (Input.isInvalid())
11860       return ExprError();
11861     resultType = Input.get()->getType();
11862     if (resultType->isDependentType())
11863       break;
11864     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11865     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11866       // C99 does not support '~' for complex conjugation.
11867       Diag(OpLoc, diag::ext_integer_complement_complex)
11868           << resultType << Input.get()->getSourceRange();
11869     else if (resultType->hasIntegerRepresentation())
11870       break;
11871     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
11872       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11873       // on vector float types.
11874       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11875       if (!T->isIntegerType())
11876         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11877                           << resultType << Input.get()->getSourceRange());
11878     } else {
11879       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11880                        << resultType << Input.get()->getSourceRange());
11881     }
11882     break;
11883
11884   case UO_LNot: // logical negation
11885     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11886     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11887     if (Input.isInvalid()) return ExprError();
11888     resultType = Input.get()->getType();
11889
11890     // Though we still have to promote half FP to float...
11891     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11892       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11893       resultType = Context.FloatTy;
11894     }
11895
11896     if (resultType->isDependentType())
11897       break;
11898     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11899       // C99 6.5.3.3p1: ok, fallthrough;
11900       if (Context.getLangOpts().CPlusPlus) {
11901         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11902         // operand contextually converted to bool.
11903         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11904                                   ScalarTypeToBooleanCastKind(resultType));
11905       } else if (Context.getLangOpts().OpenCL &&
11906                  Context.getLangOpts().OpenCLVersion < 120) {
11907         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11908         // operate on scalar float types.
11909         if (!resultType->isIntegerType() && !resultType->isPointerType())
11910           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11911                            << resultType << Input.get()->getSourceRange());
11912       }
11913     } else if (resultType->isExtVectorType()) {
11914       if (Context.getLangOpts().OpenCL &&
11915           Context.getLangOpts().OpenCLVersion < 120) {
11916         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11917         // operate on vector float types.
11918         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11919         if (!T->isIntegerType())
11920           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11921                            << resultType << Input.get()->getSourceRange());
11922       }
11923       // Vector logical not returns the signed variant of the operand type.
11924       resultType = GetSignedVectorType(resultType);
11925       break;
11926     } else {
11927       // FIXME: GCC's vector extension permits the usage of '!' with a vector
11928       //        type in C++. We should allow that here too.
11929       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11930         << resultType << Input.get()->getSourceRange());
11931     }
11932     
11933     // LNot always has type int. C99 6.5.3.3p5.
11934     // In C++, it's bool. C++ 5.3.1p8
11935     resultType = Context.getLogicalOperationType();
11936     break;
11937   case UO_Real:
11938   case UO_Imag:
11939     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11940     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11941     // complex l-values to ordinary l-values and all other values to r-values.
11942     if (Input.isInvalid()) return ExprError();
11943     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11944       if (Input.get()->getValueKind() != VK_RValue &&
11945           Input.get()->getObjectKind() == OK_Ordinary)
11946         VK = Input.get()->getValueKind();
11947     } else if (!getLangOpts().CPlusPlus) {
11948       // In C, a volatile scalar is read by __imag. In C++, it is not.
11949       Input = DefaultLvalueConversion(Input.get());
11950     }
11951     break;
11952   case UO_Extension:
11953     resultType = Input.get()->getType();
11954     VK = Input.get()->getValueKind();
11955     OK = Input.get()->getObjectKind();
11956     break;
11957   case UO_Coawait:
11958     // It's unnessesary to represent the pass-through operator co_await in the
11959     // AST; just return the input expression instead.
11960     assert(!Input.get()->getType()->isDependentType() &&
11961                    "the co_await expression must be non-dependant before "
11962                    "building operator co_await");
11963     return Input;
11964   }
11965   if (resultType.isNull() || Input.isInvalid())
11966     return ExprError();
11967
11968   // Check for array bounds violations in the operand of the UnaryOperator,
11969   // except for the '*' and '&' operators that have to be handled specially
11970   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11971   // that are explicitly defined as valid by the standard).
11972   if (Opc != UO_AddrOf && Opc != UO_Deref)
11973     CheckArrayAccess(Input.get());
11974
11975   return new (Context)
11976       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11977 }
11978
11979 /// \brief Determine whether the given expression is a qualified member
11980 /// access expression, of a form that could be turned into a pointer to member
11981 /// with the address-of operator.
11982 static bool isQualifiedMemberAccess(Expr *E) {
11983   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11984     if (!DRE->getQualifier())
11985       return false;
11986     
11987     ValueDecl *VD = DRE->getDecl();
11988     if (!VD->isCXXClassMember())
11989       return false;
11990     
11991     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11992       return true;
11993     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11994       return Method->isInstance();
11995       
11996     return false;
11997   }
11998   
11999   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12000     if (!ULE->getQualifier())
12001       return false;
12002     
12003     for (NamedDecl *D : ULE->decls()) {
12004       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12005         if (Method->isInstance())
12006           return true;
12007       } else {
12008         // Overload set does not contain methods.
12009         break;
12010       }
12011     }
12012     
12013     return false;
12014   }
12015   
12016   return false;
12017 }
12018
12019 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12020                               UnaryOperatorKind Opc, Expr *Input) {
12021   // First things first: handle placeholders so that the
12022   // overloaded-operator check considers the right type.
12023   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12024     // Increment and decrement of pseudo-object references.
12025     if (pty->getKind() == BuiltinType::PseudoObject &&
12026         UnaryOperator::isIncrementDecrementOp(Opc))
12027       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12028
12029     // extension is always a builtin operator.
12030     if (Opc == UO_Extension)
12031       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12032
12033     // & gets special logic for several kinds of placeholder.
12034     // The builtin code knows what to do.
12035     if (Opc == UO_AddrOf &&
12036         (pty->getKind() == BuiltinType::Overload ||
12037          pty->getKind() == BuiltinType::UnknownAny ||
12038          pty->getKind() == BuiltinType::BoundMember))
12039       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12040
12041     // Anything else needs to be handled now.
12042     ExprResult Result = CheckPlaceholderExpr(Input);
12043     if (Result.isInvalid()) return ExprError();
12044     Input = Result.get();
12045   }
12046
12047   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12048       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12049       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12050     // Find all of the overloaded operators visible from this
12051     // point. We perform both an operator-name lookup from the local
12052     // scope and an argument-dependent lookup based on the types of
12053     // the arguments.
12054     UnresolvedSet<16> Functions;
12055     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12056     if (S && OverOp != OO_None)
12057       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12058                                    Functions);
12059
12060     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12061   }
12062
12063   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12064 }
12065
12066 // Unary Operators.  'Tok' is the token for the operator.
12067 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12068                               tok::TokenKind Op, Expr *Input) {
12069   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12070 }
12071
12072 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12073 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12074                                 LabelDecl *TheDecl) {
12075   TheDecl->markUsed(Context);
12076   // Create the AST node.  The address of a label always has type 'void*'.
12077   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12078                                      Context.getPointerType(Context.VoidTy));
12079 }
12080
12081 /// Given the last statement in a statement-expression, check whether
12082 /// the result is a producing expression (like a call to an
12083 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12084 /// release out of the full-expression.  Otherwise, return null.
12085 /// Cannot fail.
12086 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12087   // Should always be wrapped with one of these.
12088   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12089   if (!cleanups) return nullptr;
12090
12091   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12092   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12093     return nullptr;
12094
12095   // Splice out the cast.  This shouldn't modify any interesting
12096   // features of the statement.
12097   Expr *producer = cast->getSubExpr();
12098   assert(producer->getType() == cast->getType());
12099   assert(producer->getValueKind() == cast->getValueKind());
12100   cleanups->setSubExpr(producer);
12101   return cleanups;
12102 }
12103
12104 void Sema::ActOnStartStmtExpr() {
12105   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12106 }
12107
12108 void Sema::ActOnStmtExprError() {
12109   // Note that function is also called by TreeTransform when leaving a
12110   // StmtExpr scope without rebuilding anything.
12111
12112   DiscardCleanupsInEvaluationContext();
12113   PopExpressionEvaluationContext();
12114 }
12115
12116 ExprResult
12117 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12118                     SourceLocation RPLoc) { // "({..})"
12119   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12120   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12121
12122   if (hasAnyUnrecoverableErrorsInThisFunction())
12123     DiscardCleanupsInEvaluationContext();
12124   assert(!Cleanup.exprNeedsCleanups() &&
12125          "cleanups within StmtExpr not correctly bound!");
12126   PopExpressionEvaluationContext();
12127
12128   // FIXME: there are a variety of strange constraints to enforce here, for
12129   // example, it is not possible to goto into a stmt expression apparently.
12130   // More semantic analysis is needed.
12131
12132   // If there are sub-stmts in the compound stmt, take the type of the last one
12133   // as the type of the stmtexpr.
12134   QualType Ty = Context.VoidTy;
12135   bool StmtExprMayBindToTemp = false;
12136   if (!Compound->body_empty()) {
12137     Stmt *LastStmt = Compound->body_back();
12138     LabelStmt *LastLabelStmt = nullptr;
12139     // If LastStmt is a label, skip down through into the body.
12140     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12141       LastLabelStmt = Label;
12142       LastStmt = Label->getSubStmt();
12143     }
12144
12145     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12146       // Do function/array conversion on the last expression, but not
12147       // lvalue-to-rvalue.  However, initialize an unqualified type.
12148       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12149       if (LastExpr.isInvalid())
12150         return ExprError();
12151       Ty = LastExpr.get()->getType().getUnqualifiedType();
12152
12153       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12154         // In ARC, if the final expression ends in a consume, splice
12155         // the consume out and bind it later.  In the alternate case
12156         // (when dealing with a retainable type), the result
12157         // initialization will create a produce.  In both cases the
12158         // result will be +1, and we'll need to balance that out with
12159         // a bind.
12160         if (Expr *rebuiltLastStmt
12161               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12162           LastExpr = rebuiltLastStmt;
12163         } else {
12164           LastExpr = PerformCopyInitialization(
12165                             InitializedEntity::InitializeResult(LPLoc, 
12166                                                                 Ty,
12167                                                                 false),
12168                                                    SourceLocation(),
12169                                                LastExpr);
12170         }
12171
12172         if (LastExpr.isInvalid())
12173           return ExprError();
12174         if (LastExpr.get() != nullptr) {
12175           if (!LastLabelStmt)
12176             Compound->setLastStmt(LastExpr.get());
12177           else
12178             LastLabelStmt->setSubStmt(LastExpr.get());
12179           StmtExprMayBindToTemp = true;
12180         }
12181       }
12182     }
12183   }
12184
12185   // FIXME: Check that expression type is complete/non-abstract; statement
12186   // expressions are not lvalues.
12187   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12188   if (StmtExprMayBindToTemp)
12189     return MaybeBindToTemporary(ResStmtExpr);
12190   return ResStmtExpr;
12191 }
12192
12193 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12194                                       TypeSourceInfo *TInfo,
12195                                       ArrayRef<OffsetOfComponent> Components,
12196                                       SourceLocation RParenLoc) {
12197   QualType ArgTy = TInfo->getType();
12198   bool Dependent = ArgTy->isDependentType();
12199   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12200   
12201   // We must have at least one component that refers to the type, and the first
12202   // one is known to be a field designator.  Verify that the ArgTy represents
12203   // a struct/union/class.
12204   if (!Dependent && !ArgTy->isRecordType())
12205     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
12206                        << ArgTy << TypeRange);
12207   
12208   // Type must be complete per C99 7.17p3 because a declaring a variable
12209   // with an incomplete type would be ill-formed.
12210   if (!Dependent 
12211       && RequireCompleteType(BuiltinLoc, ArgTy,
12212                              diag::err_offsetof_incomplete_type, TypeRange))
12213     return ExprError();
12214   
12215   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12216   // GCC extension, diagnose them.
12217   // FIXME: This diagnostic isn't actually visible because the location is in
12218   // a system header!
12219   if (Components.size() != 1)
12220     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12221       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12222   
12223   bool DidWarnAboutNonPOD = false;
12224   QualType CurrentType = ArgTy;
12225   SmallVector<OffsetOfNode, 4> Comps;
12226   SmallVector<Expr*, 4> Exprs;
12227   for (const OffsetOfComponent &OC : Components) {
12228     if (OC.isBrackets) {
12229       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12230       if (!CurrentType->isDependentType()) {
12231         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12232         if(!AT)
12233           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12234                            << CurrentType);
12235         CurrentType = AT->getElementType();
12236       } else
12237         CurrentType = Context.DependentTy;
12238       
12239       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12240       if (IdxRval.isInvalid())
12241         return ExprError();
12242       Expr *Idx = IdxRval.get();
12243
12244       // The expression must be an integral expression.
12245       // FIXME: An integral constant expression?
12246       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12247           !Idx->getType()->isIntegerType())
12248         return ExprError(Diag(Idx->getLocStart(),
12249                               diag::err_typecheck_subscript_not_integer)
12250                          << Idx->getSourceRange());
12251
12252       // Record this array index.
12253       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12254       Exprs.push_back(Idx);
12255       continue;
12256     }
12257     
12258     // Offset of a field.
12259     if (CurrentType->isDependentType()) {
12260       // We have the offset of a field, but we can't look into the dependent
12261       // type. Just record the identifier of the field.
12262       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12263       CurrentType = Context.DependentTy;
12264       continue;
12265     }
12266     
12267     // We need to have a complete type to look into.
12268     if (RequireCompleteType(OC.LocStart, CurrentType,
12269                             diag::err_offsetof_incomplete_type))
12270       return ExprError();
12271     
12272     // Look for the designated field.
12273     const RecordType *RC = CurrentType->getAs<RecordType>();
12274     if (!RC) 
12275       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12276                        << CurrentType);
12277     RecordDecl *RD = RC->getDecl();
12278     
12279     // C++ [lib.support.types]p5:
12280     //   The macro offsetof accepts a restricted set of type arguments in this
12281     //   International Standard. type shall be a POD structure or a POD union
12282     //   (clause 9).
12283     // C++11 [support.types]p4:
12284     //   If type is not a standard-layout class (Clause 9), the results are
12285     //   undefined.
12286     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12287       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12288       unsigned DiagID =
12289         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12290                             : diag::ext_offsetof_non_pod_type;
12291
12292       if (!IsSafe && !DidWarnAboutNonPOD &&
12293           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12294                               PDiag(DiagID)
12295                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12296                               << CurrentType))
12297         DidWarnAboutNonPOD = true;
12298     }
12299     
12300     // Look for the field.
12301     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12302     LookupQualifiedName(R, RD);
12303     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12304     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12305     if (!MemberDecl) {
12306       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12307         MemberDecl = IndirectMemberDecl->getAnonField();
12308     }
12309
12310     if (!MemberDecl)
12311       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12312                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
12313                                                               OC.LocEnd));
12314     
12315     // C99 7.17p3:
12316     //   (If the specified member is a bit-field, the behavior is undefined.)
12317     //
12318     // We diagnose this as an error.
12319     if (MemberDecl->isBitField()) {
12320       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12321         << MemberDecl->getDeclName()
12322         << SourceRange(BuiltinLoc, RParenLoc);
12323       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12324       return ExprError();
12325     }
12326
12327     RecordDecl *Parent = MemberDecl->getParent();
12328     if (IndirectMemberDecl)
12329       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12330
12331     // If the member was found in a base class, introduce OffsetOfNodes for
12332     // the base class indirections.
12333     CXXBasePaths Paths;
12334     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12335                       Paths)) {
12336       if (Paths.getDetectedVirtual()) {
12337         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12338           << MemberDecl->getDeclName()
12339           << SourceRange(BuiltinLoc, RParenLoc);
12340         return ExprError();
12341       }
12342
12343       CXXBasePath &Path = Paths.front();
12344       for (const CXXBasePathElement &B : Path)
12345         Comps.push_back(OffsetOfNode(B.Base));
12346     }
12347
12348     if (IndirectMemberDecl) {
12349       for (auto *FI : IndirectMemberDecl->chain()) {
12350         assert(isa<FieldDecl>(FI));
12351         Comps.push_back(OffsetOfNode(OC.LocStart,
12352                                      cast<FieldDecl>(FI), OC.LocEnd));
12353       }
12354     } else
12355       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12356
12357     CurrentType = MemberDecl->getType().getNonReferenceType(); 
12358   }
12359   
12360   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12361                               Comps, Exprs, RParenLoc);
12362 }
12363
12364 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12365                                       SourceLocation BuiltinLoc,
12366                                       SourceLocation TypeLoc,
12367                                       ParsedType ParsedArgTy,
12368                                       ArrayRef<OffsetOfComponent> Components,
12369                                       SourceLocation RParenLoc) {
12370   
12371   TypeSourceInfo *ArgTInfo;
12372   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12373   if (ArgTy.isNull())
12374     return ExprError();
12375
12376   if (!ArgTInfo)
12377     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12378
12379   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12380 }
12381
12382
12383 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12384                                  Expr *CondExpr,
12385                                  Expr *LHSExpr, Expr *RHSExpr,
12386                                  SourceLocation RPLoc) {
12387   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12388
12389   ExprValueKind VK = VK_RValue;
12390   ExprObjectKind OK = OK_Ordinary;
12391   QualType resType;
12392   bool ValueDependent = false;
12393   bool CondIsTrue = false;
12394   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12395     resType = Context.DependentTy;
12396     ValueDependent = true;
12397   } else {
12398     // The conditional expression is required to be a constant expression.
12399     llvm::APSInt condEval(32);
12400     ExprResult CondICE
12401       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12402           diag::err_typecheck_choose_expr_requires_constant, false);
12403     if (CondICE.isInvalid())
12404       return ExprError();
12405     CondExpr = CondICE.get();
12406     CondIsTrue = condEval.getZExtValue();
12407
12408     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12409     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12410
12411     resType = ActiveExpr->getType();
12412     ValueDependent = ActiveExpr->isValueDependent();
12413     VK = ActiveExpr->getValueKind();
12414     OK = ActiveExpr->getObjectKind();
12415   }
12416
12417   return new (Context)
12418       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12419                  CondIsTrue, resType->isDependentType(), ValueDependent);
12420 }
12421
12422 //===----------------------------------------------------------------------===//
12423 // Clang Extensions.
12424 //===----------------------------------------------------------------------===//
12425
12426 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12427 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12428   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12429
12430   if (LangOpts.CPlusPlus) {
12431     Decl *ManglingContextDecl;
12432     if (MangleNumberingContext *MCtx =
12433             getCurrentMangleNumberContext(Block->getDeclContext(),
12434                                           ManglingContextDecl)) {
12435       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12436       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12437     }
12438   }
12439
12440   PushBlockScope(CurScope, Block);
12441   CurContext->addDecl(Block);
12442   if (CurScope)
12443     PushDeclContext(CurScope, Block);
12444   else
12445     CurContext = Block;
12446
12447   getCurBlock()->HasImplicitReturnType = true;
12448
12449   // Enter a new evaluation context to insulate the block from any
12450   // cleanups from the enclosing full-expression.
12451   PushExpressionEvaluationContext(
12452       ExpressionEvaluationContext::PotentiallyEvaluated);
12453 }
12454
12455 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12456                                Scope *CurScope) {
12457   assert(ParamInfo.getIdentifier() == nullptr &&
12458          "block-id should have no identifier!");
12459   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12460   BlockScopeInfo *CurBlock = getCurBlock();
12461
12462   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12463   QualType T = Sig->getType();
12464
12465   // FIXME: We should allow unexpanded parameter packs here, but that would,
12466   // in turn, make the block expression contain unexpanded parameter packs.
12467   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12468     // Drop the parameters.
12469     FunctionProtoType::ExtProtoInfo EPI;
12470     EPI.HasTrailingReturn = false;
12471     EPI.TypeQuals |= DeclSpec::TQ_const;
12472     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12473     Sig = Context.getTrivialTypeSourceInfo(T);
12474   }
12475   
12476   // GetTypeForDeclarator always produces a function type for a block
12477   // literal signature.  Furthermore, it is always a FunctionProtoType
12478   // unless the function was written with a typedef.
12479   assert(T->isFunctionType() &&
12480          "GetTypeForDeclarator made a non-function block signature");
12481
12482   // Look for an explicit signature in that function type.
12483   FunctionProtoTypeLoc ExplicitSignature;
12484
12485   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12486   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12487
12488     // Check whether that explicit signature was synthesized by
12489     // GetTypeForDeclarator.  If so, don't save that as part of the
12490     // written signature.
12491     if (ExplicitSignature.getLocalRangeBegin() ==
12492         ExplicitSignature.getLocalRangeEnd()) {
12493       // This would be much cheaper if we stored TypeLocs instead of
12494       // TypeSourceInfos.
12495       TypeLoc Result = ExplicitSignature.getReturnLoc();
12496       unsigned Size = Result.getFullDataSize();
12497       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12498       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12499
12500       ExplicitSignature = FunctionProtoTypeLoc();
12501     }
12502   }
12503
12504   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12505   CurBlock->FunctionType = T;
12506
12507   const FunctionType *Fn = T->getAs<FunctionType>();
12508   QualType RetTy = Fn->getReturnType();
12509   bool isVariadic =
12510     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12511
12512   CurBlock->TheDecl->setIsVariadic(isVariadic);
12513
12514   // Context.DependentTy is used as a placeholder for a missing block
12515   // return type.  TODO:  what should we do with declarators like:
12516   //   ^ * { ... }
12517   // If the answer is "apply template argument deduction"....
12518   if (RetTy != Context.DependentTy) {
12519     CurBlock->ReturnType = RetTy;
12520     CurBlock->TheDecl->setBlockMissingReturnType(false);
12521     CurBlock->HasImplicitReturnType = false;
12522   }
12523
12524   // Push block parameters from the declarator if we had them.
12525   SmallVector<ParmVarDecl*, 8> Params;
12526   if (ExplicitSignature) {
12527     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12528       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12529       if (Param->getIdentifier() == nullptr &&
12530           !Param->isImplicit() &&
12531           !Param->isInvalidDecl() &&
12532           !getLangOpts().CPlusPlus)
12533         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12534       Params.push_back(Param);
12535     }
12536
12537   // Fake up parameter variables if we have a typedef, like
12538   //   ^ fntype { ... }
12539   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12540     for (const auto &I : Fn->param_types()) {
12541       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12542           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12543       Params.push_back(Param);
12544     }
12545   }
12546
12547   // Set the parameters on the block decl.
12548   if (!Params.empty()) {
12549     CurBlock->TheDecl->setParams(Params);
12550     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12551                              /*CheckParameterNames=*/false);
12552   }
12553   
12554   // Finally we can process decl attributes.
12555   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12556
12557   // Put the parameter variables in scope.
12558   for (auto AI : CurBlock->TheDecl->parameters()) {
12559     AI->setOwningFunction(CurBlock->TheDecl);
12560
12561     // If this has an identifier, add it to the scope stack.
12562     if (AI->getIdentifier()) {
12563       CheckShadow(CurBlock->TheScope, AI);
12564
12565       PushOnScopeChains(AI, CurBlock->TheScope);
12566     }
12567   }
12568 }
12569
12570 /// ActOnBlockError - If there is an error parsing a block, this callback
12571 /// is invoked to pop the information about the block from the action impl.
12572 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12573   // Leave the expression-evaluation context.
12574   DiscardCleanupsInEvaluationContext();
12575   PopExpressionEvaluationContext();
12576
12577   // Pop off CurBlock, handle nested blocks.
12578   PopDeclContext();
12579   PopFunctionScopeInfo();
12580 }
12581
12582 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12583 /// literal was successfully completed.  ^(int x){...}
12584 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12585                                     Stmt *Body, Scope *CurScope) {
12586   // If blocks are disabled, emit an error.
12587   if (!LangOpts.Blocks)
12588     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12589
12590   // Leave the expression-evaluation context.
12591   if (hasAnyUnrecoverableErrorsInThisFunction())
12592     DiscardCleanupsInEvaluationContext();
12593   assert(!Cleanup.exprNeedsCleanups() &&
12594          "cleanups within block not correctly bound!");
12595   PopExpressionEvaluationContext();
12596
12597   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12598
12599   if (BSI->HasImplicitReturnType)
12600     deduceClosureReturnType(*BSI);
12601
12602   PopDeclContext();
12603
12604   QualType RetTy = Context.VoidTy;
12605   if (!BSI->ReturnType.isNull())
12606     RetTy = BSI->ReturnType;
12607
12608   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12609   QualType BlockTy;
12610
12611   // Set the captured variables on the block.
12612   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12613   SmallVector<BlockDecl::Capture, 4> Captures;
12614   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12615     if (Cap.isThisCapture())
12616       continue;
12617     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12618                               Cap.isNested(), Cap.getInitExpr());
12619     Captures.push_back(NewCap);
12620   }
12621   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12622
12623   // If the user wrote a function type in some form, try to use that.
12624   if (!BSI->FunctionType.isNull()) {
12625     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12626
12627     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12628     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12629     
12630     // Turn protoless block types into nullary block types.
12631     if (isa<FunctionNoProtoType>(FTy)) {
12632       FunctionProtoType::ExtProtoInfo EPI;
12633       EPI.ExtInfo = Ext;
12634       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12635
12636     // Otherwise, if we don't need to change anything about the function type,
12637     // preserve its sugar structure.
12638     } else if (FTy->getReturnType() == RetTy &&
12639                (!NoReturn || FTy->getNoReturnAttr())) {
12640       BlockTy = BSI->FunctionType;
12641
12642     // Otherwise, make the minimal modifications to the function type.
12643     } else {
12644       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12645       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12646       EPI.TypeQuals = 0; // FIXME: silently?
12647       EPI.ExtInfo = Ext;
12648       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12649     }
12650
12651   // If we don't have a function type, just build one from nothing.
12652   } else {
12653     FunctionProtoType::ExtProtoInfo EPI;
12654     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12655     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12656   }
12657
12658   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12659   BlockTy = Context.getBlockPointerType(BlockTy);
12660
12661   // If needed, diagnose invalid gotos and switches in the block.
12662   if (getCurFunction()->NeedsScopeChecking() &&
12663       !PP.isCodeCompletionEnabled())
12664     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12665
12666   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12667
12668   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12669     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12670
12671   // Try to apply the named return value optimization. We have to check again
12672   // if we can do this, though, because blocks keep return statements around
12673   // to deduce an implicit return type.
12674   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12675       !BSI->TheDecl->isDependentContext())
12676     computeNRVO(Body, BSI);
12677   
12678   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12679   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12680   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12681
12682   // If the block isn't obviously global, i.e. it captures anything at
12683   // all, then we need to do a few things in the surrounding context:
12684   if (Result->getBlockDecl()->hasCaptures()) {
12685     // First, this expression has a new cleanup object.
12686     ExprCleanupObjects.push_back(Result->getBlockDecl());
12687     Cleanup.setExprNeedsCleanups(true);
12688
12689     // It also gets a branch-protected scope if any of the captured
12690     // variables needs destruction.
12691     for (const auto &CI : Result->getBlockDecl()->captures()) {
12692       const VarDecl *var = CI.getVariable();
12693       if (var->getType().isDestructedType() != QualType::DK_none) {
12694         getCurFunction()->setHasBranchProtectedScope();
12695         break;
12696       }
12697     }
12698   }
12699
12700   return Result;
12701 }
12702
12703 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12704                             SourceLocation RPLoc) {
12705   TypeSourceInfo *TInfo;
12706   GetTypeFromParser(Ty, &TInfo);
12707   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12708 }
12709
12710 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12711                                 Expr *E, TypeSourceInfo *TInfo,
12712                                 SourceLocation RPLoc) {
12713   Expr *OrigExpr = E;
12714   bool IsMS = false;
12715
12716   // CUDA device code does not support varargs.
12717   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12718     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12719       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12720       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12721         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12722     }
12723   }
12724
12725   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12726   // as Microsoft ABI on an actual Microsoft platform, where
12727   // __builtin_ms_va_list and __builtin_va_list are the same.)
12728   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12729       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12730     QualType MSVaListType = Context.getBuiltinMSVaListType();
12731     if (Context.hasSameType(MSVaListType, E->getType())) {
12732       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12733         return ExprError();
12734       IsMS = true;
12735     }
12736   }
12737
12738   // Get the va_list type
12739   QualType VaListType = Context.getBuiltinVaListType();
12740   if (!IsMS) {
12741     if (VaListType->isArrayType()) {
12742       // Deal with implicit array decay; for example, on x86-64,
12743       // va_list is an array, but it's supposed to decay to
12744       // a pointer for va_arg.
12745       VaListType = Context.getArrayDecayedType(VaListType);
12746       // Make sure the input expression also decays appropriately.
12747       ExprResult Result = UsualUnaryConversions(E);
12748       if (Result.isInvalid())
12749         return ExprError();
12750       E = Result.get();
12751     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12752       // If va_list is a record type and we are compiling in C++ mode,
12753       // check the argument using reference binding.
12754       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12755           Context, Context.getLValueReferenceType(VaListType), false);
12756       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12757       if (Init.isInvalid())
12758         return ExprError();
12759       E = Init.getAs<Expr>();
12760     } else {
12761       // Otherwise, the va_list argument must be an l-value because
12762       // it is modified by va_arg.
12763       if (!E->isTypeDependent() &&
12764           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12765         return ExprError();
12766     }
12767   }
12768
12769   if (!IsMS && !E->isTypeDependent() &&
12770       !Context.hasSameType(VaListType, E->getType()))
12771     return ExprError(Diag(E->getLocStart(),
12772                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12773       << OrigExpr->getType() << E->getSourceRange());
12774
12775   if (!TInfo->getType()->isDependentType()) {
12776     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12777                             diag::err_second_parameter_to_va_arg_incomplete,
12778                             TInfo->getTypeLoc()))
12779       return ExprError();
12780
12781     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12782                                TInfo->getType(),
12783                                diag::err_second_parameter_to_va_arg_abstract,
12784                                TInfo->getTypeLoc()))
12785       return ExprError();
12786
12787     if (!TInfo->getType().isPODType(Context)) {
12788       Diag(TInfo->getTypeLoc().getBeginLoc(),
12789            TInfo->getType()->isObjCLifetimeType()
12790              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12791              : diag::warn_second_parameter_to_va_arg_not_pod)
12792         << TInfo->getType()
12793         << TInfo->getTypeLoc().getSourceRange();
12794     }
12795
12796     // Check for va_arg where arguments of the given type will be promoted
12797     // (i.e. this va_arg is guaranteed to have undefined behavior).
12798     QualType PromoteType;
12799     if (TInfo->getType()->isPromotableIntegerType()) {
12800       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12801       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12802         PromoteType = QualType();
12803     }
12804     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12805       PromoteType = Context.DoubleTy;
12806     if (!PromoteType.isNull())
12807       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12808                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12809                           << TInfo->getType()
12810                           << PromoteType
12811                           << TInfo->getTypeLoc().getSourceRange());
12812   }
12813
12814   QualType T = TInfo->getType().getNonLValueExprType(Context);
12815   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12816 }
12817
12818 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12819   // The type of __null will be int or long, depending on the size of
12820   // pointers on the target.
12821   QualType Ty;
12822   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12823   if (pw == Context.getTargetInfo().getIntWidth())
12824     Ty = Context.IntTy;
12825   else if (pw == Context.getTargetInfo().getLongWidth())
12826     Ty = Context.LongTy;
12827   else if (pw == Context.getTargetInfo().getLongLongWidth())
12828     Ty = Context.LongLongTy;
12829   else {
12830     llvm_unreachable("I don't know size of pointer!");
12831   }
12832
12833   return new (Context) GNUNullExpr(Ty, TokenLoc);
12834 }
12835
12836 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12837                                               bool Diagnose) {
12838   if (!getLangOpts().ObjC1)
12839     return false;
12840
12841   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12842   if (!PT)
12843     return false;
12844
12845   if (!PT->isObjCIdType()) {
12846     // Check if the destination is the 'NSString' interface.
12847     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12848     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12849       return false;
12850   }
12851   
12852   // Ignore any parens, implicit casts (should only be
12853   // array-to-pointer decays), and not-so-opaque values.  The last is
12854   // important for making this trigger for property assignments.
12855   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12856   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12857     if (OV->getSourceExpr())
12858       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12859
12860   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12861   if (!SL || !SL->isAscii())
12862     return false;
12863   if (Diagnose) {
12864     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12865       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12866     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12867   }
12868   return true;
12869 }
12870
12871 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12872                                               const Expr *SrcExpr) {
12873   if (!DstType->isFunctionPointerType() ||
12874       !SrcExpr->getType()->isFunctionType())
12875     return false;
12876
12877   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12878   if (!DRE)
12879     return false;
12880
12881   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12882   if (!FD)
12883     return false;
12884
12885   return !S.checkAddressOfFunctionIsAvailable(FD,
12886                                               /*Complain=*/true,
12887                                               SrcExpr->getLocStart());
12888 }
12889
12890 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12891                                     SourceLocation Loc,
12892                                     QualType DstType, QualType SrcType,
12893                                     Expr *SrcExpr, AssignmentAction Action,
12894                                     bool *Complained) {
12895   if (Complained)
12896     *Complained = false;
12897
12898   // Decode the result (notice that AST's are still created for extensions).
12899   bool CheckInferredResultType = false;
12900   bool isInvalid = false;
12901   unsigned DiagKind = 0;
12902   FixItHint Hint;
12903   ConversionFixItGenerator ConvHints;
12904   bool MayHaveConvFixit = false;
12905   bool MayHaveFunctionDiff = false;
12906   const ObjCInterfaceDecl *IFace = nullptr;
12907   const ObjCProtocolDecl *PDecl = nullptr;
12908
12909   switch (ConvTy) {
12910   case Compatible:
12911       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12912       return false;
12913
12914   case PointerToInt:
12915     DiagKind = diag::ext_typecheck_convert_pointer_int;
12916     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12917     MayHaveConvFixit = true;
12918     break;
12919   case IntToPointer:
12920     DiagKind = diag::ext_typecheck_convert_int_pointer;
12921     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12922     MayHaveConvFixit = true;
12923     break;
12924   case IncompatiblePointer:
12925     if (Action == AA_Passing_CFAudited)
12926       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12927     else if (SrcType->isFunctionPointerType() &&
12928              DstType->isFunctionPointerType())
12929       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12930     else
12931       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12932
12933     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12934       SrcType->isObjCObjectPointerType();
12935     if (Hint.isNull() && !CheckInferredResultType) {
12936       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12937     }
12938     else if (CheckInferredResultType) {
12939       SrcType = SrcType.getUnqualifiedType();
12940       DstType = DstType.getUnqualifiedType();
12941     }
12942     MayHaveConvFixit = true;
12943     break;
12944   case IncompatiblePointerSign:
12945     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12946     break;
12947   case FunctionVoidPointer:
12948     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12949     break;
12950   case IncompatiblePointerDiscardsQualifiers: {
12951     // Perform array-to-pointer decay if necessary.
12952     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12953
12954     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12955     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12956     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12957       DiagKind = diag::err_typecheck_incompatible_address_space;
12958       break;
12959
12960
12961     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12962       DiagKind = diag::err_typecheck_incompatible_ownership;
12963       break;
12964     }
12965
12966     llvm_unreachable("unknown error case for discarding qualifiers!");
12967     // fallthrough
12968   }
12969   case CompatiblePointerDiscardsQualifiers:
12970     // If the qualifiers lost were because we were applying the
12971     // (deprecated) C++ conversion from a string literal to a char*
12972     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12973     // Ideally, this check would be performed in
12974     // checkPointerTypesForAssignment. However, that would require a
12975     // bit of refactoring (so that the second argument is an
12976     // expression, rather than a type), which should be done as part
12977     // of a larger effort to fix checkPointerTypesForAssignment for
12978     // C++ semantics.
12979     if (getLangOpts().CPlusPlus &&
12980         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12981       return false;
12982     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12983     break;
12984   case IncompatibleNestedPointerQualifiers:
12985     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12986     break;
12987   case IntToBlockPointer:
12988     DiagKind = diag::err_int_to_block_pointer;
12989     break;
12990   case IncompatibleBlockPointer:
12991     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12992     break;
12993   case IncompatibleObjCQualifiedId: {
12994     if (SrcType->isObjCQualifiedIdType()) {
12995       const ObjCObjectPointerType *srcOPT =
12996                 SrcType->getAs<ObjCObjectPointerType>();
12997       for (auto *srcProto : srcOPT->quals()) {
12998         PDecl = srcProto;
12999         break;
13000       }
13001       if (const ObjCInterfaceType *IFaceT =
13002             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13003         IFace = IFaceT->getDecl();
13004     }
13005     else if (DstType->isObjCQualifiedIdType()) {
13006       const ObjCObjectPointerType *dstOPT =
13007         DstType->getAs<ObjCObjectPointerType>();
13008       for (auto *dstProto : dstOPT->quals()) {
13009         PDecl = dstProto;
13010         break;
13011       }
13012       if (const ObjCInterfaceType *IFaceT =
13013             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13014         IFace = IFaceT->getDecl();
13015     }
13016     DiagKind = diag::warn_incompatible_qualified_id;
13017     break;
13018   }
13019   case IncompatibleVectors:
13020     DiagKind = diag::warn_incompatible_vectors;
13021     break;
13022   case IncompatibleObjCWeakRef:
13023     DiagKind = diag::err_arc_weak_unavailable_assign;
13024     break;
13025   case Incompatible:
13026     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13027       if (Complained)
13028         *Complained = true;
13029       return true;
13030     }
13031
13032     DiagKind = diag::err_typecheck_convert_incompatible;
13033     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13034     MayHaveConvFixit = true;
13035     isInvalid = true;
13036     MayHaveFunctionDiff = true;
13037     break;
13038   }
13039
13040   QualType FirstType, SecondType;
13041   switch (Action) {
13042   case AA_Assigning:
13043   case AA_Initializing:
13044     // The destination type comes first.
13045     FirstType = DstType;
13046     SecondType = SrcType;
13047     break;
13048
13049   case AA_Returning:
13050   case AA_Passing:
13051   case AA_Passing_CFAudited:
13052   case AA_Converting:
13053   case AA_Sending:
13054   case AA_Casting:
13055     // The source type comes first.
13056     FirstType = SrcType;
13057     SecondType = DstType;
13058     break;
13059   }
13060
13061   PartialDiagnostic FDiag = PDiag(DiagKind);
13062   if (Action == AA_Passing_CFAudited)
13063     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13064   else
13065     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13066
13067   // If we can fix the conversion, suggest the FixIts.
13068   assert(ConvHints.isNull() || Hint.isNull());
13069   if (!ConvHints.isNull()) {
13070     for (FixItHint &H : ConvHints.Hints)
13071       FDiag << H;
13072   } else {
13073     FDiag << Hint;
13074   }
13075   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13076
13077   if (MayHaveFunctionDiff)
13078     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13079
13080   Diag(Loc, FDiag);
13081   if (DiagKind == diag::warn_incompatible_qualified_id &&
13082       PDecl && IFace && !IFace->hasDefinition())
13083       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13084         << IFace->getName() << PDecl->getName();
13085     
13086   if (SecondType == Context.OverloadTy)
13087     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13088                               FirstType, /*TakingAddress=*/true);
13089
13090   if (CheckInferredResultType)
13091     EmitRelatedResultTypeNote(SrcExpr);
13092
13093   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13094     EmitRelatedResultTypeNoteForReturn(DstType);
13095   
13096   if (Complained)
13097     *Complained = true;
13098   return isInvalid;
13099 }
13100
13101 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13102                                                  llvm::APSInt *Result) {
13103   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13104   public:
13105     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13106       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13107     }
13108   } Diagnoser;
13109   
13110   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13111 }
13112
13113 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13114                                                  llvm::APSInt *Result,
13115                                                  unsigned DiagID,
13116                                                  bool AllowFold) {
13117   class IDDiagnoser : public VerifyICEDiagnoser {
13118     unsigned DiagID;
13119     
13120   public:
13121     IDDiagnoser(unsigned DiagID)
13122       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13123     
13124     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13125       S.Diag(Loc, DiagID) << SR;
13126     }
13127   } Diagnoser(DiagID);
13128   
13129   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13130 }
13131
13132 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13133                                             SourceRange SR) {
13134   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13135 }
13136
13137 ExprResult
13138 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13139                                       VerifyICEDiagnoser &Diagnoser,
13140                                       bool AllowFold) {
13141   SourceLocation DiagLoc = E->getLocStart();
13142
13143   if (getLangOpts().CPlusPlus11) {
13144     // C++11 [expr.const]p5:
13145     //   If an expression of literal class type is used in a context where an
13146     //   integral constant expression is required, then that class type shall
13147     //   have a single non-explicit conversion function to an integral or
13148     //   unscoped enumeration type
13149     ExprResult Converted;
13150     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13151     public:
13152       CXX11ConvertDiagnoser(bool Silent)
13153           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13154                                 Silent, true) {}
13155
13156       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13157                                            QualType T) override {
13158         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13159       }
13160
13161       SemaDiagnosticBuilder diagnoseIncomplete(
13162           Sema &S, SourceLocation Loc, QualType T) override {
13163         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13164       }
13165
13166       SemaDiagnosticBuilder diagnoseExplicitConv(
13167           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13168         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13169       }
13170
13171       SemaDiagnosticBuilder noteExplicitConv(
13172           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13173         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13174                  << ConvTy->isEnumeralType() << ConvTy;
13175       }
13176
13177       SemaDiagnosticBuilder diagnoseAmbiguous(
13178           Sema &S, SourceLocation Loc, QualType T) override {
13179         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13180       }
13181
13182       SemaDiagnosticBuilder noteAmbiguous(
13183           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13184         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13185                  << ConvTy->isEnumeralType() << ConvTy;
13186       }
13187
13188       SemaDiagnosticBuilder diagnoseConversion(
13189           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13190         llvm_unreachable("conversion functions are permitted");
13191       }
13192     } ConvertDiagnoser(Diagnoser.Suppress);
13193
13194     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13195                                                     ConvertDiagnoser);
13196     if (Converted.isInvalid())
13197       return Converted;
13198     E = Converted.get();
13199     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13200       return ExprError();
13201   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13202     // An ICE must be of integral or unscoped enumeration type.
13203     if (!Diagnoser.Suppress)
13204       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13205     return ExprError();
13206   }
13207
13208   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13209   // in the non-ICE case.
13210   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13211     if (Result)
13212       *Result = E->EvaluateKnownConstInt(Context);
13213     return E;
13214   }
13215
13216   Expr::EvalResult EvalResult;
13217   SmallVector<PartialDiagnosticAt, 8> Notes;
13218   EvalResult.Diag = &Notes;
13219
13220   // Try to evaluate the expression, and produce diagnostics explaining why it's
13221   // not a constant expression as a side-effect.
13222   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13223                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13224
13225   // In C++11, we can rely on diagnostics being produced for any expression
13226   // which is not a constant expression. If no diagnostics were produced, then
13227   // this is a constant expression.
13228   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13229     if (Result)
13230       *Result = EvalResult.Val.getInt();
13231     return E;
13232   }
13233
13234   // If our only note is the usual "invalid subexpression" note, just point
13235   // the caret at its location rather than producing an essentially
13236   // redundant note.
13237   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13238         diag::note_invalid_subexpr_in_const_expr) {
13239     DiagLoc = Notes[0].first;
13240     Notes.clear();
13241   }
13242
13243   if (!Folded || !AllowFold) {
13244     if (!Diagnoser.Suppress) {
13245       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13246       for (const PartialDiagnosticAt &Note : Notes)
13247         Diag(Note.first, Note.second);
13248     }
13249
13250     return ExprError();
13251   }
13252
13253   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13254   for (const PartialDiagnosticAt &Note : Notes)
13255     Diag(Note.first, Note.second);
13256
13257   if (Result)
13258     *Result = EvalResult.Val.getInt();
13259   return E;
13260 }
13261
13262 namespace {
13263   // Handle the case where we conclude a expression which we speculatively
13264   // considered to be unevaluated is actually evaluated.
13265   class TransformToPE : public TreeTransform<TransformToPE> {
13266     typedef TreeTransform<TransformToPE> BaseTransform;
13267
13268   public:
13269     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13270
13271     // Make sure we redo semantic analysis
13272     bool AlwaysRebuild() { return true; }
13273
13274     // Make sure we handle LabelStmts correctly.
13275     // FIXME: This does the right thing, but maybe we need a more general
13276     // fix to TreeTransform?
13277     StmtResult TransformLabelStmt(LabelStmt *S) {
13278       S->getDecl()->setStmt(nullptr);
13279       return BaseTransform::TransformLabelStmt(S);
13280     }
13281
13282     // We need to special-case DeclRefExprs referring to FieldDecls which
13283     // are not part of a member pointer formation; normal TreeTransforming
13284     // doesn't catch this case because of the way we represent them in the AST.
13285     // FIXME: This is a bit ugly; is it really the best way to handle this
13286     // case?
13287     //
13288     // Error on DeclRefExprs referring to FieldDecls.
13289     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13290       if (isa<FieldDecl>(E->getDecl()) &&
13291           !SemaRef.isUnevaluatedContext())
13292         return SemaRef.Diag(E->getLocation(),
13293                             diag::err_invalid_non_static_member_use)
13294             << E->getDecl() << E->getSourceRange();
13295
13296       return BaseTransform::TransformDeclRefExpr(E);
13297     }
13298
13299     // Exception: filter out member pointer formation
13300     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13301       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13302         return E;
13303
13304       return BaseTransform::TransformUnaryOperator(E);
13305     }
13306
13307     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13308       // Lambdas never need to be transformed.
13309       return E;
13310     }
13311   };
13312 }
13313
13314 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13315   assert(isUnevaluatedContext() &&
13316          "Should only transform unevaluated expressions");
13317   ExprEvalContexts.back().Context =
13318       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13319   if (isUnevaluatedContext())
13320     return E;
13321   return TransformToPE(*this).TransformExpr(E);
13322 }
13323
13324 void
13325 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13326                                       Decl *LambdaContextDecl,
13327                                       bool IsDecltype) {
13328   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13329                                 LambdaContextDecl, IsDecltype);
13330   Cleanup.reset();
13331   if (!MaybeODRUseExprs.empty())
13332     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13333 }
13334
13335 void
13336 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13337                                       ReuseLambdaContextDecl_t,
13338                                       bool IsDecltype) {
13339   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13340   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13341 }
13342
13343 void Sema::PopExpressionEvaluationContext() {
13344   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13345   unsigned NumTypos = Rec.NumTypos;
13346
13347   if (!Rec.Lambdas.empty()) {
13348     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13349       unsigned D;
13350       if (Rec.isUnevaluated()) {
13351         // C++11 [expr.prim.lambda]p2:
13352         //   A lambda-expression shall not appear in an unevaluated operand
13353         //   (Clause 5).
13354         D = diag::err_lambda_unevaluated_operand;
13355       } else {
13356         // C++1y [expr.const]p2:
13357         //   A conditional-expression e is a core constant expression unless the
13358         //   evaluation of e, following the rules of the abstract machine, would
13359         //   evaluate [...] a lambda-expression.
13360         D = diag::err_lambda_in_constant_expression;
13361       }
13362
13363       // C++1z allows lambda expressions as core constant expressions.
13364       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13365       // 1607) from appearing within template-arguments and array-bounds that
13366       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13367       // unevaluated contexts) might lift some of these restrictions in a 
13368       // future version.
13369       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13370         for (const auto *L : Rec.Lambdas)
13371           Diag(L->getLocStart(), D);
13372     } else {
13373       // Mark the capture expressions odr-used. This was deferred
13374       // during lambda expression creation.
13375       for (auto *Lambda : Rec.Lambdas) {
13376         for (auto *C : Lambda->capture_inits())
13377           MarkDeclarationsReferencedInExpr(C);
13378       }
13379     }
13380   }
13381
13382   // When are coming out of an unevaluated context, clear out any
13383   // temporaries that we may have created as part of the evaluation of
13384   // the expression in that context: they aren't relevant because they
13385   // will never be constructed.
13386   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13387     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13388                              ExprCleanupObjects.end());
13389     Cleanup = Rec.ParentCleanup;
13390     CleanupVarDeclMarking();
13391     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13392   // Otherwise, merge the contexts together.
13393   } else {
13394     Cleanup.mergeFrom(Rec.ParentCleanup);
13395     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13396                             Rec.SavedMaybeODRUseExprs.end());
13397   }
13398
13399   // Pop the current expression evaluation context off the stack.
13400   ExprEvalContexts.pop_back();
13401
13402   if (!ExprEvalContexts.empty())
13403     ExprEvalContexts.back().NumTypos += NumTypos;
13404   else
13405     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13406                             "last ExpressionEvaluationContextRecord");
13407 }
13408
13409 void Sema::DiscardCleanupsInEvaluationContext() {
13410   ExprCleanupObjects.erase(
13411          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13412          ExprCleanupObjects.end());
13413   Cleanup.reset();
13414   MaybeODRUseExprs.clear();
13415 }
13416
13417 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13418   if (!E->getType()->isVariablyModifiedType())
13419     return E;
13420   return TransformToPotentiallyEvaluated(E);
13421 }
13422
13423 /// Are we within a context in which some evaluation could be performed (be it
13424 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13425 /// captured by C++'s idea of an "unevaluated context".
13426 static bool isEvaluatableContext(Sema &SemaRef) {
13427   switch (SemaRef.ExprEvalContexts.back().Context) {
13428     case Sema::ExpressionEvaluationContext::Unevaluated:
13429     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13430     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13431       // Expressions in this context are never evaluated.
13432       return false;
13433
13434     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13435     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13436     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13437       // Expressions in this context could be evaluated.
13438       return true;
13439
13440     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13441       // Referenced declarations will only be used if the construct in the
13442       // containing expression is used, at which point we'll be given another
13443       // turn to mark them.
13444       return false;
13445   }
13446   llvm_unreachable("Invalid context");
13447 }
13448
13449 /// Are we within a context in which references to resolved functions or to
13450 /// variables result in odr-use?
13451 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13452   // An expression in a template is not really an expression until it's been
13453   // instantiated, so it doesn't trigger odr-use.
13454   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13455     return false;
13456
13457   switch (SemaRef.ExprEvalContexts.back().Context) {
13458     case Sema::ExpressionEvaluationContext::Unevaluated:
13459     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13460     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13461     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13462       return false;
13463
13464     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13465     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13466       return true;
13467
13468     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13469       return false;
13470   }
13471   llvm_unreachable("Invalid context");
13472 }
13473
13474 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13475   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13476   return Func->isConstexpr() &&
13477          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13478 }
13479
13480 /// \brief Mark a function referenced, and check whether it is odr-used
13481 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13482 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13483                                   bool MightBeOdrUse) {
13484   assert(Func && "No function?");
13485
13486   Func->setReferenced();
13487
13488   // C++11 [basic.def.odr]p3:
13489   //   A function whose name appears as a potentially-evaluated expression is
13490   //   odr-used if it is the unique lookup result or the selected member of a
13491   //   set of overloaded functions [...].
13492   //
13493   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13494   // can just check that here.
13495   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13496
13497   // Determine whether we require a function definition to exist, per
13498   // C++11 [temp.inst]p3:
13499   //   Unless a function template specialization has been explicitly
13500   //   instantiated or explicitly specialized, the function template
13501   //   specialization is implicitly instantiated when the specialization is
13502   //   referenced in a context that requires a function definition to exist.
13503   //
13504   // That is either when this is an odr-use, or when a usage of a constexpr
13505   // function occurs within an evaluatable context.
13506   bool NeedDefinition =
13507       OdrUse || (isEvaluatableContext(*this) &&
13508                  isImplicitlyDefinableConstexprFunction(Func));
13509
13510   // C++14 [temp.expl.spec]p6:
13511   //   If a template [...] is explicitly specialized then that specialization
13512   //   shall be declared before the first use of that specialization that would
13513   //   cause an implicit instantiation to take place, in every translation unit
13514   //   in which such a use occurs
13515   if (NeedDefinition &&
13516       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13517        Func->getMemberSpecializationInfo()))
13518     checkSpecializationVisibility(Loc, Func);
13519
13520   // C++14 [except.spec]p17:
13521   //   An exception-specification is considered to be needed when:
13522   //   - the function is odr-used or, if it appears in an unevaluated operand,
13523   //     would be odr-used if the expression were potentially-evaluated;
13524   //
13525   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13526   // function is a pure virtual function we're calling, and in that case the
13527   // function was selected by overload resolution and we need to resolve its
13528   // exception specification for a different reason.
13529   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13530   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13531     ResolveExceptionSpec(Loc, FPT);
13532
13533   // If we don't need to mark the function as used, and we don't need to
13534   // try to provide a definition, there's nothing more to do.
13535   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13536       (!NeedDefinition || Func->getBody()))
13537     return;
13538
13539   // Note that this declaration has been used.
13540   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13541     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13542     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13543       if (Constructor->isDefaultConstructor()) {
13544         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13545           return;
13546         DefineImplicitDefaultConstructor(Loc, Constructor);
13547       } else if (Constructor->isCopyConstructor()) {
13548         DefineImplicitCopyConstructor(Loc, Constructor);
13549       } else if (Constructor->isMoveConstructor()) {
13550         DefineImplicitMoveConstructor(Loc, Constructor);
13551       }
13552     } else if (Constructor->getInheritedConstructor()) {
13553       DefineInheritingConstructor(Loc, Constructor);
13554     }
13555   } else if (CXXDestructorDecl *Destructor =
13556                  dyn_cast<CXXDestructorDecl>(Func)) {
13557     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13558     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13559       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13560         return;
13561       DefineImplicitDestructor(Loc, Destructor);
13562     }
13563     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13564       MarkVTableUsed(Loc, Destructor->getParent());
13565   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13566     if (MethodDecl->isOverloadedOperator() &&
13567         MethodDecl->getOverloadedOperator() == OO_Equal) {
13568       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13569       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13570         if (MethodDecl->isCopyAssignmentOperator())
13571           DefineImplicitCopyAssignment(Loc, MethodDecl);
13572         else if (MethodDecl->isMoveAssignmentOperator())
13573           DefineImplicitMoveAssignment(Loc, MethodDecl);
13574       }
13575     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13576                MethodDecl->getParent()->isLambda()) {
13577       CXXConversionDecl *Conversion =
13578           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13579       if (Conversion->isLambdaToBlockPointerConversion())
13580         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13581       else
13582         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13583     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13584       MarkVTableUsed(Loc, MethodDecl->getParent());
13585   }
13586
13587   // Recursive functions should be marked when used from another function.
13588   // FIXME: Is this really right?
13589   if (CurContext == Func) return;
13590
13591   // Implicit instantiation of function templates and member functions of
13592   // class templates.
13593   if (Func->isImplicitlyInstantiable()) {
13594     bool AlreadyInstantiated = false;
13595     SourceLocation PointOfInstantiation = Loc;
13596     if (FunctionTemplateSpecializationInfo *SpecInfo
13597                               = Func->getTemplateSpecializationInfo()) {
13598       if (SpecInfo->getPointOfInstantiation().isInvalid())
13599         SpecInfo->setPointOfInstantiation(Loc);
13600       else if (SpecInfo->getTemplateSpecializationKind()
13601                  == TSK_ImplicitInstantiation) {
13602         AlreadyInstantiated = true;
13603         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13604       }
13605     } else if (MemberSpecializationInfo *MSInfo
13606                                 = Func->getMemberSpecializationInfo()) {
13607       if (MSInfo->getPointOfInstantiation().isInvalid())
13608         MSInfo->setPointOfInstantiation(Loc);
13609       else if (MSInfo->getTemplateSpecializationKind()
13610                  == TSK_ImplicitInstantiation) {
13611         AlreadyInstantiated = true;
13612         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13613       }
13614     }
13615
13616     if (!AlreadyInstantiated || Func->isConstexpr()) {
13617       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13618           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13619           CodeSynthesisContexts.size())
13620         PendingLocalImplicitInstantiations.push_back(
13621             std::make_pair(Func, PointOfInstantiation));
13622       else if (Func->isConstexpr())
13623         // Do not defer instantiations of constexpr functions, to avoid the
13624         // expression evaluator needing to call back into Sema if it sees a
13625         // call to such a function.
13626         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13627       else {
13628         Func->setInstantiationIsPending(true);
13629         PendingInstantiations.push_back(std::make_pair(Func,
13630                                                        PointOfInstantiation));
13631         // Notify the consumer that a function was implicitly instantiated.
13632         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13633       }
13634     }
13635   } else {
13636     // Walk redefinitions, as some of them may be instantiable.
13637     for (auto i : Func->redecls()) {
13638       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13639         MarkFunctionReferenced(Loc, i, OdrUse);
13640     }
13641   }
13642
13643   if (!OdrUse) return;
13644
13645   // Keep track of used but undefined functions.
13646   if (!Func->isDefined()) {
13647     if (mightHaveNonExternalLinkage(Func))
13648       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13649     else if (Func->getMostRecentDecl()->isInlined() &&
13650              !LangOpts.GNUInline &&
13651              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13652       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13653   }
13654
13655   Func->markUsed(Context);
13656 }
13657
13658 static void
13659 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13660                                    ValueDecl *var, DeclContext *DC) {
13661   DeclContext *VarDC = var->getDeclContext();
13662
13663   //  If the parameter still belongs to the translation unit, then
13664   //  we're actually just using one parameter in the declaration of
13665   //  the next.
13666   if (isa<ParmVarDecl>(var) &&
13667       isa<TranslationUnitDecl>(VarDC))
13668     return;
13669
13670   // For C code, don't diagnose about capture if we're not actually in code
13671   // right now; it's impossible to write a non-constant expression outside of
13672   // function context, so we'll get other (more useful) diagnostics later.
13673   //
13674   // For C++, things get a bit more nasty... it would be nice to suppress this
13675   // diagnostic for certain cases like using a local variable in an array bound
13676   // for a member of a local class, but the correct predicate is not obvious.
13677   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13678     return;
13679
13680   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13681   unsigned ContextKind = 3; // unknown
13682   if (isa<CXXMethodDecl>(VarDC) &&
13683       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13684     ContextKind = 2;
13685   } else if (isa<FunctionDecl>(VarDC)) {
13686     ContextKind = 0;
13687   } else if (isa<BlockDecl>(VarDC)) {
13688     ContextKind = 1;
13689   }
13690
13691   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13692     << var << ValueKind << ContextKind << VarDC;
13693   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13694       << var;
13695
13696   // FIXME: Add additional diagnostic info about class etc. which prevents
13697   // capture.
13698 }
13699
13700  
13701 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
13702                                       bool &SubCapturesAreNested,
13703                                       QualType &CaptureType, 
13704                                       QualType &DeclRefType) {
13705    // Check whether we've already captured it.
13706   if (CSI->CaptureMap.count(Var)) {
13707     // If we found a capture, any subcaptures are nested.
13708     SubCapturesAreNested = true;
13709       
13710     // Retrieve the capture type for this variable.
13711     CaptureType = CSI->getCapture(Var).getCaptureType();
13712       
13713     // Compute the type of an expression that refers to this variable.
13714     DeclRefType = CaptureType.getNonReferenceType();
13715
13716     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13717     // are mutable in the sense that user can change their value - they are
13718     // private instances of the captured declarations.
13719     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13720     if (Cap.isCopyCapture() &&
13721         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13722         !(isa<CapturedRegionScopeInfo>(CSI) &&
13723           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13724       DeclRefType.addConst();
13725     return true;
13726   }
13727   return false;
13728 }
13729
13730 // Only block literals, captured statements, and lambda expressions can
13731 // capture; other scopes don't work.
13732 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
13733                                  SourceLocation Loc, 
13734                                  const bool Diagnose, Sema &S) {
13735   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13736     return getLambdaAwareParentOfDeclContext(DC);
13737   else if (Var->hasLocalStorage()) {
13738     if (Diagnose)
13739        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13740   }
13741   return nullptr;
13742 }
13743
13744 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13745 // certain types of variables (unnamed, variably modified types etc.)
13746 // so check for eligibility.
13747 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
13748                                  SourceLocation Loc, 
13749                                  const bool Diagnose, Sema &S) {
13750
13751   bool IsBlock = isa<BlockScopeInfo>(CSI);
13752   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13753
13754   // Lambdas are not allowed to capture unnamed variables
13755   // (e.g. anonymous unions).
13756   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13757   // assuming that's the intent.
13758   if (IsLambda && !Var->getDeclName()) {
13759     if (Diagnose) {
13760       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13761       S.Diag(Var->getLocation(), diag::note_declared_at);
13762     }
13763     return false;
13764   }
13765
13766   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13767   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13768     if (Diagnose) {
13769       S.Diag(Loc, diag::err_ref_vm_type);
13770       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13771         << Var->getDeclName();
13772     }
13773     return false;
13774   }
13775   // Prohibit structs with flexible array members too.
13776   // We cannot capture what is in the tail end of the struct.
13777   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13778     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13779       if (Diagnose) {
13780         if (IsBlock)
13781           S.Diag(Loc, diag::err_ref_flexarray_type);
13782         else
13783           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13784             << Var->getDeclName();
13785         S.Diag(Var->getLocation(), diag::note_previous_decl)
13786           << Var->getDeclName();
13787       }
13788       return false;
13789     }
13790   }
13791   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13792   // Lambdas and captured statements are not allowed to capture __block
13793   // variables; they don't support the expected semantics.
13794   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13795     if (Diagnose) {
13796       S.Diag(Loc, diag::err_capture_block_variable)
13797         << Var->getDeclName() << !IsLambda;
13798       S.Diag(Var->getLocation(), diag::note_previous_decl)
13799         << Var->getDeclName();
13800     }
13801     return false;
13802   }
13803   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13804   if (S.getLangOpts().OpenCL && IsBlock &&
13805       Var->getType()->isBlockPointerType()) {
13806     if (Diagnose)
13807       S.Diag(Loc, diag::err_opencl_block_ref_block);
13808     return false;
13809   }
13810
13811   return true;
13812 }
13813
13814 // Returns true if the capture by block was successful.
13815 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
13816                                  SourceLocation Loc, 
13817                                  const bool BuildAndDiagnose, 
13818                                  QualType &CaptureType,
13819                                  QualType &DeclRefType, 
13820                                  const bool Nested,
13821                                  Sema &S) {
13822   Expr *CopyExpr = nullptr;
13823   bool ByRef = false;
13824       
13825   // Blocks are not allowed to capture arrays.
13826   if (CaptureType->isArrayType()) {
13827     if (BuildAndDiagnose) {
13828       S.Diag(Loc, diag::err_ref_array_type);
13829       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13830       << Var->getDeclName();
13831     }
13832     return false;
13833   }
13834
13835   // Forbid the block-capture of autoreleasing variables.
13836   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13837     if (BuildAndDiagnose) {
13838       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13839         << /*block*/ 0;
13840       S.Diag(Var->getLocation(), diag::note_previous_decl)
13841         << Var->getDeclName();
13842     }
13843     return false;
13844   }
13845
13846   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13847   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13848     // This function finds out whether there is an AttributedType of kind
13849     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13850     // attr_objc_ownership implies __autoreleasing was explicitly specified
13851     // rather than being added implicitly by the compiler.
13852     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13853       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13854         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13855           return true;
13856
13857         // Peel off AttributedTypes that are not of kind objc_ownership.
13858         Ty = AttrTy->getModifiedType();
13859       }
13860
13861       return false;
13862     };
13863
13864     QualType PointeeTy = PT->getPointeeType();
13865
13866     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13867         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13868         !IsObjCOwnershipAttributedType(PointeeTy)) {
13869       if (BuildAndDiagnose) {
13870         SourceLocation VarLoc = Var->getLocation();
13871         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13872         {
13873           auto AddAutoreleaseNote =
13874               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13875           // Provide a fix-it for the '__autoreleasing' keyword at the
13876           // appropriate location in the variable's type.
13877           if (const auto *TSI = Var->getTypeSourceInfo()) {
13878             PointerTypeLoc PTL =
13879                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13880             if (PTL) {
13881               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13882               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13883                                                S.getLangOpts());
13884               if (Loc.isValid()) {
13885                 StringRef CharAtLoc = Lexer::getSourceText(
13886                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13887                     S.getSourceManager(), S.getLangOpts());
13888                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13889                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13890                              ? " __autoreleasing "
13891                              : " __autoreleasing");
13892               }
13893             }
13894           }
13895         }
13896         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13897       }
13898     }
13899   }
13900
13901   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13902   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13903       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13904     // Block capture by reference does not change the capture or
13905     // declaration reference types.
13906     ByRef = true;
13907   } else {
13908     // Block capture by copy introduces 'const'.
13909     CaptureType = CaptureType.getNonReferenceType().withConst();
13910     DeclRefType = CaptureType;
13911                 
13912     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13913       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13914         // The capture logic needs the destructor, so make sure we mark it.
13915         // Usually this is unnecessary because most local variables have
13916         // their destructors marked at declaration time, but parameters are
13917         // an exception because it's technically only the call site that
13918         // actually requires the destructor.
13919         if (isa<ParmVarDecl>(Var))
13920           S.FinalizeVarWithDestructor(Var, Record);
13921
13922         // Enter a new evaluation context to insulate the copy
13923         // full-expression.
13924         EnterExpressionEvaluationContext scope(
13925             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13926
13927         // According to the blocks spec, the capture of a variable from
13928         // the stack requires a const copy constructor.  This is not true
13929         // of the copy/move done to move a __block variable to the heap.
13930         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13931                                                   DeclRefType.withConst(), 
13932                                                   VK_LValue, Loc);
13933             
13934         ExprResult Result
13935           = S.PerformCopyInitialization(
13936               InitializedEntity::InitializeBlock(Var->getLocation(),
13937                                                   CaptureType, false),
13938               Loc, DeclRef);
13939             
13940         // Build a full-expression copy expression if initialization
13941         // succeeded and used a non-trivial constructor.  Recover from
13942         // errors by pretending that the copy isn't necessary.
13943         if (!Result.isInvalid() &&
13944             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13945                 ->isTrivial()) {
13946           Result = S.MaybeCreateExprWithCleanups(Result);
13947           CopyExpr = Result.get();
13948         }
13949       }
13950     }
13951   }
13952
13953   // Actually capture the variable.
13954   if (BuildAndDiagnose)
13955     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
13956                     SourceLocation(), CaptureType, CopyExpr);
13957
13958   return true;
13959
13960 }
13961
13962
13963 /// \brief Capture the given variable in the captured region.
13964 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13965                                     VarDecl *Var, 
13966                                     SourceLocation Loc, 
13967                                     const bool BuildAndDiagnose, 
13968                                     QualType &CaptureType,
13969                                     QualType &DeclRefType, 
13970                                     const bool RefersToCapturedVariable,
13971                                     Sema &S) {
13972   // By default, capture variables by reference.
13973   bool ByRef = true;
13974   // Using an LValue reference type is consistent with Lambdas (see below).
13975   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13976     if (S.IsOpenMPCapturedDecl(Var))
13977       DeclRefType = DeclRefType.getUnqualifiedType();
13978     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13979   }
13980
13981   if (ByRef)
13982     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13983   else
13984     CaptureType = DeclRefType;
13985
13986   Expr *CopyExpr = nullptr;
13987   if (BuildAndDiagnose) {
13988     // The current implementation assumes that all variables are captured
13989     // by references. Since there is no capture by copy, no expression
13990     // evaluation will be needed.
13991     RecordDecl *RD = RSI->TheRecordDecl;
13992
13993     FieldDecl *Field
13994       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13995                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13996                           nullptr, false, ICIS_NoInit);
13997     Field->setImplicit(true);
13998     Field->setAccess(AS_private);
13999     RD->addDecl(Field);
14000  
14001     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14002                                             DeclRefType, VK_LValue, Loc);
14003     Var->setReferenced(true);
14004     Var->markUsed(S.Context);
14005   }
14006
14007   // Actually capture the variable.
14008   if (BuildAndDiagnose)
14009     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14010                     SourceLocation(), CaptureType, CopyExpr);
14011   
14012   
14013   return true;
14014 }
14015
14016 /// \brief Create a field within the lambda class for the variable
14017 /// being captured.
14018 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 
14019                                     QualType FieldType, QualType DeclRefType,
14020                                     SourceLocation Loc,
14021                                     bool RefersToCapturedVariable) {
14022   CXXRecordDecl *Lambda = LSI->Lambda;
14023
14024   // Build the non-static data member.
14025   FieldDecl *Field
14026     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14027                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14028                         nullptr, false, ICIS_NoInit);
14029   Field->setImplicit(true);
14030   Field->setAccess(AS_private);
14031   Lambda->addDecl(Field);
14032 }
14033
14034 /// \brief Capture the given variable in the lambda.
14035 static bool captureInLambda(LambdaScopeInfo *LSI,
14036                             VarDecl *Var, 
14037                             SourceLocation Loc, 
14038                             const bool BuildAndDiagnose, 
14039                             QualType &CaptureType,
14040                             QualType &DeclRefType, 
14041                             const bool RefersToCapturedVariable,
14042                             const Sema::TryCaptureKind Kind, 
14043                             SourceLocation EllipsisLoc,
14044                             const bool IsTopScope,
14045                             Sema &S) {
14046
14047   // Determine whether we are capturing by reference or by value.
14048   bool ByRef = false;
14049   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14050     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14051   } else {
14052     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14053   }
14054     
14055   // Compute the type of the field that will capture this variable.
14056   if (ByRef) {
14057     // C++11 [expr.prim.lambda]p15:
14058     //   An entity is captured by reference if it is implicitly or
14059     //   explicitly captured but not captured by copy. It is
14060     //   unspecified whether additional unnamed non-static data
14061     //   members are declared in the closure type for entities
14062     //   captured by reference.
14063     //
14064     // FIXME: It is not clear whether we want to build an lvalue reference
14065     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14066     // to do the former, while EDG does the latter. Core issue 1249 will 
14067     // clarify, but for now we follow GCC because it's a more permissive and
14068     // easily defensible position.
14069     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14070   } else {
14071     // C++11 [expr.prim.lambda]p14:
14072     //   For each entity captured by copy, an unnamed non-static
14073     //   data member is declared in the closure type. The
14074     //   declaration order of these members is unspecified. The type
14075     //   of such a data member is the type of the corresponding
14076     //   captured entity if the entity is not a reference to an
14077     //   object, or the referenced type otherwise. [Note: If the
14078     //   captured entity is a reference to a function, the
14079     //   corresponding data member is also a reference to a
14080     //   function. - end note ]
14081     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14082       if (!RefType->getPointeeType()->isFunctionType())
14083         CaptureType = RefType->getPointeeType();
14084     }
14085
14086     // Forbid the lambda copy-capture of autoreleasing variables.
14087     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14088       if (BuildAndDiagnose) {
14089         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14090         S.Diag(Var->getLocation(), diag::note_previous_decl)
14091           << Var->getDeclName();
14092       }
14093       return false;
14094     }
14095
14096     // Make sure that by-copy captures are of a complete and non-abstract type.
14097     if (BuildAndDiagnose) {
14098       if (!CaptureType->isDependentType() &&
14099           S.RequireCompleteType(Loc, CaptureType,
14100                                 diag::err_capture_of_incomplete_type,
14101                                 Var->getDeclName()))
14102         return false;
14103
14104       if (S.RequireNonAbstractType(Loc, CaptureType,
14105                                    diag::err_capture_of_abstract_type))
14106         return false;
14107     }
14108   }
14109
14110   // Capture this variable in the lambda.
14111   if (BuildAndDiagnose)
14112     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14113                             RefersToCapturedVariable);
14114     
14115   // Compute the type of a reference to this captured variable.
14116   if (ByRef)
14117     DeclRefType = CaptureType.getNonReferenceType();
14118   else {
14119     // C++ [expr.prim.lambda]p5:
14120     //   The closure type for a lambda-expression has a public inline 
14121     //   function call operator [...]. This function call operator is 
14122     //   declared const (9.3.1) if and only if the lambda-expression's 
14123     //   parameter-declaration-clause is not followed by mutable.
14124     DeclRefType = CaptureType.getNonReferenceType();
14125     if (!LSI->Mutable && !CaptureType->isReferenceType())
14126       DeclRefType.addConst();      
14127   }
14128     
14129   // Add the capture.
14130   if (BuildAndDiagnose)
14131     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
14132                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14133       
14134   return true;
14135 }
14136
14137 bool Sema::tryCaptureVariable(
14138     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14139     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14140     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14141   // An init-capture is notionally from the context surrounding its
14142   // declaration, but its parent DC is the lambda class.
14143   DeclContext *VarDC = Var->getDeclContext();
14144   if (Var->isInitCapture())
14145     VarDC = VarDC->getParent();
14146   
14147   DeclContext *DC = CurContext;
14148   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
14149       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
14150   // We need to sync up the Declaration Context with the
14151   // FunctionScopeIndexToStopAt
14152   if (FunctionScopeIndexToStopAt) {
14153     unsigned FSIndex = FunctionScopes.size() - 1;
14154     while (FSIndex != MaxFunctionScopesIndex) {
14155       DC = getLambdaAwareParentOfDeclContext(DC);
14156       --FSIndex;
14157     }
14158   }
14159
14160   
14161   // If the variable is declared in the current context, there is no need to
14162   // capture it.
14163   if (VarDC == DC) return true;
14164
14165   // Capture global variables if it is required to use private copy of this
14166   // variable.
14167   bool IsGlobal = !Var->hasLocalStorage();
14168   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14169     return true;
14170
14171   // Walk up the stack to determine whether we can capture the variable,
14172   // performing the "simple" checks that don't depend on type. We stop when
14173   // we've either hit the declared scope of the variable or find an existing
14174   // capture of that variable.  We start from the innermost capturing-entity
14175   // (the DC) and ensure that all intervening capturing-entities 
14176   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14177   // declcontext can either capture the variable or have already captured
14178   // the variable.
14179   CaptureType = Var->getType();
14180   DeclRefType = CaptureType.getNonReferenceType();
14181   bool Nested = false;
14182   bool Explicit = (Kind != TryCapture_Implicit);
14183   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14184   do {
14185     // Only block literals, captured statements, and lambda expressions can
14186     // capture; other scopes don't work.
14187     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
14188                                                               ExprLoc, 
14189                                                               BuildAndDiagnose,
14190                                                               *this);
14191     // We need to check for the parent *first* because, if we *have*
14192     // private-captured a global variable, we need to recursively capture it in
14193     // intermediate blocks, lambdas, etc.
14194     if (!ParentDC) {
14195       if (IsGlobal) {
14196         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14197         break;
14198       }
14199       return true;
14200     }
14201
14202     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14203     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14204
14205
14206     // Check whether we've already captured it.
14207     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
14208                                              DeclRefType)) {
14209       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14210       break;
14211     }
14212     // If we are instantiating a generic lambda call operator body, 
14213     // we do not want to capture new variables.  What was captured
14214     // during either a lambdas transformation or initial parsing
14215     // should be used. 
14216     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14217       if (BuildAndDiagnose) {
14218         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
14219         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14220           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14221           Diag(Var->getLocation(), diag::note_previous_decl) 
14222              << Var->getDeclName();
14223           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
14224         } else
14225           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14226       }
14227       return true;
14228     }
14229     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
14230     // certain types of variables (unnamed, variably modified types etc.)
14231     // so check for eligibility.
14232     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14233        return true;
14234
14235     // Try to capture variable-length arrays types.
14236     if (Var->getType()->isVariablyModifiedType()) {
14237       // We're going to walk down into the type and look for VLA
14238       // expressions.
14239       QualType QTy = Var->getType();
14240       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14241         QTy = PVD->getOriginalType();
14242       captureVariablyModifiedType(Context, QTy, CSI);
14243     }
14244
14245     if (getLangOpts().OpenMP) {
14246       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14247         // OpenMP private variables should not be captured in outer scope, so
14248         // just break here. Similarly, global variables that are captured in a
14249         // target region should not be captured outside the scope of the region.
14250         if (RSI->CapRegionKind == CR_OpenMP) {
14251           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14252           // When we detect target captures we are looking from inside the
14253           // target region, therefore we need to propagate the capture from the
14254           // enclosing region. Therefore, the capture is not initially nested.
14255           if (IsTargetCap)
14256             FunctionScopesIndex--;
14257
14258           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14259             Nested = !IsTargetCap;
14260             DeclRefType = DeclRefType.getUnqualifiedType();
14261             CaptureType = Context.getLValueReferenceType(DeclRefType);
14262             break;
14263           }
14264         }
14265       }
14266     }
14267     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14268       // No capture-default, and this is not an explicit capture 
14269       // so cannot capture this variable.  
14270       if (BuildAndDiagnose) {
14271         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14272         Diag(Var->getLocation(), diag::note_previous_decl) 
14273           << Var->getDeclName();
14274         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14275           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14276                diag::note_lambda_decl);
14277         // FIXME: If we error out because an outer lambda can not implicitly
14278         // capture a variable that an inner lambda explicitly captures, we
14279         // should have the inner lambda do the explicit capture - because
14280         // it makes for cleaner diagnostics later.  This would purely be done
14281         // so that the diagnostic does not misleadingly claim that a variable 
14282         // can not be captured by a lambda implicitly even though it is captured 
14283         // explicitly.  Suggestion:
14284         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
14285         //    at the function head
14286         //  - cache the StartingDeclContext - this must be a lambda 
14287         //  - captureInLambda in the innermost lambda the variable.
14288       }
14289       return true;
14290     }
14291
14292     FunctionScopesIndex--;
14293     DC = ParentDC;
14294     Explicit = false;
14295   } while (!VarDC->Equals(DC));
14296
14297   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14298   // computing the type of the capture at each step, checking type-specific 
14299   // requirements, and adding captures if requested. 
14300   // If the variable had already been captured previously, we start capturing 
14301   // at the lambda nested within that one.   
14302   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
14303        ++I) {
14304     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14305     
14306     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14307       if (!captureInBlock(BSI, Var, ExprLoc, 
14308                           BuildAndDiagnose, CaptureType, 
14309                           DeclRefType, Nested, *this))
14310         return true;
14311       Nested = true;
14312     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14313       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
14314                                    BuildAndDiagnose, CaptureType, 
14315                                    DeclRefType, Nested, *this))
14316         return true;
14317       Nested = true;
14318     } else {
14319       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14320       if (!captureInLambda(LSI, Var, ExprLoc, 
14321                            BuildAndDiagnose, CaptureType, 
14322                            DeclRefType, Nested, Kind, EllipsisLoc, 
14323                             /*IsTopScope*/I == N - 1, *this))
14324         return true;
14325       Nested = true;
14326     }
14327   }
14328   return false;
14329 }
14330
14331 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14332                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
14333   QualType CaptureType;
14334   QualType DeclRefType;
14335   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14336                             /*BuildAndDiagnose=*/true, CaptureType,
14337                             DeclRefType, nullptr);
14338 }
14339
14340 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14341   QualType CaptureType;
14342   QualType DeclRefType;
14343   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14344                              /*BuildAndDiagnose=*/false, CaptureType,
14345                              DeclRefType, nullptr);
14346 }
14347
14348 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14349   QualType CaptureType;
14350   QualType DeclRefType;
14351   
14352   // Determine whether we can capture this variable.
14353   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14354                          /*BuildAndDiagnose=*/false, CaptureType, 
14355                          DeclRefType, nullptr))
14356     return QualType();
14357
14358   return DeclRefType;
14359 }
14360
14361
14362
14363 // If either the type of the variable or the initializer is dependent, 
14364 // return false. Otherwise, determine whether the variable is a constant
14365 // expression. Use this if you need to know if a variable that might or
14366 // might not be dependent is truly a constant expression.
14367 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
14368     ASTContext &Context) {
14369  
14370   if (Var->getType()->isDependentType()) 
14371     return false;
14372   const VarDecl *DefVD = nullptr;
14373   Var->getAnyInitializer(DefVD);
14374   if (!DefVD) 
14375     return false;
14376   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14377   Expr *Init = cast<Expr>(Eval->Value);
14378   if (Init->isValueDependent()) 
14379     return false;
14380   return IsVariableAConstantExpression(Var, Context); 
14381 }
14382
14383
14384 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14385   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
14386   // an object that satisfies the requirements for appearing in a
14387   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14388   // is immediately applied."  This function handles the lvalue-to-rvalue
14389   // conversion part.
14390   MaybeODRUseExprs.erase(E->IgnoreParens());
14391   
14392   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14393   // to a variable that is a constant expression, and if so, identify it as
14394   // a reference to a variable that does not involve an odr-use of that 
14395   // variable. 
14396   if (LambdaScopeInfo *LSI = getCurLambda()) {
14397     Expr *SansParensExpr = E->IgnoreParens();
14398     VarDecl *Var = nullptr;
14399     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
14400       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14401     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14402       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14403     
14404     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
14405       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
14406   }
14407 }
14408
14409 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14410   Res = CorrectDelayedTyposInExpr(Res);
14411
14412   if (!Res.isUsable())
14413     return Res;
14414
14415   // If a constant-expression is a reference to a variable where we delay
14416   // deciding whether it is an odr-use, just assume we will apply the
14417   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14418   // (a non-type template argument), we have special handling anyway.
14419   UpdateMarkingForLValueToRValue(Res.get());
14420   return Res;
14421 }
14422
14423 void Sema::CleanupVarDeclMarking() {
14424   for (Expr *E : MaybeODRUseExprs) {
14425     VarDecl *Var;
14426     SourceLocation Loc;
14427     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14428       Var = cast<VarDecl>(DRE->getDecl());
14429       Loc = DRE->getLocation();
14430     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14431       Var = cast<VarDecl>(ME->getMemberDecl());
14432       Loc = ME->getMemberLoc();
14433     } else {
14434       llvm_unreachable("Unexpected expression");
14435     }
14436
14437     MarkVarDeclODRUsed(Var, Loc, *this,
14438                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14439   }
14440
14441   MaybeODRUseExprs.clear();
14442 }
14443
14444
14445 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14446                                     VarDecl *Var, Expr *E) {
14447   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14448          "Invalid Expr argument to DoMarkVarDeclReferenced");
14449   Var->setReferenced();
14450
14451   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14452
14453   bool OdrUseContext = isOdrUseContext(SemaRef);
14454   bool NeedDefinition =
14455       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14456                         Var->isUsableInConstantExpressions(SemaRef.Context));
14457
14458   VarTemplateSpecializationDecl *VarSpec =
14459       dyn_cast<VarTemplateSpecializationDecl>(Var);
14460   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14461          "Can't instantiate a partial template specialization.");
14462
14463   // If this might be a member specialization of a static data member, check
14464   // the specialization is visible. We already did the checks for variable
14465   // template specializations when we created them.
14466   if (NeedDefinition && TSK != TSK_Undeclared &&
14467       !isa<VarTemplateSpecializationDecl>(Var))
14468     SemaRef.checkSpecializationVisibility(Loc, Var);
14469
14470   // Perform implicit instantiation of static data members, static data member
14471   // templates of class templates, and variable template specializations. Delay
14472   // instantiations of variable templates, except for those that could be used
14473   // in a constant expression.
14474   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14475     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14476
14477     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14478       if (Var->getPointOfInstantiation().isInvalid()) {
14479         // This is a modification of an existing AST node. Notify listeners.
14480         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14481           L->StaticDataMemberInstantiated(Var);
14482       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14483         // Don't bother trying to instantiate it again, unless we might need
14484         // its initializer before we get to the end of the TU.
14485         TryInstantiating = false;
14486     }
14487
14488     if (Var->getPointOfInstantiation().isInvalid())
14489       Var->setTemplateSpecializationKind(TSK, Loc);
14490
14491     if (TryInstantiating) {
14492       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14493       bool InstantiationDependent = false;
14494       bool IsNonDependent =
14495           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14496                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14497                   : true;
14498
14499       // Do not instantiate specializations that are still type-dependent.
14500       if (IsNonDependent) {
14501         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14502           // Do not defer instantiations of variables which could be used in a
14503           // constant expression.
14504           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14505         } else {
14506           SemaRef.PendingInstantiations
14507               .push_back(std::make_pair(Var, PointOfInstantiation));
14508         }
14509       }
14510     }
14511   }
14512
14513   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14514   // the requirements for appearing in a constant expression (5.19) and, if
14515   // it is an object, the lvalue-to-rvalue conversion (4.1)
14516   // is immediately applied."  We check the first part here, and
14517   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14518   // Note that we use the C++11 definition everywhere because nothing in
14519   // C++03 depends on whether we get the C++03 version correct. The second
14520   // part does not apply to references, since they are not objects.
14521   if (OdrUseContext && E &&
14522       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14523     // A reference initialized by a constant expression can never be
14524     // odr-used, so simply ignore it.
14525     if (!Var->getType()->isReferenceType())
14526       SemaRef.MaybeODRUseExprs.insert(E);
14527   } else if (OdrUseContext) {
14528     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14529                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14530   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14531     // If this is a dependent context, we don't need to mark variables as
14532     // odr-used, but we may still need to track them for lambda capture.
14533     // FIXME: Do we also need to do this inside dependent typeid expressions
14534     // (which are modeled as unevaluated at this point)?
14535     const bool RefersToEnclosingScope =
14536         (SemaRef.CurContext != Var->getDeclContext() &&
14537          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14538     if (RefersToEnclosingScope) {
14539       LambdaScopeInfo *const LSI =
14540           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14541       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14542         // If a variable could potentially be odr-used, defer marking it so
14543         // until we finish analyzing the full expression for any
14544         // lvalue-to-rvalue
14545         // or discarded value conversions that would obviate odr-use.
14546         // Add it to the list of potential captures that will be analyzed
14547         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14548         // unless the variable is a reference that was initialized by a constant
14549         // expression (this will never need to be captured or odr-used).
14550         assert(E && "Capture variable should be used in an expression.");
14551         if (!Var->getType()->isReferenceType() ||
14552             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14553           LSI->addPotentialCapture(E->IgnoreParens());
14554       }
14555     }
14556   }
14557 }
14558
14559 /// \brief Mark a variable referenced, and check whether it is odr-used
14560 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14561 /// used directly for normal expressions referring to VarDecl.
14562 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14563   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14564 }
14565
14566 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14567                                Decl *D, Expr *E, bool MightBeOdrUse) {
14568   if (SemaRef.isInOpenMPDeclareTargetContext())
14569     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14570
14571   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14572     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14573     return;
14574   }
14575
14576   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14577
14578   // If this is a call to a method via a cast, also mark the method in the
14579   // derived class used in case codegen can devirtualize the call.
14580   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14581   if (!ME)
14582     return;
14583   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14584   if (!MD)
14585     return;
14586   // Only attempt to devirtualize if this is truly a virtual call.
14587   bool IsVirtualCall = MD->isVirtual() &&
14588                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14589   if (!IsVirtualCall)
14590     return;
14591
14592   // If it's possible to devirtualize the call, mark the called function
14593   // referenced.
14594   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
14595       ME->getBase(), SemaRef.getLangOpts().AppleKext);
14596   if (DM)
14597     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14598
14599
14600 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14601 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
14602   // TODO: update this with DR# once a defect report is filed.
14603   // C++11 defect. The address of a pure member should not be an ODR use, even
14604   // if it's a qualified reference.
14605   bool OdrUse = true;
14606   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14607     if (Method->isVirtual() &&
14608         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
14609       OdrUse = false;
14610   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14611 }
14612
14613 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14614 void Sema::MarkMemberReferenced(MemberExpr *E) {
14615   // C++11 [basic.def.odr]p2:
14616   //   A non-overloaded function whose name appears as a potentially-evaluated
14617   //   expression or a member of a set of candidate functions, if selected by
14618   //   overload resolution when referred to from a potentially-evaluated
14619   //   expression, is odr-used, unless it is a pure virtual function and its
14620   //   name is not explicitly qualified.
14621   bool MightBeOdrUse = true;
14622   if (E->performsVirtualDispatch(getLangOpts())) {
14623     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14624       if (Method->isPure())
14625         MightBeOdrUse = false;
14626   }
14627   SourceLocation Loc = E->getMemberLoc().isValid() ?
14628                             E->getMemberLoc() : E->getLocStart();
14629   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14630 }
14631
14632 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14633 /// marks the declaration referenced, and performs odr-use checking for
14634 /// functions and variables. This method should not be used when building a
14635 /// normal expression which refers to a variable.
14636 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14637                                  bool MightBeOdrUse) {
14638   if (MightBeOdrUse) {
14639     if (auto *VD = dyn_cast<VarDecl>(D)) {
14640       MarkVariableReferenced(Loc, VD);
14641       return;
14642     }
14643   }
14644   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14645     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14646     return;
14647   }
14648   D->setReferenced();
14649 }
14650
14651 namespace {
14652   // Mark all of the declarations used by a type as referenced.
14653   // FIXME: Not fully implemented yet! We need to have a better understanding
14654   // of when we're entering a context we should not recurse into.
14655   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14656   // TreeTransforms rebuilding the type in a new context. Rather than
14657   // duplicating the TreeTransform logic, we should consider reusing it here.
14658   // Currently that causes problems when rebuilding LambdaExprs.
14659   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14660     Sema &S;
14661     SourceLocation Loc;
14662
14663   public:
14664     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14665
14666     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14667
14668     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14669   };
14670 }
14671
14672 bool MarkReferencedDecls::TraverseTemplateArgument(
14673     const TemplateArgument &Arg) {
14674   {
14675     // A non-type template argument is a constant-evaluated context.
14676     EnterExpressionEvaluationContext Evaluated(
14677         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14678     if (Arg.getKind() == TemplateArgument::Declaration) {
14679       if (Decl *D = Arg.getAsDecl())
14680         S.MarkAnyDeclReferenced(Loc, D, true);
14681     } else if (Arg.getKind() == TemplateArgument::Expression) {
14682       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14683     }
14684   }
14685
14686   return Inherited::TraverseTemplateArgument(Arg);
14687 }
14688
14689 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14690   MarkReferencedDecls Marker(*this, Loc);
14691   Marker.TraverseType(T);
14692 }
14693
14694 namespace {
14695   /// \brief Helper class that marks all of the declarations referenced by
14696   /// potentially-evaluated subexpressions as "referenced".
14697   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14698     Sema &S;
14699     bool SkipLocalVariables;
14700     
14701   public:
14702     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14703     
14704     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
14705       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14706     
14707     void VisitDeclRefExpr(DeclRefExpr *E) {
14708       // If we were asked not to visit local variables, don't.
14709       if (SkipLocalVariables) {
14710         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14711           if (VD->hasLocalStorage())
14712             return;
14713       }
14714       
14715       S.MarkDeclRefReferenced(E);
14716     }
14717
14718     void VisitMemberExpr(MemberExpr *E) {
14719       S.MarkMemberReferenced(E);
14720       Inherited::VisitMemberExpr(E);
14721     }
14722     
14723     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14724       S.MarkFunctionReferenced(E->getLocStart(),
14725             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14726       Visit(E->getSubExpr());
14727     }
14728     
14729     void VisitCXXNewExpr(CXXNewExpr *E) {
14730       if (E->getOperatorNew())
14731         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14732       if (E->getOperatorDelete())
14733         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14734       Inherited::VisitCXXNewExpr(E);
14735     }
14736
14737     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14738       if (E->getOperatorDelete())
14739         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14740       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14741       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14742         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14743         S.MarkFunctionReferenced(E->getLocStart(), 
14744                                     S.LookupDestructor(Record));
14745       }
14746       
14747       Inherited::VisitCXXDeleteExpr(E);
14748     }
14749     
14750     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14751       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14752       Inherited::VisitCXXConstructExpr(E);
14753     }
14754     
14755     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14756       Visit(E->getExpr());
14757     }
14758
14759     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14760       Inherited::VisitImplicitCastExpr(E);
14761
14762       if (E->getCastKind() == CK_LValueToRValue)
14763         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14764     }
14765   };
14766 }
14767
14768 /// \brief Mark any declarations that appear within this expression or any
14769 /// potentially-evaluated subexpressions as "referenced".
14770 ///
14771 /// \param SkipLocalVariables If true, don't mark local variables as 
14772 /// 'referenced'.
14773 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
14774                                             bool SkipLocalVariables) {
14775   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14776 }
14777
14778 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14779 /// of the program being compiled.
14780 ///
14781 /// This routine emits the given diagnostic when the code currently being
14782 /// type-checked is "potentially evaluated", meaning that there is a
14783 /// possibility that the code will actually be executable. Code in sizeof()
14784 /// expressions, code used only during overload resolution, etc., are not
14785 /// potentially evaluated. This routine will suppress such diagnostics or,
14786 /// in the absolutely nutty case of potentially potentially evaluated
14787 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14788 /// later.
14789 ///
14790 /// This routine should be used for all diagnostics that describe the run-time
14791 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14792 /// Failure to do so will likely result in spurious diagnostics or failures
14793 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14794 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14795                                const PartialDiagnostic &PD) {
14796   switch (ExprEvalContexts.back().Context) {
14797   case ExpressionEvaluationContext::Unevaluated:
14798   case ExpressionEvaluationContext::UnevaluatedList:
14799   case ExpressionEvaluationContext::UnevaluatedAbstract:
14800   case ExpressionEvaluationContext::DiscardedStatement:
14801     // The argument will never be evaluated, so don't complain.
14802     break;
14803
14804   case ExpressionEvaluationContext::ConstantEvaluated:
14805     // Relevant diagnostics should be produced by constant evaluation.
14806     break;
14807
14808   case ExpressionEvaluationContext::PotentiallyEvaluated:
14809   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14810     if (Statement && getCurFunctionOrMethodDecl()) {
14811       FunctionScopes.back()->PossiblyUnreachableDiags.
14812         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14813     }
14814     else
14815       Diag(Loc, PD);
14816       
14817     return true;
14818   }
14819
14820   return false;
14821 }
14822
14823 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14824                                CallExpr *CE, FunctionDecl *FD) {
14825   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14826     return false;
14827
14828   // If we're inside a decltype's expression, don't check for a valid return
14829   // type or construct temporaries until we know whether this is the last call.
14830   if (ExprEvalContexts.back().IsDecltype) {
14831     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14832     return false;
14833   }
14834
14835   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14836     FunctionDecl *FD;
14837     CallExpr *CE;
14838     
14839   public:
14840     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14841       : FD(FD), CE(CE) { }
14842
14843     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14844       if (!FD) {
14845         S.Diag(Loc, diag::err_call_incomplete_return)
14846           << T << CE->getSourceRange();
14847         return;
14848       }
14849       
14850       S.Diag(Loc, diag::err_call_function_incomplete_return)
14851         << CE->getSourceRange() << FD->getDeclName() << T;
14852       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14853           << FD->getDeclName();
14854     }
14855   } Diagnoser(FD, CE);
14856   
14857   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14858     return true;
14859
14860   return false;
14861 }
14862
14863 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14864 // will prevent this condition from triggering, which is what we want.
14865 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14866   SourceLocation Loc;
14867
14868   unsigned diagnostic = diag::warn_condition_is_assignment;
14869   bool IsOrAssign = false;
14870
14871   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14872     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14873       return;
14874
14875     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14876
14877     // Greylist some idioms by putting them into a warning subcategory.
14878     if (ObjCMessageExpr *ME
14879           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14880       Selector Sel = ME->getSelector();
14881
14882       // self = [<foo> init...]
14883       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14884         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14885
14886       // <foo> = [<bar> nextObject]
14887       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14888         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14889     }
14890
14891     Loc = Op->getOperatorLoc();
14892   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14893     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14894       return;
14895
14896     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14897     Loc = Op->getOperatorLoc();
14898   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14899     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14900   else {
14901     // Not an assignment.
14902     return;
14903   }
14904
14905   Diag(Loc, diagnostic) << E->getSourceRange();
14906
14907   SourceLocation Open = E->getLocStart();
14908   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14909   Diag(Loc, diag::note_condition_assign_silence)
14910         << FixItHint::CreateInsertion(Open, "(")
14911         << FixItHint::CreateInsertion(Close, ")");
14912
14913   if (IsOrAssign)
14914     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14915       << FixItHint::CreateReplacement(Loc, "!=");
14916   else
14917     Diag(Loc, diag::note_condition_assign_to_comparison)
14918       << FixItHint::CreateReplacement(Loc, "==");
14919 }
14920
14921 /// \brief Redundant parentheses over an equality comparison can indicate
14922 /// that the user intended an assignment used as condition.
14923 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14924   // Don't warn if the parens came from a macro.
14925   SourceLocation parenLoc = ParenE->getLocStart();
14926   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14927     return;
14928   // Don't warn for dependent expressions.
14929   if (ParenE->isTypeDependent())
14930     return;
14931
14932   Expr *E = ParenE->IgnoreParens();
14933
14934   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14935     if (opE->getOpcode() == BO_EQ &&
14936         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14937                                                            == Expr::MLV_Valid) {
14938       SourceLocation Loc = opE->getOperatorLoc();
14939       
14940       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14941       SourceRange ParenERange = ParenE->getSourceRange();
14942       Diag(Loc, diag::note_equality_comparison_silence)
14943         << FixItHint::CreateRemoval(ParenERange.getBegin())
14944         << FixItHint::CreateRemoval(ParenERange.getEnd());
14945       Diag(Loc, diag::note_equality_comparison_to_assign)
14946         << FixItHint::CreateReplacement(Loc, "=");
14947     }
14948 }
14949
14950 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14951                                        bool IsConstexpr) {
14952   DiagnoseAssignmentAsCondition(E);
14953   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14954     DiagnoseEqualityWithExtraParens(parenE);
14955
14956   ExprResult result = CheckPlaceholderExpr(E);
14957   if (result.isInvalid()) return ExprError();
14958   E = result.get();
14959
14960   if (!E->isTypeDependent()) {
14961     if (getLangOpts().CPlusPlus)
14962       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14963
14964     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14965     if (ERes.isInvalid())
14966       return ExprError();
14967     E = ERes.get();
14968
14969     QualType T = E->getType();
14970     if (!T->isScalarType()) { // C99 6.8.4.1p1
14971       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14972         << T << E->getSourceRange();
14973       return ExprError();
14974     }
14975     CheckBoolLikeConversion(E, Loc);
14976   }
14977
14978   return E;
14979 }
14980
14981 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14982                                            Expr *SubExpr, ConditionKind CK) {
14983   // Empty conditions are valid in for-statements.
14984   if (!SubExpr)
14985     return ConditionResult();
14986
14987   ExprResult Cond;
14988   switch (CK) {
14989   case ConditionKind::Boolean:
14990     Cond = CheckBooleanCondition(Loc, SubExpr);
14991     break;
14992
14993   case ConditionKind::ConstexprIf:
14994     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14995     break;
14996
14997   case ConditionKind::Switch:
14998     Cond = CheckSwitchCondition(Loc, SubExpr);
14999     break;
15000   }
15001   if (Cond.isInvalid())
15002     return ConditionError();
15003
15004   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15005   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15006   if (!FullExpr.get())
15007     return ConditionError();
15008
15009   return ConditionResult(*this, nullptr, FullExpr,
15010                          CK == ConditionKind::ConstexprIf);
15011 }
15012
15013 namespace {
15014   /// A visitor for rebuilding a call to an __unknown_any expression
15015   /// to have an appropriate type.
15016   struct RebuildUnknownAnyFunction
15017     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15018
15019     Sema &S;
15020
15021     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15022
15023     ExprResult VisitStmt(Stmt *S) {
15024       llvm_unreachable("unexpected statement!");
15025     }
15026
15027     ExprResult VisitExpr(Expr *E) {
15028       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15029         << E->getSourceRange();
15030       return ExprError();
15031     }
15032
15033     /// Rebuild an expression which simply semantically wraps another
15034     /// expression which it shares the type and value kind of.
15035     template <class T> ExprResult rebuildSugarExpr(T *E) {
15036       ExprResult SubResult = Visit(E->getSubExpr());
15037       if (SubResult.isInvalid()) return ExprError();
15038
15039       Expr *SubExpr = SubResult.get();
15040       E->setSubExpr(SubExpr);
15041       E->setType(SubExpr->getType());
15042       E->setValueKind(SubExpr->getValueKind());
15043       assert(E->getObjectKind() == OK_Ordinary);
15044       return E;
15045     }
15046
15047     ExprResult VisitParenExpr(ParenExpr *E) {
15048       return rebuildSugarExpr(E);
15049     }
15050
15051     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15052       return rebuildSugarExpr(E);
15053     }
15054
15055     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15056       ExprResult SubResult = Visit(E->getSubExpr());
15057       if (SubResult.isInvalid()) return ExprError();
15058
15059       Expr *SubExpr = SubResult.get();
15060       E->setSubExpr(SubExpr);
15061       E->setType(S.Context.getPointerType(SubExpr->getType()));
15062       assert(E->getValueKind() == VK_RValue);
15063       assert(E->getObjectKind() == OK_Ordinary);
15064       return E;
15065     }
15066
15067     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15068       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15069
15070       E->setType(VD->getType());
15071
15072       assert(E->getValueKind() == VK_RValue);
15073       if (S.getLangOpts().CPlusPlus &&
15074           !(isa<CXXMethodDecl>(VD) &&
15075             cast<CXXMethodDecl>(VD)->isInstance()))
15076         E->setValueKind(VK_LValue);
15077
15078       return E;
15079     }
15080
15081     ExprResult VisitMemberExpr(MemberExpr *E) {
15082       return resolveDecl(E, E->getMemberDecl());
15083     }
15084
15085     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15086       return resolveDecl(E, E->getDecl());
15087     }
15088   };
15089 }
15090
15091 /// Given a function expression of unknown-any type, try to rebuild it
15092 /// to have a function type.
15093 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15094   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15095   if (Result.isInvalid()) return ExprError();
15096   return S.DefaultFunctionArrayConversion(Result.get());
15097 }
15098
15099 namespace {
15100   /// A visitor for rebuilding an expression of type __unknown_anytype
15101   /// into one which resolves the type directly on the referring
15102   /// expression.  Strict preservation of the original source
15103   /// structure is not a goal.
15104   struct RebuildUnknownAnyExpr
15105     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15106
15107     Sema &S;
15108
15109     /// The current destination type.
15110     QualType DestType;
15111
15112     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15113       : S(S), DestType(CastType) {}
15114
15115     ExprResult VisitStmt(Stmt *S) {
15116       llvm_unreachable("unexpected statement!");
15117     }
15118
15119     ExprResult VisitExpr(Expr *E) {
15120       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15121         << E->getSourceRange();
15122       return ExprError();
15123     }
15124
15125     ExprResult VisitCallExpr(CallExpr *E);
15126     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15127
15128     /// Rebuild an expression which simply semantically wraps another
15129     /// expression which it shares the type and value kind of.
15130     template <class T> ExprResult rebuildSugarExpr(T *E) {
15131       ExprResult SubResult = Visit(E->getSubExpr());
15132       if (SubResult.isInvalid()) return ExprError();
15133       Expr *SubExpr = SubResult.get();
15134       E->setSubExpr(SubExpr);
15135       E->setType(SubExpr->getType());
15136       E->setValueKind(SubExpr->getValueKind());
15137       assert(E->getObjectKind() == OK_Ordinary);
15138       return E;
15139     }
15140
15141     ExprResult VisitParenExpr(ParenExpr *E) {
15142       return rebuildSugarExpr(E);
15143     }
15144
15145     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15146       return rebuildSugarExpr(E);
15147     }
15148
15149     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15150       const PointerType *Ptr = DestType->getAs<PointerType>();
15151       if (!Ptr) {
15152         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15153           << E->getSourceRange();
15154         return ExprError();
15155       }
15156
15157       if (isa<CallExpr>(E->getSubExpr())) {
15158         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15159           << E->getSourceRange();
15160         return ExprError();
15161       }
15162
15163       assert(E->getValueKind() == VK_RValue);
15164       assert(E->getObjectKind() == OK_Ordinary);
15165       E->setType(DestType);
15166
15167       // Build the sub-expression as if it were an object of the pointee type.
15168       DestType = Ptr->getPointeeType();
15169       ExprResult SubResult = Visit(E->getSubExpr());
15170       if (SubResult.isInvalid()) return ExprError();
15171       E->setSubExpr(SubResult.get());
15172       return E;
15173     }
15174
15175     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15176
15177     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15178
15179     ExprResult VisitMemberExpr(MemberExpr *E) {
15180       return resolveDecl(E, E->getMemberDecl());
15181     }
15182
15183     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15184       return resolveDecl(E, E->getDecl());
15185     }
15186   };
15187 }
15188
15189 /// Rebuilds a call expression which yielded __unknown_anytype.
15190 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15191   Expr *CalleeExpr = E->getCallee();
15192
15193   enum FnKind {
15194     FK_MemberFunction,
15195     FK_FunctionPointer,
15196     FK_BlockPointer
15197   };
15198
15199   FnKind Kind;
15200   QualType CalleeType = CalleeExpr->getType();
15201   if (CalleeType == S.Context.BoundMemberTy) {
15202     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15203     Kind = FK_MemberFunction;
15204     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15205   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15206     CalleeType = Ptr->getPointeeType();
15207     Kind = FK_FunctionPointer;
15208   } else {
15209     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15210     Kind = FK_BlockPointer;
15211   }
15212   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15213
15214   // Verify that this is a legal result type of a function.
15215   if (DestType->isArrayType() || DestType->isFunctionType()) {
15216     unsigned diagID = diag::err_func_returning_array_function;
15217     if (Kind == FK_BlockPointer)
15218       diagID = diag::err_block_returning_array_function;
15219
15220     S.Diag(E->getExprLoc(), diagID)
15221       << DestType->isFunctionType() << DestType;
15222     return ExprError();
15223   }
15224
15225   // Otherwise, go ahead and set DestType as the call's result.
15226   E->setType(DestType.getNonLValueExprType(S.Context));
15227   E->setValueKind(Expr::getValueKindForType(DestType));
15228   assert(E->getObjectKind() == OK_Ordinary);
15229
15230   // Rebuild the function type, replacing the result type with DestType.
15231   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15232   if (Proto) {
15233     // __unknown_anytype(...) is a special case used by the debugger when
15234     // it has no idea what a function's signature is.
15235     //
15236     // We want to build this call essentially under the K&R
15237     // unprototyped rules, but making a FunctionNoProtoType in C++
15238     // would foul up all sorts of assumptions.  However, we cannot
15239     // simply pass all arguments as variadic arguments, nor can we
15240     // portably just call the function under a non-variadic type; see
15241     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15242     // However, it turns out that in practice it is generally safe to
15243     // call a function declared as "A foo(B,C,D);" under the prototype
15244     // "A foo(B,C,D,...);".  The only known exception is with the
15245     // Windows ABI, where any variadic function is implicitly cdecl
15246     // regardless of its normal CC.  Therefore we change the parameter
15247     // types to match the types of the arguments.
15248     //
15249     // This is a hack, but it is far superior to moving the
15250     // corresponding target-specific code from IR-gen to Sema/AST.
15251
15252     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15253     SmallVector<QualType, 8> ArgTypes;
15254     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15255       ArgTypes.reserve(E->getNumArgs());
15256       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15257         Expr *Arg = E->getArg(i);
15258         QualType ArgType = Arg->getType();
15259         if (E->isLValue()) {
15260           ArgType = S.Context.getLValueReferenceType(ArgType);
15261         } else if (E->isXValue()) {
15262           ArgType = S.Context.getRValueReferenceType(ArgType);
15263         }
15264         ArgTypes.push_back(ArgType);
15265       }
15266       ParamTypes = ArgTypes;
15267     }
15268     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15269                                          Proto->getExtProtoInfo());
15270   } else {
15271     DestType = S.Context.getFunctionNoProtoType(DestType,
15272                                                 FnType->getExtInfo());
15273   }
15274
15275   // Rebuild the appropriate pointer-to-function type.
15276   switch (Kind) { 
15277   case FK_MemberFunction:
15278     // Nothing to do.
15279     break;
15280
15281   case FK_FunctionPointer:
15282     DestType = S.Context.getPointerType(DestType);
15283     break;
15284
15285   case FK_BlockPointer:
15286     DestType = S.Context.getBlockPointerType(DestType);
15287     break;
15288   }
15289
15290   // Finally, we can recurse.
15291   ExprResult CalleeResult = Visit(CalleeExpr);
15292   if (!CalleeResult.isUsable()) return ExprError();
15293   E->setCallee(CalleeResult.get());
15294
15295   // Bind a temporary if necessary.
15296   return S.MaybeBindToTemporary(E);
15297 }
15298
15299 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15300   // Verify that this is a legal result type of a call.
15301   if (DestType->isArrayType() || DestType->isFunctionType()) {
15302     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15303       << DestType->isFunctionType() << DestType;
15304     return ExprError();
15305   }
15306
15307   // Rewrite the method result type if available.
15308   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15309     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15310     Method->setReturnType(DestType);
15311   }
15312
15313   // Change the type of the message.
15314   E->setType(DestType.getNonReferenceType());
15315   E->setValueKind(Expr::getValueKindForType(DestType));
15316
15317   return S.MaybeBindToTemporary(E);
15318 }
15319
15320 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15321   // The only case we should ever see here is a function-to-pointer decay.
15322   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15323     assert(E->getValueKind() == VK_RValue);
15324     assert(E->getObjectKind() == OK_Ordinary);
15325   
15326     E->setType(DestType);
15327   
15328     // Rebuild the sub-expression as the pointee (function) type.
15329     DestType = DestType->castAs<PointerType>()->getPointeeType();
15330   
15331     ExprResult Result = Visit(E->getSubExpr());
15332     if (!Result.isUsable()) return ExprError();
15333   
15334     E->setSubExpr(Result.get());
15335     return E;
15336   } else if (E->getCastKind() == CK_LValueToRValue) {
15337     assert(E->getValueKind() == VK_RValue);
15338     assert(E->getObjectKind() == OK_Ordinary);
15339
15340     assert(isa<BlockPointerType>(E->getType()));
15341
15342     E->setType(DestType);
15343
15344     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15345     DestType = S.Context.getLValueReferenceType(DestType);
15346
15347     ExprResult Result = Visit(E->getSubExpr());
15348     if (!Result.isUsable()) return ExprError();
15349
15350     E->setSubExpr(Result.get());
15351     return E;
15352   } else {
15353     llvm_unreachable("Unhandled cast type!");
15354   }
15355 }
15356
15357 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15358   ExprValueKind ValueKind = VK_LValue;
15359   QualType Type = DestType;
15360
15361   // We know how to make this work for certain kinds of decls:
15362
15363   //  - functions
15364   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15365     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15366       DestType = Ptr->getPointeeType();
15367       ExprResult Result = resolveDecl(E, VD);
15368       if (Result.isInvalid()) return ExprError();
15369       return S.ImpCastExprToType(Result.get(), Type,
15370                                  CK_FunctionToPointerDecay, VK_RValue);
15371     }
15372
15373     if (!Type->isFunctionType()) {
15374       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15375         << VD << E->getSourceRange();
15376       return ExprError();
15377     }
15378     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15379       // We must match the FunctionDecl's type to the hack introduced in
15380       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15381       // type. See the lengthy commentary in that routine.
15382       QualType FDT = FD->getType();
15383       const FunctionType *FnType = FDT->castAs<FunctionType>();
15384       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15385       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15386       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15387         SourceLocation Loc = FD->getLocation();
15388         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15389                                       FD->getDeclContext(),
15390                                       Loc, Loc, FD->getNameInfo().getName(),
15391                                       DestType, FD->getTypeSourceInfo(),
15392                                       SC_None, false/*isInlineSpecified*/,
15393                                       FD->hasPrototype(),
15394                                       false/*isConstexprSpecified*/);
15395           
15396         if (FD->getQualifier())
15397           NewFD->setQualifierInfo(FD->getQualifierLoc());
15398
15399         SmallVector<ParmVarDecl*, 16> Params;
15400         for (const auto &AI : FT->param_types()) {
15401           ParmVarDecl *Param =
15402             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15403           Param->setScopeInfo(0, Params.size());
15404           Params.push_back(Param);
15405         }
15406         NewFD->setParams(Params);
15407         DRE->setDecl(NewFD);
15408         VD = DRE->getDecl();
15409       }
15410     }
15411
15412     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15413       if (MD->isInstance()) {
15414         ValueKind = VK_RValue;
15415         Type = S.Context.BoundMemberTy;
15416       }
15417
15418     // Function references aren't l-values in C.
15419     if (!S.getLangOpts().CPlusPlus)
15420       ValueKind = VK_RValue;
15421
15422   //  - variables
15423   } else if (isa<VarDecl>(VD)) {
15424     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15425       Type = RefTy->getPointeeType();
15426     } else if (Type->isFunctionType()) {
15427       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15428         << VD << E->getSourceRange();
15429       return ExprError();
15430     }
15431
15432   //  - nothing else
15433   } else {
15434     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15435       << VD << E->getSourceRange();
15436     return ExprError();
15437   }
15438
15439   // Modifying the declaration like this is friendly to IR-gen but
15440   // also really dangerous.
15441   VD->setType(DestType);
15442   E->setType(Type);
15443   E->setValueKind(ValueKind);
15444   return E;
15445 }
15446
15447 /// Check a cast of an unknown-any type.  We intentionally only
15448 /// trigger this for C-style casts.
15449 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15450                                      Expr *CastExpr, CastKind &CastKind,
15451                                      ExprValueKind &VK, CXXCastPath &Path) {
15452   // The type we're casting to must be either void or complete.
15453   if (!CastType->isVoidType() &&
15454       RequireCompleteType(TypeRange.getBegin(), CastType,
15455                           diag::err_typecheck_cast_to_incomplete))
15456     return ExprError();
15457
15458   // Rewrite the casted expression from scratch.
15459   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15460   if (!result.isUsable()) return ExprError();
15461
15462   CastExpr = result.get();
15463   VK = CastExpr->getValueKind();
15464   CastKind = CK_NoOp;
15465
15466   return CastExpr;
15467 }
15468
15469 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15470   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15471 }
15472
15473 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15474                                     Expr *arg, QualType &paramType) {
15475   // If the syntactic form of the argument is not an explicit cast of
15476   // any sort, just do default argument promotion.
15477   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15478   if (!castArg) {
15479     ExprResult result = DefaultArgumentPromotion(arg);
15480     if (result.isInvalid()) return ExprError();
15481     paramType = result.get()->getType();
15482     return result;
15483   }
15484
15485   // Otherwise, use the type that was written in the explicit cast.
15486   assert(!arg->hasPlaceholderType());
15487   paramType = castArg->getTypeAsWritten();
15488
15489   // Copy-initialize a parameter of that type.
15490   InitializedEntity entity =
15491     InitializedEntity::InitializeParameter(Context, paramType,
15492                                            /*consumed*/ false);
15493   return PerformCopyInitialization(entity, callLoc, arg);
15494 }
15495
15496 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15497   Expr *orig = E;
15498   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15499   while (true) {
15500     E = E->IgnoreParenImpCasts();
15501     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15502       E = call->getCallee();
15503       diagID = diag::err_uncasted_call_of_unknown_any;
15504     } else {
15505       break;
15506     }
15507   }
15508
15509   SourceLocation loc;
15510   NamedDecl *d;
15511   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15512     loc = ref->getLocation();
15513     d = ref->getDecl();
15514   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15515     loc = mem->getMemberLoc();
15516     d = mem->getMemberDecl();
15517   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15518     diagID = diag::err_uncasted_call_of_unknown_any;
15519     loc = msg->getSelectorStartLoc();
15520     d = msg->getMethodDecl();
15521     if (!d) {
15522       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15523         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15524         << orig->getSourceRange();
15525       return ExprError();
15526     }
15527   } else {
15528     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15529       << E->getSourceRange();
15530     return ExprError();
15531   }
15532
15533   S.Diag(loc, diagID) << d << orig->getSourceRange();
15534
15535   // Never recoverable.
15536   return ExprError();
15537 }
15538
15539 /// Check for operands with placeholder types and complain if found.
15540 /// Returns ExprError() if there was an error and no recovery was possible.
15541 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15542   if (!getLangOpts().CPlusPlus) {
15543     // C cannot handle TypoExpr nodes on either side of a binop because it
15544     // doesn't handle dependent types properly, so make sure any TypoExprs have
15545     // been dealt with before checking the operands.
15546     ExprResult Result = CorrectDelayedTyposInExpr(E);
15547     if (!Result.isUsable()) return ExprError();
15548     E = Result.get();
15549   }
15550
15551   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15552   if (!placeholderType) return E;
15553
15554   switch (placeholderType->getKind()) {
15555
15556   // Overloaded expressions.
15557   case BuiltinType::Overload: {
15558     // Try to resolve a single function template specialization.
15559     // This is obligatory.
15560     ExprResult Result = E;
15561     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15562       return Result;
15563
15564     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15565     // leaves Result unchanged on failure.
15566     Result = E;
15567     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15568       return Result;
15569
15570     // If that failed, try to recover with a call.
15571     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15572                          /*complain*/ true);
15573     return Result;
15574   }
15575
15576   // Bound member functions.
15577   case BuiltinType::BoundMember: {
15578     ExprResult result = E;
15579     const Expr *BME = E->IgnoreParens();
15580     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15581     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15582     if (isa<CXXPseudoDestructorExpr>(BME)) {
15583       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15584     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15585       if (ME->getMemberNameInfo().getName().getNameKind() ==
15586           DeclarationName::CXXDestructorName)
15587         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15588     }
15589     tryToRecoverWithCall(result, PD,
15590                          /*complain*/ true);
15591     return result;
15592   }
15593
15594   // ARC unbridged casts.
15595   case BuiltinType::ARCUnbridgedCast: {
15596     Expr *realCast = stripARCUnbridgedCast(E);
15597     diagnoseARCUnbridgedCast(realCast);
15598     return realCast;
15599   }
15600
15601   // Expressions of unknown type.
15602   case BuiltinType::UnknownAny:
15603     return diagnoseUnknownAnyExpr(*this, E);
15604
15605   // Pseudo-objects.
15606   case BuiltinType::PseudoObject:
15607     return checkPseudoObjectRValue(E);
15608
15609   case BuiltinType::BuiltinFn: {
15610     // Accept __noop without parens by implicitly converting it to a call expr.
15611     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15612     if (DRE) {
15613       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15614       if (FD->getBuiltinID() == Builtin::BI__noop) {
15615         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15616                               CK_BuiltinFnToFnPtr).get();
15617         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15618                                       VK_RValue, SourceLocation());
15619       }
15620     }
15621
15622     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15623     return ExprError();
15624   }
15625
15626   // Expressions of unknown type.
15627   case BuiltinType::OMPArraySection:
15628     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15629     return ExprError();
15630
15631   // Everything else should be impossible.
15632 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15633   case BuiltinType::Id:
15634 #include "clang/Basic/OpenCLImageTypes.def"
15635 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15636 #define PLACEHOLDER_TYPE(Id, SingletonId)
15637 #include "clang/AST/BuiltinTypes.def"
15638     break;
15639   }
15640
15641   llvm_unreachable("invalid placeholder type!");
15642 }
15643
15644 bool Sema::CheckCaseExpression(Expr *E) {
15645   if (E->isTypeDependent())
15646     return true;
15647   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15648     return E->getType()->isIntegralOrEnumerationType();
15649   return false;
15650 }
15651
15652 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15653 ExprResult
15654 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15655   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15656          "Unknown Objective-C Boolean value!");
15657   QualType BoolT = Context.ObjCBuiltinBoolTy;
15658   if (!Context.getBOOLDecl()) {
15659     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15660                         Sema::LookupOrdinaryName);
15661     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15662       NamedDecl *ND = Result.getFoundDecl();
15663       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
15664         Context.setBOOLDecl(TD);
15665     }
15666   }
15667   if (Context.getBOOLDecl())
15668     BoolT = Context.getBOOLType();
15669   return new (Context)
15670       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15671 }
15672
15673 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15674     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15675     SourceLocation RParen) {
15676
15677   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15678
15679   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15680                            [&](const AvailabilitySpec &Spec) {
15681                              return Spec.getPlatform() == Platform;
15682                            });
15683
15684   VersionTuple Version;
15685   if (Spec != AvailSpecs.end())
15686     Version = Spec->getVersion();
15687
15688   // The use of `@available` in the enclosing function should be analyzed to
15689   // warn when it's used inappropriately (i.e. not if(@available)).
15690   if (getCurFunctionOrMethodDecl())
15691     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
15692   else if (getCurBlock() || getCurLambda())
15693     getCurFunction()->HasPotentialAvailabilityViolations = true;
15694
15695   return new (Context)
15696       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15697 }