1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/FixedPoint.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/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68 
69     // See if this is an aligned allocation/deallocation function that is
70     // unavailable.
71     if (TreatUnavailableAsInvalid &&
72         isUnavailableAlignedAllocationFunction(*FD))
73       return false;
74   }
75 
76   // See if this function is unavailable.
77   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
78       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
79     return false;
80 
81   return true;
82 }
83 
84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
85   // Warn if this is used but marked unused.
86   if (const auto *A = D->getAttr<UnusedAttr>()) {
87     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
88     // should diagnose them.
89     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
90         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
91       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
92       if (DC && !DC->hasAttr<UnusedAttr>())
93         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
94     }
95   }
96 }
97 
98 /// Emit a note explaining that this function is deleted.
99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
100   assert(Decl->isDeleted());
101 
102   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
103 
104   if (Method && Method->isDeleted() && Method->isDefaulted()) {
105     // If the method was explicitly defaulted, point at that declaration.
106     if (!Method->isImplicit())
107       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108 
109     // Try to diagnose why this special member function was implicitly
110     // deleted. This might fail, if that reason no longer applies.
111     CXXSpecialMember CSM = getSpecialMember(Method);
112     if (CSM != CXXInvalid)
113       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
114 
115     return;
116   }
117 
118   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119   if (Ctor && Ctor->isInheritingConstructor())
120     return NoteDeletedInheritingConstructor(Ctor);
121 
122   Diag(Decl->getLocation(), diag::note_availability_specified_here)
123     << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129   for (auto I : D->redecls()) {
130     if (I->getStorageClass() != SC_None)
131       return true;
132   }
133   return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145                                                       const NamedDecl *D,
146                                                       SourceLocation Loc) {
147   // This is disabled under C++; there are too many ways for this to fire in
148   // contexts where the warning is a false positive, or where it is technically
149   // correct but benign.
150   if (S.getLangOpts().CPlusPlus)
151     return;
152 
153   // Check if this is an inlined function or method.
154   FunctionDecl *Current = S.getCurFunctionDecl();
155   if (!Current)
156     return;
157   if (!Current->isInlined())
158     return;
159   if (!Current->isExternallyVisible())
160     return;
161 
162   // Check if the decl has internal linkage.
163   if (D->getFormalLinkage() != InternalLinkage)
164     return;
165 
166   // Downgrade from ExtWarn to Extension if
167   //  (1) the supposedly external inline function is in the main file,
168   //      and probably won't be included anywhere else.
169   //  (2) the thing we're referencing is a pure function.
170   //  (3) the thing we're referencing is another inline function.
171   // This last can give us false negatives, but it's better than warning on
172   // wrappers for simple C library functions.
173   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175   if (!DowngradeWarning && UsedFn)
176     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179                                : diag::ext_internal_in_extern_inline)
180     << /*IsVar=*/!UsedFn << D;
181 
182   S.MaybeSuggestAddingStaticToDecl(Current);
183 
184   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185       << D;
186 }
187 
188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189   const FunctionDecl *First = Cur->getFirstDecl();
190 
191   // Suggest "static" on the function, if possible.
192   if (!hasAnyExplicitStorageClass(First)) {
193     SourceLocation DeclBegin = First->getSourceRange().getBegin();
194     Diag(DeclBegin, diag::note_convert_inline_to_static)
195       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196   }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212                              const ObjCInterfaceDecl *UnknownObjCClass,
213                              bool ObjCPropertyAccess,
214                              bool AvoidPartialAvailabilityChecks,
215                              ObjCInterfaceDecl *ClassReceiver) {
216   SourceLocation Loc = Locs.front();
217   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218     // If there were any diagnostics suppressed by template argument deduction,
219     // emit them now.
220     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221     if (Pos != SuppressedDiagnostics.end()) {
222       for (const PartialDiagnosticAt &Suppressed : Pos->second)
223         Diag(Suppressed.first, Suppressed.second);
224 
225       // Clear out the list of suppressed diagnostics, so that we don't emit
226       // them again for this specialization. However, we don't obsolete this
227       // entry from the table, because we want to avoid ever emitting these
228       // diagnostics again.
229       Pos->second.clear();
230     }
231 
232     // C++ [basic.start.main]p3:
233     //   The function 'main' shall not be used within a program.
234     if (cast<FunctionDecl>(D)->isMain())
235       Diag(Loc, diag::ext_main_used);
236 
237     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238   }
239 
240   // See if this is an auto-typed variable whose initializer we are parsing.
241   if (ParsingInitForAutoVars.count(D)) {
242     if (isa<BindingDecl>(D)) {
243       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244         << D->getDeclName();
245     } else {
246       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247         << D->getDeclName() << cast<VarDecl>(D)->getType();
248     }
249     return true;
250   }
251 
252   // See if this is a deleted function.
253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254     if (FD->isDeleted()) {
255       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256       if (Ctor && Ctor->isInheritingConstructor())
257         Diag(Loc, diag::err_deleted_inherited_ctor_use)
258             << Ctor->getParent()
259             << Ctor->getInheritedConstructor().getConstructor()->getParent();
260       else
261         Diag(Loc, diag::err_deleted_function_use);
262       NoteDeletedFunction(FD);
263       return true;
264     }
265 
266     // If the function has a deduced return type, and we can't deduce it,
267     // then we can't use it either.
268     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
269         DeduceReturnType(FD, Loc))
270       return true;
271 
272     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
273       return true;
274   }
275 
276   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
277     // Lambdas are only default-constructible or assignable in C++2a onwards.
278     if (MD->getParent()->isLambda() &&
279         ((isa<CXXConstructorDecl>(MD) &&
280           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
281          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
282       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
283         << !isa<CXXConstructorDecl>(MD);
284     }
285   }
286 
287   auto getReferencedObjCProp = [](const NamedDecl *D) ->
288                                       const ObjCPropertyDecl * {
289     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
290       return MD->findPropertyDecl();
291     return nullptr;
292   };
293   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
294     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
295       return true;
296   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
297       return true;
298   }
299 
300   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
301   // Only the variables omp_in and omp_out are allowed in the combiner.
302   // Only the variables omp_priv and omp_orig are allowed in the
303   // initializer-clause.
304   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
305   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
306       isa<VarDecl>(D)) {
307     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
308         << getCurFunction()->HasOMPDeclareReductionCombiner;
309     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
310     return true;
311   }
312 
313   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
314   //  List-items in map clauses on this construct may only refer to the declared
315   //  variable var and entities that could be referenced by a procedure defined
316   //  at the same location
317   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
318   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
319       isa<VarDecl>(D)) {
320     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
321         << DMD->getVarName().getAsString();
322     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
323     return true;
324   }
325 
326   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
327                              AvoidPartialAvailabilityChecks, ClassReceiver);
328 
329   DiagnoseUnusedOfDecl(*this, D, Loc);
330 
331   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
332 
333   return false;
334 }
335 
336 /// DiagnoseSentinelCalls - This routine checks whether a call or
337 /// message-send is to a declaration with the sentinel attribute, and
338 /// if so, it checks that the requirements of the sentinel are
339 /// satisfied.
340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
341                                  ArrayRef<Expr *> Args) {
342   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
343   if (!attr)
344     return;
345 
346   // The number of formal parameters of the declaration.
347   unsigned numFormalParams;
348 
349   // The kind of declaration.  This is also an index into a %select in
350   // the diagnostic.
351   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
352 
353   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
354     numFormalParams = MD->param_size();
355     calleeType = CT_Method;
356   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
357     numFormalParams = FD->param_size();
358     calleeType = CT_Function;
359   } else if (isa<VarDecl>(D)) {
360     QualType type = cast<ValueDecl>(D)->getType();
361     const FunctionType *fn = nullptr;
362     if (const PointerType *ptr = type->getAs<PointerType>()) {
363       fn = ptr->getPointeeType()->getAs<FunctionType>();
364       if (!fn) return;
365       calleeType = CT_Function;
366     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
367       fn = ptr->getPointeeType()->castAs<FunctionType>();
368       calleeType = CT_Block;
369     } else {
370       return;
371     }
372 
373     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
374       numFormalParams = proto->getNumParams();
375     } else {
376       numFormalParams = 0;
377     }
378   } else {
379     return;
380   }
381 
382   // "nullPos" is the number of formal parameters at the end which
383   // effectively count as part of the variadic arguments.  This is
384   // useful if you would prefer to not have *any* formal parameters,
385   // but the language forces you to have at least one.
386   unsigned nullPos = attr->getNullPos();
387   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
388   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
389 
390   // The number of arguments which should follow the sentinel.
391   unsigned numArgsAfterSentinel = attr->getSentinel();
392 
393   // If there aren't enough arguments for all the formal parameters,
394   // the sentinel, and the args after the sentinel, complain.
395   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
396     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
397     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
398     return;
399   }
400 
401   // Otherwise, find the sentinel expression.
402   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
403   if (!sentinelExpr) return;
404   if (sentinelExpr->isValueDependent()) return;
405   if (Context.isSentinelNullExpr(sentinelExpr)) return;
406 
407   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
408   // or 'NULL' if those are actually defined in the context.  Only use
409   // 'nil' for ObjC methods, where it's much more likely that the
410   // variadic arguments form a list of object pointers.
411   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
412   std::string NullValue;
413   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
414     NullValue = "nil";
415   else if (getLangOpts().CPlusPlus11)
416     NullValue = "nullptr";
417   else if (PP.isMacroDefined("NULL"))
418     NullValue = "NULL";
419   else
420     NullValue = "(void*) 0";
421 
422   if (MissingNilLoc.isInvalid())
423     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
424   else
425     Diag(MissingNilLoc, diag::warn_missing_sentinel)
426       << int(calleeType)
427       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
428   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429 }
430 
431 SourceRange Sema::getExprRange(Expr *E) const {
432   return E ? E->getSourceRange() : SourceRange();
433 }
434 
435 //===----------------------------------------------------------------------===//
436 //  Standard Promotions and Conversions
437 //===----------------------------------------------------------------------===//
438 
439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
441   // Handle any placeholder expressions which made it here.
442   if (E->getType()->isPlaceholderType()) {
443     ExprResult result = CheckPlaceholderExpr(E);
444     if (result.isInvalid()) return ExprError();
445     E = result.get();
446   }
447 
448   QualType Ty = E->getType();
449   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
450 
451   if (Ty->isFunctionType()) {
452     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
453       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
454         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
455           return ExprError();
456 
457     E = ImpCastExprToType(E, Context.getPointerType(Ty),
458                           CK_FunctionToPointerDecay).get();
459   } else if (Ty->isArrayType()) {
460     // In C90 mode, arrays only promote to pointers if the array expression is
461     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
462     // type 'array of type' is converted to an expression that has type 'pointer
463     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
464     // that has type 'array of type' ...".  The relevant change is "an lvalue"
465     // (C90) to "an expression" (C99).
466     //
467     // C++ 4.2p1:
468     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
469     // T" can be converted to an rvalue of type "pointer to T".
470     //
471     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
472       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
473                             CK_ArrayToPointerDecay).get();
474   }
475   return E;
476 }
477 
478 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
479   // Check to see if we are dereferencing a null pointer.  If so,
480   // and if not volatile-qualified, this is undefined behavior that the
481   // optimizer will delete, so warn about it.  People sometimes try to use this
482   // to get a deterministic trap and are surprised by clang's behavior.  This
483   // only handles the pattern "*null", which is a very syntactic check.
484   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
485     if (UO->getOpcode() == UO_Deref &&
486         UO->getSubExpr()->IgnoreParenCasts()->
487           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
488         !UO->getType().isVolatileQualified()) {
489     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
490                           S.PDiag(diag::warn_indirection_through_null)
491                             << UO->getSubExpr()->getSourceRange());
492     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
493                         S.PDiag(diag::note_indirection_through_null));
494   }
495 }
496 
497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
498                                     SourceLocation AssignLoc,
499                                     const Expr* RHS) {
500   const ObjCIvarDecl *IV = OIRE->getDecl();
501   if (!IV)
502     return;
503 
504   DeclarationName MemberName = IV->getDeclName();
505   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
506   if (!Member || !Member->isStr("isa"))
507     return;
508 
509   const Expr *Base = OIRE->getBase();
510   QualType BaseType = Base->getType();
511   if (OIRE->isArrow())
512     BaseType = BaseType->getPointeeType();
513   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
514     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
515       ObjCInterfaceDecl *ClassDeclared = nullptr;
516       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
517       if (!ClassDeclared->getSuperClass()
518           && (*ClassDeclared->ivar_begin()) == IV) {
519         if (RHS) {
520           NamedDecl *ObjectSetClass =
521             S.LookupSingleName(S.TUScope,
522                                &S.Context.Idents.get("object_setClass"),
523                                SourceLocation(), S.LookupOrdinaryName);
524           if (ObjectSetClass) {
525             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
526             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
527                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
528                                               "object_setClass(")
529                 << FixItHint::CreateReplacement(
530                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
531                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
532           }
533           else
534             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
535         } else {
536           NamedDecl *ObjectGetClass =
537             S.LookupSingleName(S.TUScope,
538                                &S.Context.Idents.get("object_getClass"),
539                                SourceLocation(), S.LookupOrdinaryName);
540           if (ObjectGetClass)
541             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
542                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
543                                               "object_getClass(")
544                 << FixItHint::CreateReplacement(
545                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
546           else
547             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
548         }
549         S.Diag(IV->getLocation(), diag::note_ivar_decl);
550       }
551     }
552 }
553 
554 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
555   // Handle any placeholder expressions which made it here.
556   if (E->getType()->isPlaceholderType()) {
557     ExprResult result = CheckPlaceholderExpr(E);
558     if (result.isInvalid()) return ExprError();
559     E = result.get();
560   }
561 
562   // C++ [conv.lval]p1:
563   //   A glvalue of a non-function, non-array type T can be
564   //   converted to a prvalue.
565   if (!E->isGLValue()) return E;
566 
567   QualType T = E->getType();
568   assert(!T.isNull() && "r-value conversion on typeless expression?");
569 
570   // We don't want to throw lvalue-to-rvalue casts on top of
571   // expressions of certain types in C++.
572   if (getLangOpts().CPlusPlus &&
573       (E->getType() == Context.OverloadTy ||
574        T->isDependentType() ||
575        T->isRecordType()))
576     return E;
577 
578   // The C standard is actually really unclear on this point, and
579   // DR106 tells us what the result should be but not why.  It's
580   // generally best to say that void types just doesn't undergo
581   // lvalue-to-rvalue at all.  Note that expressions of unqualified
582   // 'void' type are never l-values, but qualified void can be.
583   if (T->isVoidType())
584     return E;
585 
586   // OpenCL usually rejects direct accesses to values of 'half' type.
587   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
588       T->isHalfType()) {
589     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
590       << 0 << T;
591     return ExprError();
592   }
593 
594   CheckForNullPointerDereference(*this, E);
595   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
596     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
597                                      &Context.Idents.get("object_getClass"),
598                                      SourceLocation(), LookupOrdinaryName);
599     if (ObjectGetClass)
600       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
601           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
602           << FixItHint::CreateReplacement(
603                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
604     else
605       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
606   }
607   else if (const ObjCIvarRefExpr *OIRE =
608             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
609     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
610 
611   // C++ [conv.lval]p1:
612   //   [...] If T is a non-class type, the type of the prvalue is the
613   //   cv-unqualified version of T. Otherwise, the type of the
614   //   rvalue is T.
615   //
616   // C99 6.3.2.1p2:
617   //   If the lvalue has qualified type, the value has the unqualified
618   //   version of the type of the lvalue; otherwise, the value has the
619   //   type of the lvalue.
620   if (T.hasQualifiers())
621     T = T.getUnqualifiedType();
622 
623   // Under the MS ABI, lock down the inheritance model now.
624   if (T->isMemberPointerType() &&
625       Context.getTargetInfo().getCXXABI().isMicrosoft())
626     (void)isCompleteType(E->getExprLoc(), T);
627 
628   UpdateMarkingForLValueToRValue(E);
629 
630   // Loading a __weak object implicitly retains the value, so we need a cleanup to
631   // balance that.
632   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
633     Cleanup.setExprNeedsCleanups(true);
634 
635   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
636                                             nullptr, VK_RValue);
637 
638   // C11 6.3.2.1p2:
639   //   ... if the lvalue has atomic type, the value has the non-atomic version
640   //   of the type of the lvalue ...
641   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
642     T = Atomic->getValueType().getUnqualifiedType();
643     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
644                                    nullptr, VK_RValue);
645   }
646 
647   return Res;
648 }
649 
650 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
651   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
652   if (Res.isInvalid())
653     return ExprError();
654   Res = DefaultLvalueConversion(Res.get());
655   if (Res.isInvalid())
656     return ExprError();
657   return Res;
658 }
659 
660 /// CallExprUnaryConversions - a special case of an unary conversion
661 /// performed on a function designator of a call expression.
662 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
663   QualType Ty = E->getType();
664   ExprResult Res = E;
665   // Only do implicit cast for a function type, but not for a pointer
666   // to function type.
667   if (Ty->isFunctionType()) {
668     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
669                             CK_FunctionToPointerDecay).get();
670     if (Res.isInvalid())
671       return ExprError();
672   }
673   Res = DefaultLvalueConversion(Res.get());
674   if (Res.isInvalid())
675     return ExprError();
676   return Res.get();
677 }
678 
679 /// UsualUnaryConversions - Performs various conversions that are common to most
680 /// operators (C99 6.3). The conversions of array and function types are
681 /// sometimes suppressed. For example, the array->pointer conversion doesn't
682 /// apply if the array is an argument to the sizeof or address (&) operators.
683 /// In these instances, this routine should *not* be called.
684 ExprResult Sema::UsualUnaryConversions(Expr *E) {
685   // First, convert to an r-value.
686   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
687   if (Res.isInvalid())
688     return ExprError();
689   E = Res.get();
690 
691   QualType Ty = E->getType();
692   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
693 
694   // Half FP have to be promoted to float unless it is natively supported
695   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
696     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
697 
698   // Try to perform integral promotions if the object has a theoretically
699   // promotable type.
700   if (Ty->isIntegralOrUnscopedEnumerationType()) {
701     // C99 6.3.1.1p2:
702     //
703     //   The following may be used in an expression wherever an int or
704     //   unsigned int may be used:
705     //     - an object or expression with an integer type whose integer
706     //       conversion rank is less than or equal to the rank of int
707     //       and unsigned int.
708     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
709     //
710     //   If an int can represent all values of the original type, the
711     //   value is converted to an int; otherwise, it is converted to an
712     //   unsigned int. These are called the integer promotions. All
713     //   other types are unchanged by the integer promotions.
714 
715     QualType PTy = Context.isPromotableBitField(E);
716     if (!PTy.isNull()) {
717       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
718       return E;
719     }
720     if (Ty->isPromotableIntegerType()) {
721       QualType PT = Context.getPromotedIntegerType(Ty);
722       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
723       return E;
724     }
725   }
726   return E;
727 }
728 
729 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
730 /// do not have a prototype. Arguments that have type float or __fp16
731 /// are promoted to double. All other argument types are converted by
732 /// UsualUnaryConversions().
733 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
734   QualType Ty = E->getType();
735   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
736 
737   ExprResult Res = UsualUnaryConversions(E);
738   if (Res.isInvalid())
739     return ExprError();
740   E = Res.get();
741 
742   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
743   // promote to double.
744   // Note that default argument promotion applies only to float (and
745   // half/fp16); it does not apply to _Float16.
746   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
747   if (BTy && (BTy->getKind() == BuiltinType::Half ||
748               BTy->getKind() == BuiltinType::Float)) {
749     if (getLangOpts().OpenCL &&
750         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
751         if (BTy->getKind() == BuiltinType::Half) {
752             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
753         }
754     } else {
755       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
756     }
757   }
758 
759   // C++ performs lvalue-to-rvalue conversion as a default argument
760   // promotion, even on class types, but note:
761   //   C++11 [conv.lval]p2:
762   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
763   //     operand or a subexpression thereof the value contained in the
764   //     referenced object is not accessed. Otherwise, if the glvalue
765   //     has a class type, the conversion copy-initializes a temporary
766   //     of type T from the glvalue and the result of the conversion
767   //     is a prvalue for the temporary.
768   // FIXME: add some way to gate this entire thing for correctness in
769   // potentially potentially evaluated contexts.
770   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
771     ExprResult Temp = PerformCopyInitialization(
772                        InitializedEntity::InitializeTemporary(E->getType()),
773                                                 E->getExprLoc(), E);
774     if (Temp.isInvalid())
775       return ExprError();
776     E = Temp.get();
777   }
778 
779   return E;
780 }
781 
782 /// Determine the degree of POD-ness for an expression.
783 /// Incomplete types are considered POD, since this check can be performed
784 /// when we're in an unevaluated context.
785 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
786   if (Ty->isIncompleteType()) {
787     // C++11 [expr.call]p7:
788     //   After these conversions, if the argument does not have arithmetic,
789     //   enumeration, pointer, pointer to member, or class type, the program
790     //   is ill-formed.
791     //
792     // Since we've already performed array-to-pointer and function-to-pointer
793     // decay, the only such type in C++ is cv void. This also handles
794     // initializer lists as variadic arguments.
795     if (Ty->isVoidType())
796       return VAK_Invalid;
797 
798     if (Ty->isObjCObjectType())
799       return VAK_Invalid;
800     return VAK_Valid;
801   }
802 
803   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
804     return VAK_Invalid;
805 
806   if (Ty.isCXX98PODType(Context))
807     return VAK_Valid;
808 
809   // C++11 [expr.call]p7:
810   //   Passing a potentially-evaluated argument of class type (Clause 9)
811   //   having a non-trivial copy constructor, a non-trivial move constructor,
812   //   or a non-trivial destructor, with no corresponding parameter,
813   //   is conditionally-supported with implementation-defined semantics.
814   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
815     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
816       if (!Record->hasNonTrivialCopyConstructor() &&
817           !Record->hasNonTrivialMoveConstructor() &&
818           !Record->hasNonTrivialDestructor())
819         return VAK_ValidInCXX11;
820 
821   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
822     return VAK_Valid;
823 
824   if (Ty->isObjCObjectType())
825     return VAK_Invalid;
826 
827   if (getLangOpts().MSVCCompat)
828     return VAK_MSVCUndefined;
829 
830   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
831   // permitted to reject them. We should consider doing so.
832   return VAK_Undefined;
833 }
834 
835 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
836   // Don't allow one to pass an Objective-C interface to a vararg.
837   const QualType &Ty = E->getType();
838   VarArgKind VAK = isValidVarArgType(Ty);
839 
840   // Complain about passing non-POD types through varargs.
841   switch (VAK) {
842   case VAK_ValidInCXX11:
843     DiagRuntimeBehavior(
844         E->getBeginLoc(), nullptr,
845         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
846     LLVM_FALLTHROUGH;
847   case VAK_Valid:
848     if (Ty->isRecordType()) {
849       // This is unlikely to be what the user intended. If the class has a
850       // 'c_str' member function, the user probably meant to call that.
851       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
852                           PDiag(diag::warn_pass_class_arg_to_vararg)
853                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
854     }
855     break;
856 
857   case VAK_Undefined:
858   case VAK_MSVCUndefined:
859     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
860                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
861                             << getLangOpts().CPlusPlus11 << Ty << CT);
862     break;
863 
864   case VAK_Invalid:
865     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
866       Diag(E->getBeginLoc(),
867            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
868           << Ty << CT;
869     else if (Ty->isObjCObjectType())
870       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
871                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
872                               << Ty << CT);
873     else
874       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
875           << isa<InitListExpr>(E) << Ty << CT;
876     break;
877   }
878 }
879 
880 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
881 /// will create a trap if the resulting type is not a POD type.
882 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
883                                                   FunctionDecl *FDecl) {
884   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
885     // Strip the unbridged-cast placeholder expression off, if applicable.
886     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
887         (CT == VariadicMethod ||
888          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
889       E = stripARCUnbridgedCast(E);
890 
891     // Otherwise, do normal placeholder checking.
892     } else {
893       ExprResult ExprRes = CheckPlaceholderExpr(E);
894       if (ExprRes.isInvalid())
895         return ExprError();
896       E = ExprRes.get();
897     }
898   }
899 
900   ExprResult ExprRes = DefaultArgumentPromotion(E);
901   if (ExprRes.isInvalid())
902     return ExprError();
903   E = ExprRes.get();
904 
905   // Diagnostics regarding non-POD argument types are
906   // emitted along with format string checking in Sema::CheckFunctionCall().
907   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
908     // Turn this into a trap.
909     CXXScopeSpec SS;
910     SourceLocation TemplateKWLoc;
911     UnqualifiedId Name;
912     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
913                        E->getBeginLoc());
914     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
915                                           Name, true, false);
916     if (TrapFn.isInvalid())
917       return ExprError();
918 
919     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
920                                     None, E->getEndLoc());
921     if (Call.isInvalid())
922       return ExprError();
923 
924     ExprResult Comma =
925         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
926     if (Comma.isInvalid())
927       return ExprError();
928     return Comma.get();
929   }
930 
931   if (!getLangOpts().CPlusPlus &&
932       RequireCompleteType(E->getExprLoc(), E->getType(),
933                           diag::err_call_incomplete_argument))
934     return ExprError();
935 
936   return E;
937 }
938 
939 /// Converts an integer to complex float type.  Helper function of
940 /// UsualArithmeticConversions()
941 ///
942 /// \return false if the integer expression is an integer type and is
943 /// successfully converted to the complex type.
944 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
945                                                   ExprResult &ComplexExpr,
946                                                   QualType IntTy,
947                                                   QualType ComplexTy,
948                                                   bool SkipCast) {
949   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
950   if (SkipCast) return false;
951   if (IntTy->isIntegerType()) {
952     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
953     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
954     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
955                                   CK_FloatingRealToComplex);
956   } else {
957     assert(IntTy->isComplexIntegerType());
958     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
959                                   CK_IntegralComplexToFloatingComplex);
960   }
961   return false;
962 }
963 
964 /// Handle arithmetic conversion with complex types.  Helper function of
965 /// UsualArithmeticConversions()
966 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
967                                              ExprResult &RHS, QualType LHSType,
968                                              QualType RHSType,
969                                              bool IsCompAssign) {
970   // if we have an integer operand, the result is the complex type.
971   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
972                                              /*skipCast*/false))
973     return LHSType;
974   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
975                                              /*skipCast*/IsCompAssign))
976     return RHSType;
977 
978   // This handles complex/complex, complex/float, or float/complex.
979   // When both operands are complex, the shorter operand is converted to the
980   // type of the longer, and that is the type of the result. This corresponds
981   // to what is done when combining two real floating-point operands.
982   // The fun begins when size promotion occur across type domains.
983   // From H&S 6.3.4: When one operand is complex and the other is a real
984   // floating-point type, the less precise type is converted, within it's
985   // real or complex domain, to the precision of the other type. For example,
986   // when combining a "long double" with a "double _Complex", the
987   // "double _Complex" is promoted to "long double _Complex".
988 
989   // Compute the rank of the two types, regardless of whether they are complex.
990   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
991 
992   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
993   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
994   QualType LHSElementType =
995       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
996   QualType RHSElementType =
997       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
998 
999   QualType ResultType = S.Context.getComplexType(LHSElementType);
1000   if (Order < 0) {
1001     // Promote the precision of the LHS if not an assignment.
1002     ResultType = S.Context.getComplexType(RHSElementType);
1003     if (!IsCompAssign) {
1004       if (LHSComplexType)
1005         LHS =
1006             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1007       else
1008         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1009     }
1010   } else if (Order > 0) {
1011     // Promote the precision of the RHS.
1012     if (RHSComplexType)
1013       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1014     else
1015       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1016   }
1017   return ResultType;
1018 }
1019 
1020 /// Handle arithmetic conversion from integer to float.  Helper function
1021 /// of UsualArithmeticConversions()
1022 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1023                                            ExprResult &IntExpr,
1024                                            QualType FloatTy, QualType IntTy,
1025                                            bool ConvertFloat, bool ConvertInt) {
1026   if (IntTy->isIntegerType()) {
1027     if (ConvertInt)
1028       // Convert intExpr to the lhs floating point type.
1029       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1030                                     CK_IntegralToFloating);
1031     return FloatTy;
1032   }
1033 
1034   // Convert both sides to the appropriate complex float.
1035   assert(IntTy->isComplexIntegerType());
1036   QualType result = S.Context.getComplexType(FloatTy);
1037 
1038   // _Complex int -> _Complex float
1039   if (ConvertInt)
1040     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1041                                   CK_IntegralComplexToFloatingComplex);
1042 
1043   // float -> _Complex float
1044   if (ConvertFloat)
1045     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1046                                     CK_FloatingRealToComplex);
1047 
1048   return result;
1049 }
1050 
1051 /// Handle arithmethic conversion with floating point types.  Helper
1052 /// function of UsualArithmeticConversions()
1053 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1054                                       ExprResult &RHS, QualType LHSType,
1055                                       QualType RHSType, bool IsCompAssign) {
1056   bool LHSFloat = LHSType->isRealFloatingType();
1057   bool RHSFloat = RHSType->isRealFloatingType();
1058 
1059   // If we have two real floating types, convert the smaller operand
1060   // to the bigger result.
1061   if (LHSFloat && RHSFloat) {
1062     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1063     if (order > 0) {
1064       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1065       return LHSType;
1066     }
1067 
1068     assert(order < 0 && "illegal float comparison");
1069     if (!IsCompAssign)
1070       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1071     return RHSType;
1072   }
1073 
1074   if (LHSFloat) {
1075     // Half FP has to be promoted to float unless it is natively supported
1076     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1077       LHSType = S.Context.FloatTy;
1078 
1079     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1080                                       /*convertFloat=*/!IsCompAssign,
1081                                       /*convertInt=*/ true);
1082   }
1083   assert(RHSFloat);
1084   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1085                                     /*convertInt=*/ true,
1086                                     /*convertFloat=*/!IsCompAssign);
1087 }
1088 
1089 /// Diagnose attempts to convert between __float128 and long double if
1090 /// there is no support for such conversion. Helper function of
1091 /// UsualArithmeticConversions().
1092 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1093                                       QualType RHSType) {
1094   /*  No issue converting if at least one of the types is not a floating point
1095       type or the two types have the same rank.
1096   */
1097   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1098       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1099     return false;
1100 
1101   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1102          "The remaining types must be floating point types.");
1103 
1104   auto *LHSComplex = LHSType->getAs<ComplexType>();
1105   auto *RHSComplex = RHSType->getAs<ComplexType>();
1106 
1107   QualType LHSElemType = LHSComplex ?
1108     LHSComplex->getElementType() : LHSType;
1109   QualType RHSElemType = RHSComplex ?
1110     RHSComplex->getElementType() : RHSType;
1111 
1112   // No issue if the two types have the same representation
1113   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1114       &S.Context.getFloatTypeSemantics(RHSElemType))
1115     return false;
1116 
1117   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1118                                 RHSElemType == S.Context.LongDoubleTy);
1119   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1120                             RHSElemType == S.Context.Float128Ty);
1121 
1122   // We've handled the situation where __float128 and long double have the same
1123   // representation. We allow all conversions for all possible long double types
1124   // except PPC's double double.
1125   return Float128AndLongDouble &&
1126     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1127      &llvm::APFloat::PPCDoubleDouble());
1128 }
1129 
1130 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1131 
1132 namespace {
1133 /// These helper callbacks are placed in an anonymous namespace to
1134 /// permit their use as function template parameters.
1135 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1136   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1137 }
1138 
1139 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1140   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1141                              CK_IntegralComplexCast);
1142 }
1143 }
1144 
1145 /// Handle integer arithmetic conversions.  Helper function of
1146 /// UsualArithmeticConversions()
1147 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1148 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1149                                         ExprResult &RHS, QualType LHSType,
1150                                         QualType RHSType, bool IsCompAssign) {
1151   // The rules for this case are in C99 6.3.1.8
1152   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1153   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1154   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1155   if (LHSSigned == RHSSigned) {
1156     // Same signedness; use the higher-ranked type
1157     if (order >= 0) {
1158       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159       return LHSType;
1160     } else if (!IsCompAssign)
1161       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162     return RHSType;
1163   } else if (order != (LHSSigned ? 1 : -1)) {
1164     // The unsigned type has greater than or equal rank to the
1165     // signed type, so use the unsigned type
1166     if (RHSSigned) {
1167       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1168       return LHSType;
1169     } else if (!IsCompAssign)
1170       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1171     return RHSType;
1172   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1173     // The two types are different widths; if we are here, that
1174     // means the signed type is larger than the unsigned type, so
1175     // use the signed type.
1176     if (LHSSigned) {
1177       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1178       return LHSType;
1179     } else if (!IsCompAssign)
1180       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1181     return RHSType;
1182   } else {
1183     // The signed type is higher-ranked than the unsigned type,
1184     // but isn't actually any bigger (like unsigned int and long
1185     // on most 32-bit systems).  Use the unsigned type corresponding
1186     // to the signed type.
1187     QualType result =
1188       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1189     RHS = (*doRHSCast)(S, RHS.get(), result);
1190     if (!IsCompAssign)
1191       LHS = (*doLHSCast)(S, LHS.get(), result);
1192     return result;
1193   }
1194 }
1195 
1196 /// Handle conversions with GCC complex int extension.  Helper function
1197 /// of UsualArithmeticConversions()
1198 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1199                                            ExprResult &RHS, QualType LHSType,
1200                                            QualType RHSType,
1201                                            bool IsCompAssign) {
1202   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1203   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1204 
1205   if (LHSComplexInt && RHSComplexInt) {
1206     QualType LHSEltType = LHSComplexInt->getElementType();
1207     QualType RHSEltType = RHSComplexInt->getElementType();
1208     QualType ScalarType =
1209       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1210         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1211 
1212     return S.Context.getComplexType(ScalarType);
1213   }
1214 
1215   if (LHSComplexInt) {
1216     QualType LHSEltType = LHSComplexInt->getElementType();
1217     QualType ScalarType =
1218       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1219         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1220     QualType ComplexType = S.Context.getComplexType(ScalarType);
1221     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1222                               CK_IntegralRealToComplex);
1223 
1224     return ComplexType;
1225   }
1226 
1227   assert(RHSComplexInt);
1228 
1229   QualType RHSEltType = RHSComplexInt->getElementType();
1230   QualType ScalarType =
1231     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1232       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1233   QualType ComplexType = S.Context.getComplexType(ScalarType);
1234 
1235   if (!IsCompAssign)
1236     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1237                               CK_IntegralRealToComplex);
1238   return ComplexType;
1239 }
1240 
1241 /// Return the rank of a given fixed point or integer type. The value itself
1242 /// doesn't matter, but the values must be increasing with proper increasing
1243 /// rank as described in N1169 4.1.1.
1244 static unsigned GetFixedPointRank(QualType Ty) {
1245   const auto *BTy = Ty->getAs<BuiltinType>();
1246   assert(BTy && "Expected a builtin type.");
1247 
1248   switch (BTy->getKind()) {
1249   case BuiltinType::ShortFract:
1250   case BuiltinType::UShortFract:
1251   case BuiltinType::SatShortFract:
1252   case BuiltinType::SatUShortFract:
1253     return 1;
1254   case BuiltinType::Fract:
1255   case BuiltinType::UFract:
1256   case BuiltinType::SatFract:
1257   case BuiltinType::SatUFract:
1258     return 2;
1259   case BuiltinType::LongFract:
1260   case BuiltinType::ULongFract:
1261   case BuiltinType::SatLongFract:
1262   case BuiltinType::SatULongFract:
1263     return 3;
1264   case BuiltinType::ShortAccum:
1265   case BuiltinType::UShortAccum:
1266   case BuiltinType::SatShortAccum:
1267   case BuiltinType::SatUShortAccum:
1268     return 4;
1269   case BuiltinType::Accum:
1270   case BuiltinType::UAccum:
1271   case BuiltinType::SatAccum:
1272   case BuiltinType::SatUAccum:
1273     return 5;
1274   case BuiltinType::LongAccum:
1275   case BuiltinType::ULongAccum:
1276   case BuiltinType::SatLongAccum:
1277   case BuiltinType::SatULongAccum:
1278     return 6;
1279   default:
1280     if (BTy->isInteger())
1281       return 0;
1282     llvm_unreachable("Unexpected fixed point or integer type");
1283   }
1284 }
1285 
1286 /// handleFixedPointConversion - Fixed point operations between fixed
1287 /// point types and integers or other fixed point types do not fall under
1288 /// usual arithmetic conversion since these conversions could result in loss
1289 /// of precsision (N1169 4.1.4). These operations should be calculated with
1290 /// the full precision of their result type (N1169 4.1.6.2.1).
1291 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1292                                            QualType RHSTy) {
1293   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1294          "Expected at least one of the operands to be a fixed point type");
1295   assert((LHSTy->isFixedPointOrIntegerType() ||
1296           RHSTy->isFixedPointOrIntegerType()) &&
1297          "Special fixed point arithmetic operation conversions are only "
1298          "applied to ints or other fixed point types");
1299 
1300   // If one operand has signed fixed-point type and the other operand has
1301   // unsigned fixed-point type, then the unsigned fixed-point operand is
1302   // converted to its corresponding signed fixed-point type and the resulting
1303   // type is the type of the converted operand.
1304   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1305     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1306   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1307     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1308 
1309   // The result type is the type with the highest rank, whereby a fixed-point
1310   // conversion rank is always greater than an integer conversion rank; if the
1311   // type of either of the operands is a saturating fixedpoint type, the result
1312   // type shall be the saturating fixed-point type corresponding to the type
1313   // with the highest rank; the resulting value is converted (taking into
1314   // account rounding and overflow) to the precision of the resulting type.
1315   // Same ranks between signed and unsigned types are resolved earlier, so both
1316   // types are either signed or both unsigned at this point.
1317   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1318   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1319 
1320   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1321 
1322   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1323     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1324 
1325   return ResultTy;
1326 }
1327 
1328 /// UsualArithmeticConversions - Performs various conversions that are common to
1329 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1330 /// routine returns the first non-arithmetic type found. The client is
1331 /// responsible for emitting appropriate error diagnostics.
1332 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1333                                           bool IsCompAssign) {
1334   if (!IsCompAssign) {
1335     LHS = UsualUnaryConversions(LHS.get());
1336     if (LHS.isInvalid())
1337       return QualType();
1338   }
1339 
1340   RHS = UsualUnaryConversions(RHS.get());
1341   if (RHS.isInvalid())
1342     return QualType();
1343 
1344   // For conversion purposes, we ignore any qualifiers.
1345   // For example, "const float" and "float" are equivalent.
1346   QualType LHSType =
1347     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1348   QualType RHSType =
1349     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1350 
1351   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1352   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1353     LHSType = AtomicLHS->getValueType();
1354 
1355   // If both types are identical, no conversion is needed.
1356   if (LHSType == RHSType)
1357     return LHSType;
1358 
1359   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1360   // The caller can deal with this (e.g. pointer + int).
1361   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1362     return QualType();
1363 
1364   // Apply unary and bitfield promotions to the LHS's type.
1365   QualType LHSUnpromotedType = LHSType;
1366   if (LHSType->isPromotableIntegerType())
1367     LHSType = Context.getPromotedIntegerType(LHSType);
1368   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1369   if (!LHSBitfieldPromoteTy.isNull())
1370     LHSType = LHSBitfieldPromoteTy;
1371   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1372     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1373 
1374   // If both types are identical, no conversion is needed.
1375   if (LHSType == RHSType)
1376     return LHSType;
1377 
1378   // At this point, we have two different arithmetic types.
1379 
1380   // Diagnose attempts to convert between __float128 and long double where
1381   // such conversions currently can't be handled.
1382   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1383     return QualType();
1384 
1385   // Handle complex types first (C99 6.3.1.8p1).
1386   if (LHSType->isComplexType() || RHSType->isComplexType())
1387     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1388                                         IsCompAssign);
1389 
1390   // Now handle "real" floating types (i.e. float, double, long double).
1391   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1392     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1393                                  IsCompAssign);
1394 
1395   // Handle GCC complex int extension.
1396   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1397     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1398                                       IsCompAssign);
1399 
1400   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1401     return handleFixedPointConversion(*this, LHSType, RHSType);
1402 
1403   // Finally, we have two differing integer types.
1404   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1405            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1406 }
1407 
1408 //===----------------------------------------------------------------------===//
1409 //  Semantic Analysis for various Expression Types
1410 //===----------------------------------------------------------------------===//
1411 
1412 
1413 ExprResult
1414 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1415                                 SourceLocation DefaultLoc,
1416                                 SourceLocation RParenLoc,
1417                                 Expr *ControllingExpr,
1418                                 ArrayRef<ParsedType> ArgTypes,
1419                                 ArrayRef<Expr *> ArgExprs) {
1420   unsigned NumAssocs = ArgTypes.size();
1421   assert(NumAssocs == ArgExprs.size());
1422 
1423   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1424   for (unsigned i = 0; i < NumAssocs; ++i) {
1425     if (ArgTypes[i])
1426       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1427     else
1428       Types[i] = nullptr;
1429   }
1430 
1431   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1432                                              ControllingExpr,
1433                                              llvm::makeArrayRef(Types, NumAssocs),
1434                                              ArgExprs);
1435   delete [] Types;
1436   return ER;
1437 }
1438 
1439 ExprResult
1440 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1441                                  SourceLocation DefaultLoc,
1442                                  SourceLocation RParenLoc,
1443                                  Expr *ControllingExpr,
1444                                  ArrayRef<TypeSourceInfo *> Types,
1445                                  ArrayRef<Expr *> Exprs) {
1446   unsigned NumAssocs = Types.size();
1447   assert(NumAssocs == Exprs.size());
1448 
1449   // Decay and strip qualifiers for the controlling expression type, and handle
1450   // placeholder type replacement. See committee discussion from WG14 DR423.
1451   {
1452     EnterExpressionEvaluationContext Unevaluated(
1453         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1454     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1455     if (R.isInvalid())
1456       return ExprError();
1457     ControllingExpr = R.get();
1458   }
1459 
1460   // The controlling expression is an unevaluated operand, so side effects are
1461   // likely unintended.
1462   if (!inTemplateInstantiation() &&
1463       ControllingExpr->HasSideEffects(Context, false))
1464     Diag(ControllingExpr->getExprLoc(),
1465          diag::warn_side_effects_unevaluated_context);
1466 
1467   bool TypeErrorFound = false,
1468        IsResultDependent = ControllingExpr->isTypeDependent(),
1469        ContainsUnexpandedParameterPack
1470          = ControllingExpr->containsUnexpandedParameterPack();
1471 
1472   for (unsigned i = 0; i < NumAssocs; ++i) {
1473     if (Exprs[i]->containsUnexpandedParameterPack())
1474       ContainsUnexpandedParameterPack = true;
1475 
1476     if (Types[i]) {
1477       if (Types[i]->getType()->containsUnexpandedParameterPack())
1478         ContainsUnexpandedParameterPack = true;
1479 
1480       if (Types[i]->getType()->isDependentType()) {
1481         IsResultDependent = true;
1482       } else {
1483         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1484         // complete object type other than a variably modified type."
1485         unsigned D = 0;
1486         if (Types[i]->getType()->isIncompleteType())
1487           D = diag::err_assoc_type_incomplete;
1488         else if (!Types[i]->getType()->isObjectType())
1489           D = diag::err_assoc_type_nonobject;
1490         else if (Types[i]->getType()->isVariablyModifiedType())
1491           D = diag::err_assoc_type_variably_modified;
1492 
1493         if (D != 0) {
1494           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1495             << Types[i]->getTypeLoc().getSourceRange()
1496             << Types[i]->getType();
1497           TypeErrorFound = true;
1498         }
1499 
1500         // C11 6.5.1.1p2 "No two generic associations in the same generic
1501         // selection shall specify compatible types."
1502         for (unsigned j = i+1; j < NumAssocs; ++j)
1503           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1504               Context.typesAreCompatible(Types[i]->getType(),
1505                                          Types[j]->getType())) {
1506             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1507                  diag::err_assoc_compatible_types)
1508               << Types[j]->getTypeLoc().getSourceRange()
1509               << Types[j]->getType()
1510               << Types[i]->getType();
1511             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1512                  diag::note_compat_assoc)
1513               << Types[i]->getTypeLoc().getSourceRange()
1514               << Types[i]->getType();
1515             TypeErrorFound = true;
1516           }
1517       }
1518     }
1519   }
1520   if (TypeErrorFound)
1521     return ExprError();
1522 
1523   // If we determined that the generic selection is result-dependent, don't
1524   // try to compute the result expression.
1525   if (IsResultDependent)
1526     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1527                                         Exprs, DefaultLoc, RParenLoc,
1528                                         ContainsUnexpandedParameterPack);
1529 
1530   SmallVector<unsigned, 1> CompatIndices;
1531   unsigned DefaultIndex = -1U;
1532   for (unsigned i = 0; i < NumAssocs; ++i) {
1533     if (!Types[i])
1534       DefaultIndex = i;
1535     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1536                                         Types[i]->getType()))
1537       CompatIndices.push_back(i);
1538   }
1539 
1540   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1541   // type compatible with at most one of the types named in its generic
1542   // association list."
1543   if (CompatIndices.size() > 1) {
1544     // We strip parens here because the controlling expression is typically
1545     // parenthesized in macro definitions.
1546     ControllingExpr = ControllingExpr->IgnoreParens();
1547     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1548         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1549         << (unsigned)CompatIndices.size();
1550     for (unsigned I : CompatIndices) {
1551       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1552            diag::note_compat_assoc)
1553         << Types[I]->getTypeLoc().getSourceRange()
1554         << Types[I]->getType();
1555     }
1556     return ExprError();
1557   }
1558 
1559   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1560   // its controlling expression shall have type compatible with exactly one of
1561   // the types named in its generic association list."
1562   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1563     // We strip parens here because the controlling expression is typically
1564     // parenthesized in macro definitions.
1565     ControllingExpr = ControllingExpr->IgnoreParens();
1566     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1567         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1568     return ExprError();
1569   }
1570 
1571   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1572   // type name that is compatible with the type of the controlling expression,
1573   // then the result expression of the generic selection is the expression
1574   // in that generic association. Otherwise, the result expression of the
1575   // generic selection is the expression in the default generic association."
1576   unsigned ResultIndex =
1577     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1578 
1579   return GenericSelectionExpr::Create(
1580       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1581       ContainsUnexpandedParameterPack, ResultIndex);
1582 }
1583 
1584 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1585 /// location of the token and the offset of the ud-suffix within it.
1586 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1587                                      unsigned Offset) {
1588   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1589                                         S.getLangOpts());
1590 }
1591 
1592 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1593 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1594 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1595                                                  IdentifierInfo *UDSuffix,
1596                                                  SourceLocation UDSuffixLoc,
1597                                                  ArrayRef<Expr*> Args,
1598                                                  SourceLocation LitEndLoc) {
1599   assert(Args.size() <= 2 && "too many arguments for literal operator");
1600 
1601   QualType ArgTy[2];
1602   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1603     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1604     if (ArgTy[ArgIdx]->isArrayType())
1605       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1606   }
1607 
1608   DeclarationName OpName =
1609     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1610   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1611   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1612 
1613   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1614   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1615                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1616                               /*AllowStringTemplate*/ false,
1617                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1618     return ExprError();
1619 
1620   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1621 }
1622 
1623 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1624 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1625 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1626 /// multiple tokens.  However, the common case is that StringToks points to one
1627 /// string.
1628 ///
1629 ExprResult
1630 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1631   assert(!StringToks.empty() && "Must have at least one string!");
1632 
1633   StringLiteralParser Literal(StringToks, PP);
1634   if (Literal.hadError)
1635     return ExprError();
1636 
1637   SmallVector<SourceLocation, 4> StringTokLocs;
1638   for (const Token &Tok : StringToks)
1639     StringTokLocs.push_back(Tok.getLocation());
1640 
1641   QualType CharTy = Context.CharTy;
1642   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1643   if (Literal.isWide()) {
1644     CharTy = Context.getWideCharType();
1645     Kind = StringLiteral::Wide;
1646   } else if (Literal.isUTF8()) {
1647     if (getLangOpts().Char8)
1648       CharTy = Context.Char8Ty;
1649     Kind = StringLiteral::UTF8;
1650   } else if (Literal.isUTF16()) {
1651     CharTy = Context.Char16Ty;
1652     Kind = StringLiteral::UTF16;
1653   } else if (Literal.isUTF32()) {
1654     CharTy = Context.Char32Ty;
1655     Kind = StringLiteral::UTF32;
1656   } else if (Literal.isPascal()) {
1657     CharTy = Context.UnsignedCharTy;
1658   }
1659 
1660   // Warn on initializing an array of char from a u8 string literal; this
1661   // becomes ill-formed in C++2a.
1662   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1663       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1664     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1665 
1666     // Create removals for all 'u8' prefixes in the string literal(s). This
1667     // ensures C++2a compatibility (but may change the program behavior when
1668     // built by non-Clang compilers for which the execution character set is
1669     // not always UTF-8).
1670     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1671     SourceLocation RemovalDiagLoc;
1672     for (const Token &Tok : StringToks) {
1673       if (Tok.getKind() == tok::utf8_string_literal) {
1674         if (RemovalDiagLoc.isInvalid())
1675           RemovalDiagLoc = Tok.getLocation();
1676         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1677             Tok.getLocation(),
1678             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1679                                            getSourceManager(), getLangOpts())));
1680       }
1681     }
1682     Diag(RemovalDiagLoc, RemovalDiag);
1683   }
1684 
1685 
1686   QualType CharTyConst = CharTy;
1687   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1688   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1689     CharTyConst.addConst();
1690 
1691   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1692 
1693   // Get an array type for the string, according to C99 6.4.5.  This includes
1694   // the nul terminator character as well as the string length for pascal
1695   // strings.
1696   QualType StrTy = Context.getConstantArrayType(
1697       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1698       ArrayType::Normal, 0);
1699 
1700   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1701   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1702                                              Kind, Literal.Pascal, StrTy,
1703                                              &StringTokLocs[0],
1704                                              StringTokLocs.size());
1705   if (Literal.getUDSuffix().empty())
1706     return Lit;
1707 
1708   // We're building a user-defined literal.
1709   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1710   SourceLocation UDSuffixLoc =
1711     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1712                    Literal.getUDSuffixOffset());
1713 
1714   // Make sure we're allowed user-defined literals here.
1715   if (!UDLScope)
1716     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1717 
1718   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1719   //   operator "" X (str, len)
1720   QualType SizeType = Context.getSizeType();
1721 
1722   DeclarationName OpName =
1723     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1724   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1725   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1726 
1727   QualType ArgTy[] = {
1728     Context.getArrayDecayedType(StrTy), SizeType
1729   };
1730 
1731   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1732   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1733                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1734                                 /*AllowStringTemplate*/ true,
1735                                 /*DiagnoseMissing*/ true)) {
1736 
1737   case LOLR_Cooked: {
1738     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1739     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1740                                                     StringTokLocs[0]);
1741     Expr *Args[] = { Lit, LenArg };
1742 
1743     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1744   }
1745 
1746   case LOLR_StringTemplate: {
1747     TemplateArgumentListInfo ExplicitArgs;
1748 
1749     unsigned CharBits = Context.getIntWidth(CharTy);
1750     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1751     llvm::APSInt Value(CharBits, CharIsUnsigned);
1752 
1753     TemplateArgument TypeArg(CharTy);
1754     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1755     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1756 
1757     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1758       Value = Lit->getCodeUnit(I);
1759       TemplateArgument Arg(Context, Value, CharTy);
1760       TemplateArgumentLocInfo ArgInfo;
1761       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1762     }
1763     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1764                                     &ExplicitArgs);
1765   }
1766   case LOLR_Raw:
1767   case LOLR_Template:
1768   case LOLR_ErrorNoDiagnostic:
1769     llvm_unreachable("unexpected literal operator lookup result");
1770   case LOLR_Error:
1771     return ExprError();
1772   }
1773   llvm_unreachable("unexpected literal operator lookup result");
1774 }
1775 
1776 ExprResult
1777 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1778                        SourceLocation Loc,
1779                        const CXXScopeSpec *SS) {
1780   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1781   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1782 }
1783 
1784 /// BuildDeclRefExpr - Build an expression that references a
1785 /// declaration that does not require a closure capture.
1786 ExprResult
1787 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1788                        const DeclarationNameInfo &NameInfo,
1789                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1790                        const TemplateArgumentListInfo *TemplateArgs) {
1791   bool RefersToCapturedVariable =
1792       isa<VarDecl>(D) &&
1793       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1794 
1795   DeclRefExpr *E;
1796   if (isa<VarTemplateSpecializationDecl>(D)) {
1797     VarTemplateSpecializationDecl *VarSpec =
1798         cast<VarTemplateSpecializationDecl>(D);
1799 
1800     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1801                                         : NestedNameSpecifierLoc(),
1802                             VarSpec->getTemplateKeywordLoc(), D,
1803                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1804                             FoundD, TemplateArgs);
1805   } else {
1806     assert(!TemplateArgs && "No template arguments for non-variable"
1807                             " template specialization references");
1808     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1809                                         : NestedNameSpecifierLoc(),
1810                             SourceLocation(), D, RefersToCapturedVariable,
1811                             NameInfo, Ty, VK, FoundD);
1812   }
1813 
1814   MarkDeclRefReferenced(E);
1815 
1816   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1817       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1818       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1819     getCurFunction()->recordUseOfWeak(E);
1820 
1821   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1822   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1823     FD = IFD->getAnonField();
1824   if (FD) {
1825     UnusedPrivateFields.remove(FD);
1826     // Just in case we're building an illegal pointer-to-member.
1827     if (FD->isBitField())
1828       E->setObjectKind(OK_BitField);
1829   }
1830 
1831   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1832   // designates a bit-field.
1833   if (auto *BD = dyn_cast<BindingDecl>(D))
1834     if (auto *BE = BD->getBinding())
1835       E->setObjectKind(BE->getObjectKind());
1836 
1837   return E;
1838 }
1839 
1840 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1841 /// possibly a list of template arguments.
1842 ///
1843 /// If this produces template arguments, it is permitted to call
1844 /// DecomposeTemplateName.
1845 ///
1846 /// This actually loses a lot of source location information for
1847 /// non-standard name kinds; we should consider preserving that in
1848 /// some way.
1849 void
1850 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1851                              TemplateArgumentListInfo &Buffer,
1852                              DeclarationNameInfo &NameInfo,
1853                              const TemplateArgumentListInfo *&TemplateArgs) {
1854   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1855     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1856     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1857 
1858     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1859                                        Id.TemplateId->NumArgs);
1860     translateTemplateArguments(TemplateArgsPtr, Buffer);
1861 
1862     TemplateName TName = Id.TemplateId->Template.get();
1863     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1864     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1865     TemplateArgs = &Buffer;
1866   } else {
1867     NameInfo = GetNameFromUnqualifiedId(Id);
1868     TemplateArgs = nullptr;
1869   }
1870 }
1871 
1872 static void emitEmptyLookupTypoDiagnostic(
1873     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1874     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1875     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1876   DeclContext *Ctx =
1877       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1878   if (!TC) {
1879     // Emit a special diagnostic for failed member lookups.
1880     // FIXME: computing the declaration context might fail here (?)
1881     if (Ctx)
1882       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1883                                                  << SS.getRange();
1884     else
1885       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1886     return;
1887   }
1888 
1889   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1890   bool DroppedSpecifier =
1891       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1892   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1893                         ? diag::note_implicit_param_decl
1894                         : diag::note_previous_decl;
1895   if (!Ctx)
1896     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1897                          SemaRef.PDiag(NoteID));
1898   else
1899     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1900                                  << Typo << Ctx << DroppedSpecifier
1901                                  << SS.getRange(),
1902                          SemaRef.PDiag(NoteID));
1903 }
1904 
1905 /// Diagnose an empty lookup.
1906 ///
1907 /// \return false if new lookup candidates were found
1908 bool
1909 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1910                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1911                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1912                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1913   DeclarationName Name = R.getLookupName();
1914 
1915   unsigned diagnostic = diag::err_undeclared_var_use;
1916   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1917   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1918       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1919       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1920     diagnostic = diag::err_undeclared_use;
1921     diagnostic_suggest = diag::err_undeclared_use_suggest;
1922   }
1923 
1924   // If the original lookup was an unqualified lookup, fake an
1925   // unqualified lookup.  This is useful when (for example) the
1926   // original lookup would not have found something because it was a
1927   // dependent name.
1928   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1929   while (DC) {
1930     if (isa<CXXRecordDecl>(DC)) {
1931       LookupQualifiedName(R, DC);
1932 
1933       if (!R.empty()) {
1934         // Don't give errors about ambiguities in this lookup.
1935         R.suppressDiagnostics();
1936 
1937         // During a default argument instantiation the CurContext points
1938         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1939         // function parameter list, hence add an explicit check.
1940         bool isDefaultArgument =
1941             !CodeSynthesisContexts.empty() &&
1942             CodeSynthesisContexts.back().Kind ==
1943                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1944         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1945         bool isInstance = CurMethod &&
1946                           CurMethod->isInstance() &&
1947                           DC == CurMethod->getParent() && !isDefaultArgument;
1948 
1949         // Give a code modification hint to insert 'this->'.
1950         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1951         // Actually quite difficult!
1952         if (getLangOpts().MSVCCompat)
1953           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1954         if (isInstance) {
1955           Diag(R.getNameLoc(), diagnostic) << Name
1956             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1957           CheckCXXThisCapture(R.getNameLoc());
1958         } else {
1959           Diag(R.getNameLoc(), diagnostic) << Name;
1960         }
1961 
1962         // Do we really want to note all of these?
1963         for (NamedDecl *D : R)
1964           Diag(D->getLocation(), diag::note_dependent_var_use);
1965 
1966         // Return true if we are inside a default argument instantiation
1967         // and the found name refers to an instance member function, otherwise
1968         // the function calling DiagnoseEmptyLookup will try to create an
1969         // implicit member call and this is wrong for default argument.
1970         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1971           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1972           return true;
1973         }
1974 
1975         // Tell the callee to try to recover.
1976         return false;
1977       }
1978 
1979       R.clear();
1980     }
1981 
1982     // In Microsoft mode, if we are performing lookup from within a friend
1983     // function definition declared at class scope then we must set
1984     // DC to the lexical parent to be able to search into the parent
1985     // class.
1986     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1987         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1988         DC->getLexicalParent()->isRecord())
1989       DC = DC->getLexicalParent();
1990     else
1991       DC = DC->getParent();
1992   }
1993 
1994   // We didn't find anything, so try to correct for a typo.
1995   TypoCorrection Corrected;
1996   if (S && Out) {
1997     SourceLocation TypoLoc = R.getNameLoc();
1998     assert(!ExplicitTemplateArgs &&
1999            "Diagnosing an empty lookup with explicit template args!");
2000     *Out = CorrectTypoDelayed(
2001         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
2002         [=](const TypoCorrection &TC) {
2003           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2004                                         diagnostic, diagnostic_suggest);
2005         },
2006         nullptr, CTK_ErrorRecovery);
2007     if (*Out)
2008       return true;
2009   } else if (S && (Corrected =
2010                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
2011                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
2012     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2013     bool DroppedSpecifier =
2014         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2015     R.setLookupName(Corrected.getCorrection());
2016 
2017     bool AcceptableWithRecovery = false;
2018     bool AcceptableWithoutRecovery = false;
2019     NamedDecl *ND = Corrected.getFoundDecl();
2020     if (ND) {
2021       if (Corrected.isOverloaded()) {
2022         OverloadCandidateSet OCS(R.getNameLoc(),
2023                                  OverloadCandidateSet::CSK_Normal);
2024         OverloadCandidateSet::iterator Best;
2025         for (NamedDecl *CD : Corrected) {
2026           if (FunctionTemplateDecl *FTD =
2027                    dyn_cast<FunctionTemplateDecl>(CD))
2028             AddTemplateOverloadCandidate(
2029                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2030                 Args, OCS);
2031           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2032             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2033               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2034                                    Args, OCS);
2035         }
2036         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2037         case OR_Success:
2038           ND = Best->FoundDecl;
2039           Corrected.setCorrectionDecl(ND);
2040           break;
2041         default:
2042           // FIXME: Arbitrarily pick the first declaration for the note.
2043           Corrected.setCorrectionDecl(ND);
2044           break;
2045         }
2046       }
2047       R.addDecl(ND);
2048       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2049         CXXRecordDecl *Record = nullptr;
2050         if (Corrected.getCorrectionSpecifier()) {
2051           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2052           Record = Ty->getAsCXXRecordDecl();
2053         }
2054         if (!Record)
2055           Record = cast<CXXRecordDecl>(
2056               ND->getDeclContext()->getRedeclContext());
2057         R.setNamingClass(Record);
2058       }
2059 
2060       auto *UnderlyingND = ND->getUnderlyingDecl();
2061       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2062                                isa<FunctionTemplateDecl>(UnderlyingND);
2063       // FIXME: If we ended up with a typo for a type name or
2064       // Objective-C class name, we're in trouble because the parser
2065       // is in the wrong place to recover. Suggest the typo
2066       // correction, but don't make it a fix-it since we're not going
2067       // to recover well anyway.
2068       AcceptableWithoutRecovery =
2069           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2070     } else {
2071       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2072       // because we aren't able to recover.
2073       AcceptableWithoutRecovery = true;
2074     }
2075 
2076     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2077       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2078                             ? diag::note_implicit_param_decl
2079                             : diag::note_previous_decl;
2080       if (SS.isEmpty())
2081         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2082                      PDiag(NoteID), AcceptableWithRecovery);
2083       else
2084         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2085                                   << Name << computeDeclContext(SS, false)
2086                                   << DroppedSpecifier << SS.getRange(),
2087                      PDiag(NoteID), AcceptableWithRecovery);
2088 
2089       // Tell the callee whether to try to recover.
2090       return !AcceptableWithRecovery;
2091     }
2092   }
2093   R.clear();
2094 
2095   // Emit a special diagnostic for failed member lookups.
2096   // FIXME: computing the declaration context might fail here (?)
2097   if (!SS.isEmpty()) {
2098     Diag(R.getNameLoc(), diag::err_no_member)
2099       << Name << computeDeclContext(SS, false)
2100       << SS.getRange();
2101     return true;
2102   }
2103 
2104   // Give up, we can't recover.
2105   Diag(R.getNameLoc(), diagnostic) << Name;
2106   return true;
2107 }
2108 
2109 /// In Microsoft mode, if we are inside a template class whose parent class has
2110 /// dependent base classes, and we can't resolve an unqualified identifier, then
2111 /// assume the identifier is a member of a dependent base class.  We can only
2112 /// recover successfully in static methods, instance methods, and other contexts
2113 /// where 'this' is available.  This doesn't precisely match MSVC's
2114 /// instantiation model, but it's close enough.
2115 static Expr *
2116 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2117                                DeclarationNameInfo &NameInfo,
2118                                SourceLocation TemplateKWLoc,
2119                                const TemplateArgumentListInfo *TemplateArgs) {
2120   // Only try to recover from lookup into dependent bases in static methods or
2121   // contexts where 'this' is available.
2122   QualType ThisType = S.getCurrentThisType();
2123   const CXXRecordDecl *RD = nullptr;
2124   if (!ThisType.isNull())
2125     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2126   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2127     RD = MD->getParent();
2128   if (!RD || !RD->hasAnyDependentBases())
2129     return nullptr;
2130 
2131   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2132   // is available, suggest inserting 'this->' as a fixit.
2133   SourceLocation Loc = NameInfo.getLoc();
2134   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2135   DB << NameInfo.getName() << RD;
2136 
2137   if (!ThisType.isNull()) {
2138     DB << FixItHint::CreateInsertion(Loc, "this->");
2139     return CXXDependentScopeMemberExpr::Create(
2140         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2141         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2142         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2143   }
2144 
2145   // Synthesize a fake NNS that points to the derived class.  This will
2146   // perform name lookup during template instantiation.
2147   CXXScopeSpec SS;
2148   auto *NNS =
2149       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2150   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2151   return DependentScopeDeclRefExpr::Create(
2152       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2153       TemplateArgs);
2154 }
2155 
2156 ExprResult
2157 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2158                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2159                         bool HasTrailingLParen, bool IsAddressOfOperand,
2160                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2161                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2162   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2163          "cannot be direct & operand and have a trailing lparen");
2164   if (SS.isInvalid())
2165     return ExprError();
2166 
2167   TemplateArgumentListInfo TemplateArgsBuffer;
2168 
2169   // Decompose the UnqualifiedId into the following data.
2170   DeclarationNameInfo NameInfo;
2171   const TemplateArgumentListInfo *TemplateArgs;
2172   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2173 
2174   DeclarationName Name = NameInfo.getName();
2175   IdentifierInfo *II = Name.getAsIdentifierInfo();
2176   SourceLocation NameLoc = NameInfo.getLoc();
2177 
2178   if (II && II->isEditorPlaceholder()) {
2179     // FIXME: When typed placeholders are supported we can create a typed
2180     // placeholder expression node.
2181     return ExprError();
2182   }
2183 
2184   // C++ [temp.dep.expr]p3:
2185   //   An id-expression is type-dependent if it contains:
2186   //     -- an identifier that was declared with a dependent type,
2187   //        (note: handled after lookup)
2188   //     -- a template-id that is dependent,
2189   //        (note: handled in BuildTemplateIdExpr)
2190   //     -- a conversion-function-id that specifies a dependent type,
2191   //     -- a nested-name-specifier that contains a class-name that
2192   //        names a dependent type.
2193   // Determine whether this is a member of an unknown specialization;
2194   // we need to handle these differently.
2195   bool DependentID = false;
2196   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2197       Name.getCXXNameType()->isDependentType()) {
2198     DependentID = true;
2199   } else if (SS.isSet()) {
2200     if (DeclContext *DC = computeDeclContext(SS, false)) {
2201       if (RequireCompleteDeclContext(SS, DC))
2202         return ExprError();
2203     } else {
2204       DependentID = true;
2205     }
2206   }
2207 
2208   if (DependentID)
2209     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2210                                       IsAddressOfOperand, TemplateArgs);
2211 
2212   // Perform the required lookup.
2213   LookupResult R(*this, NameInfo,
2214                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2215                      ? LookupObjCImplicitSelfParam
2216                      : LookupOrdinaryName);
2217   if (TemplateKWLoc.isValid() || TemplateArgs) {
2218     // Lookup the template name again to correctly establish the context in
2219     // which it was found. This is really unfortunate as we already did the
2220     // lookup to determine that it was a template name in the first place. If
2221     // this becomes a performance hit, we can work harder to preserve those
2222     // results until we get here but it's likely not worth it.
2223     bool MemberOfUnknownSpecialization;
2224     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2225                            MemberOfUnknownSpecialization, TemplateKWLoc))
2226       return ExprError();
2227 
2228     if (MemberOfUnknownSpecialization ||
2229         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2230       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2231                                         IsAddressOfOperand, TemplateArgs);
2232   } else {
2233     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2234     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2235 
2236     // If the result might be in a dependent base class, this is a dependent
2237     // id-expression.
2238     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2239       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2240                                         IsAddressOfOperand, TemplateArgs);
2241 
2242     // If this reference is in an Objective-C method, then we need to do
2243     // some special Objective-C lookup, too.
2244     if (IvarLookupFollowUp) {
2245       ExprResult E(LookupInObjCMethod(R, S, II, true));
2246       if (E.isInvalid())
2247         return ExprError();
2248 
2249       if (Expr *Ex = E.getAs<Expr>())
2250         return Ex;
2251     }
2252   }
2253 
2254   if (R.isAmbiguous())
2255     return ExprError();
2256 
2257   // This could be an implicitly declared function reference (legal in C90,
2258   // extension in C99, forbidden in C++).
2259   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2260     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2261     if (D) R.addDecl(D);
2262   }
2263 
2264   // Determine whether this name might be a candidate for
2265   // argument-dependent lookup.
2266   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2267 
2268   if (R.empty() && !ADL) {
2269     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2270       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2271                                                    TemplateKWLoc, TemplateArgs))
2272         return E;
2273     }
2274 
2275     // Don't diagnose an empty lookup for inline assembly.
2276     if (IsInlineAsmIdentifier)
2277       return ExprError();
2278 
2279     // If this name wasn't predeclared and if this is not a function
2280     // call, diagnose the problem.
2281     TypoExpr *TE = nullptr;
2282     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2283         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2284     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2285     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2286            "Typo correction callback misconfigured");
2287     if (CCC) {
2288       // Make sure the callback knows what the typo being diagnosed is.
2289       CCC->setTypoName(II);
2290       if (SS.isValid())
2291         CCC->setTypoNNS(SS.getScopeRep());
2292     }
2293     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2294     // a template name, but we happen to have always already looked up the name
2295     // before we get here if it must be a template name.
2296     if (DiagnoseEmptyLookup(S, SS, R,
2297                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2298                             nullptr, None, &TE)) {
2299       if (TE && KeywordReplacement) {
2300         auto &State = getTypoExprState(TE);
2301         auto BestTC = State.Consumer->getNextCorrection();
2302         if (BestTC.isKeyword()) {
2303           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2304           if (State.DiagHandler)
2305             State.DiagHandler(BestTC);
2306           KeywordReplacement->startToken();
2307           KeywordReplacement->setKind(II->getTokenID());
2308           KeywordReplacement->setIdentifierInfo(II);
2309           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2310           // Clean up the state associated with the TypoExpr, since it has
2311           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2312           clearDelayedTypo(TE);
2313           // Signal that a correction to a keyword was performed by returning a
2314           // valid-but-null ExprResult.
2315           return (Expr*)nullptr;
2316         }
2317         State.Consumer->resetCorrectionStream();
2318       }
2319       return TE ? TE : ExprError();
2320     }
2321 
2322     assert(!R.empty() &&
2323            "DiagnoseEmptyLookup returned false but added no results");
2324 
2325     // If we found an Objective-C instance variable, let
2326     // LookupInObjCMethod build the appropriate expression to
2327     // reference the ivar.
2328     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2329       R.clear();
2330       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2331       // In a hopelessly buggy code, Objective-C instance variable
2332       // lookup fails and no expression will be built to reference it.
2333       if (!E.isInvalid() && !E.get())
2334         return ExprError();
2335       return E;
2336     }
2337   }
2338 
2339   // This is guaranteed from this point on.
2340   assert(!R.empty() || ADL);
2341 
2342   // Check whether this might be a C++ implicit instance member access.
2343   // C++ [class.mfct.non-static]p3:
2344   //   When an id-expression that is not part of a class member access
2345   //   syntax and not used to form a pointer to member is used in the
2346   //   body of a non-static member function of class X, if name lookup
2347   //   resolves the name in the id-expression to a non-static non-type
2348   //   member of some class C, the id-expression is transformed into a
2349   //   class member access expression using (*this) as the
2350   //   postfix-expression to the left of the . operator.
2351   //
2352   // But we don't actually need to do this for '&' operands if R
2353   // resolved to a function or overloaded function set, because the
2354   // expression is ill-formed if it actually works out to be a
2355   // non-static member function:
2356   //
2357   // C++ [expr.ref]p4:
2358   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2359   //   [t]he expression can be used only as the left-hand operand of a
2360   //   member function call.
2361   //
2362   // There are other safeguards against such uses, but it's important
2363   // to get this right here so that we don't end up making a
2364   // spuriously dependent expression if we're inside a dependent
2365   // instance method.
2366   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2367     bool MightBeImplicitMember;
2368     if (!IsAddressOfOperand)
2369       MightBeImplicitMember = true;
2370     else if (!SS.isEmpty())
2371       MightBeImplicitMember = false;
2372     else if (R.isOverloadedResult())
2373       MightBeImplicitMember = false;
2374     else if (R.isUnresolvableResult())
2375       MightBeImplicitMember = true;
2376     else
2377       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2378                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2379                               isa<MSPropertyDecl>(R.getFoundDecl());
2380 
2381     if (MightBeImplicitMember)
2382       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2383                                              R, TemplateArgs, S);
2384   }
2385 
2386   if (TemplateArgs || TemplateKWLoc.isValid()) {
2387 
2388     // In C++1y, if this is a variable template id, then check it
2389     // in BuildTemplateIdExpr().
2390     // The single lookup result must be a variable template declaration.
2391     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2392         Id.TemplateId->Kind == TNK_Var_template) {
2393       assert(R.getAsSingle<VarTemplateDecl>() &&
2394              "There should only be one declaration found.");
2395     }
2396 
2397     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2398   }
2399 
2400   return BuildDeclarationNameExpr(SS, R, ADL);
2401 }
2402 
2403 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2404 /// declaration name, generally during template instantiation.
2405 /// There's a large number of things which don't need to be done along
2406 /// this path.
2407 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2408     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2409     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2410   DeclContext *DC = computeDeclContext(SS, false);
2411   if (!DC)
2412     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2413                                      NameInfo, /*TemplateArgs=*/nullptr);
2414 
2415   if (RequireCompleteDeclContext(SS, DC))
2416     return ExprError();
2417 
2418   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2419   LookupQualifiedName(R, DC);
2420 
2421   if (R.isAmbiguous())
2422     return ExprError();
2423 
2424   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2425     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2426                                      NameInfo, /*TemplateArgs=*/nullptr);
2427 
2428   if (R.empty()) {
2429     Diag(NameInfo.getLoc(), diag::err_no_member)
2430       << NameInfo.getName() << DC << SS.getRange();
2431     return ExprError();
2432   }
2433 
2434   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2435     // Diagnose a missing typename if this resolved unambiguously to a type in
2436     // a dependent context.  If we can recover with a type, downgrade this to
2437     // a warning in Microsoft compatibility mode.
2438     unsigned DiagID = diag::err_typename_missing;
2439     if (RecoveryTSI && getLangOpts().MSVCCompat)
2440       DiagID = diag::ext_typename_missing;
2441     SourceLocation Loc = SS.getBeginLoc();
2442     auto D = Diag(Loc, DiagID);
2443     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2444       << SourceRange(Loc, NameInfo.getEndLoc());
2445 
2446     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2447     // context.
2448     if (!RecoveryTSI)
2449       return ExprError();
2450 
2451     // Only issue the fixit if we're prepared to recover.
2452     D << FixItHint::CreateInsertion(Loc, "typename ");
2453 
2454     // Recover by pretending this was an elaborated type.
2455     QualType Ty = Context.getTypeDeclType(TD);
2456     TypeLocBuilder TLB;
2457     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2458 
2459     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2460     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2461     QTL.setElaboratedKeywordLoc(SourceLocation());
2462     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2463 
2464     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2465 
2466     return ExprEmpty();
2467   }
2468 
2469   // Defend against this resolving to an implicit member access. We usually
2470   // won't get here if this might be a legitimate a class member (we end up in
2471   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2472   // a pointer-to-member or in an unevaluated context in C++11.
2473   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2474     return BuildPossibleImplicitMemberExpr(SS,
2475                                            /*TemplateKWLoc=*/SourceLocation(),
2476                                            R, /*TemplateArgs=*/nullptr, S);
2477 
2478   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2479 }
2480 
2481 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2482 /// detected that we're currently inside an ObjC method.  Perform some
2483 /// additional lookup.
2484 ///
2485 /// Ideally, most of this would be done by lookup, but there's
2486 /// actually quite a lot of extra work involved.
2487 ///
2488 /// Returns a null sentinel to indicate trivial success.
2489 ExprResult
2490 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2491                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2492   SourceLocation Loc = Lookup.getNameLoc();
2493   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2494 
2495   // Check for error condition which is already reported.
2496   if (!CurMethod)
2497     return ExprError();
2498 
2499   // There are two cases to handle here.  1) scoped lookup could have failed,
2500   // in which case we should look for an ivar.  2) scoped lookup could have
2501   // found a decl, but that decl is outside the current instance method (i.e.
2502   // a global variable).  In these two cases, we do a lookup for an ivar with
2503   // this name, if the lookup sucedes, we replace it our current decl.
2504 
2505   // If we're in a class method, we don't normally want to look for
2506   // ivars.  But if we don't find anything else, and there's an
2507   // ivar, that's an error.
2508   bool IsClassMethod = CurMethod->isClassMethod();
2509 
2510   bool LookForIvars;
2511   if (Lookup.empty())
2512     LookForIvars = true;
2513   else if (IsClassMethod)
2514     LookForIvars = false;
2515   else
2516     LookForIvars = (Lookup.isSingleResult() &&
2517                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2518   ObjCInterfaceDecl *IFace = nullptr;
2519   if (LookForIvars) {
2520     IFace = CurMethod->getClassInterface();
2521     ObjCInterfaceDecl *ClassDeclared;
2522     ObjCIvarDecl *IV = nullptr;
2523     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2524       // Diagnose using an ivar in a class method.
2525       if (IsClassMethod)
2526         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2527                          << IV->getDeclName());
2528 
2529       // If we're referencing an invalid decl, just return this as a silent
2530       // error node.  The error diagnostic was already emitted on the decl.
2531       if (IV->isInvalidDecl())
2532         return ExprError();
2533 
2534       // Check if referencing a field with __attribute__((deprecated)).
2535       if (DiagnoseUseOfDecl(IV, Loc))
2536         return ExprError();
2537 
2538       // Diagnose the use of an ivar outside of the declaring class.
2539       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2540           !declaresSameEntity(ClassDeclared, IFace) &&
2541           !getLangOpts().DebuggerSupport)
2542         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2543 
2544       // FIXME: This should use a new expr for a direct reference, don't
2545       // turn this into Self->ivar, just return a BareIVarExpr or something.
2546       IdentifierInfo &II = Context.Idents.get("self");
2547       UnqualifiedId SelfName;
2548       SelfName.setIdentifier(&II, SourceLocation());
2549       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2550       CXXScopeSpec SelfScopeSpec;
2551       SourceLocation TemplateKWLoc;
2552       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2553                                               SelfName, false, false);
2554       if (SelfExpr.isInvalid())
2555         return ExprError();
2556 
2557       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2558       if (SelfExpr.isInvalid())
2559         return ExprError();
2560 
2561       MarkAnyDeclReferenced(Loc, IV, true);
2562 
2563       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2564       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2565           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2566         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2567 
2568       ObjCIvarRefExpr *Result = new (Context)
2569           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2570                           IV->getLocation(), SelfExpr.get(), true, true);
2571 
2572       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2573         if (!isUnevaluatedContext() &&
2574             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2575           getCurFunction()->recordUseOfWeak(Result);
2576       }
2577       if (getLangOpts().ObjCAutoRefCount) {
2578         if (CurContext->isClosure())
2579           Diag(Loc, diag::warn_implicitly_retains_self)
2580             << FixItHint::CreateInsertion(Loc, "self->");
2581       }
2582 
2583       return Result;
2584     }
2585   } else if (CurMethod->isInstanceMethod()) {
2586     // We should warn if a local variable hides an ivar.
2587     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2588       ObjCInterfaceDecl *ClassDeclared;
2589       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2590         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2591             declaresSameEntity(IFace, ClassDeclared))
2592           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2593       }
2594     }
2595   } else if (Lookup.isSingleResult() &&
2596              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2597     // If accessing a stand-alone ivar in a class method, this is an error.
2598     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2599       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2600                        << IV->getDeclName());
2601   }
2602 
2603   if (Lookup.empty() && II && AllowBuiltinCreation) {
2604     // FIXME. Consolidate this with similar code in LookupName.
2605     if (unsigned BuiltinID = II->getBuiltinID()) {
2606       if (!(getLangOpts().CPlusPlus &&
2607             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2608         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2609                                            S, Lookup.isForRedeclaration(),
2610                                            Lookup.getNameLoc());
2611         if (D) Lookup.addDecl(D);
2612       }
2613     }
2614   }
2615   // Sentinel value saying that we didn't do anything special.
2616   return ExprResult((Expr *)nullptr);
2617 }
2618 
2619 /// Cast a base object to a member's actual type.
2620 ///
2621 /// Logically this happens in three phases:
2622 ///
2623 /// * First we cast from the base type to the naming class.
2624 ///   The naming class is the class into which we were looking
2625 ///   when we found the member;  it's the qualifier type if a
2626 ///   qualifier was provided, and otherwise it's the base type.
2627 ///
2628 /// * Next we cast from the naming class to the declaring class.
2629 ///   If the member we found was brought into a class's scope by
2630 ///   a using declaration, this is that class;  otherwise it's
2631 ///   the class declaring the member.
2632 ///
2633 /// * Finally we cast from the declaring class to the "true"
2634 ///   declaring class of the member.  This conversion does not
2635 ///   obey access control.
2636 ExprResult
2637 Sema::PerformObjectMemberConversion(Expr *From,
2638                                     NestedNameSpecifier *Qualifier,
2639                                     NamedDecl *FoundDecl,
2640                                     NamedDecl *Member) {
2641   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2642   if (!RD)
2643     return From;
2644 
2645   QualType DestRecordType;
2646   QualType DestType;
2647   QualType FromRecordType;
2648   QualType FromType = From->getType();
2649   bool PointerConversions = false;
2650   if (isa<FieldDecl>(Member)) {
2651     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2652     auto FromPtrType = FromType->getAs<PointerType>();
2653     DestRecordType = Context.getAddrSpaceQualType(
2654         DestRecordType, FromPtrType
2655                             ? FromType->getPointeeType().getAddressSpace()
2656                             : FromType.getAddressSpace());
2657 
2658     if (FromPtrType) {
2659       DestType = Context.getPointerType(DestRecordType);
2660       FromRecordType = FromPtrType->getPointeeType();
2661       PointerConversions = true;
2662     } else {
2663       DestType = DestRecordType;
2664       FromRecordType = FromType;
2665     }
2666   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2667     if (Method->isStatic())
2668       return From;
2669 
2670     DestType = Method->getThisType();
2671     DestRecordType = DestType->getPointeeType();
2672 
2673     if (FromType->getAs<PointerType>()) {
2674       FromRecordType = FromType->getPointeeType();
2675       PointerConversions = true;
2676     } else {
2677       FromRecordType = FromType;
2678       DestType = DestRecordType;
2679     }
2680   } else {
2681     // No conversion necessary.
2682     return From;
2683   }
2684 
2685   if (DestType->isDependentType() || FromType->isDependentType())
2686     return From;
2687 
2688   // If the unqualified types are the same, no conversion is necessary.
2689   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2690     return From;
2691 
2692   SourceRange FromRange = From->getSourceRange();
2693   SourceLocation FromLoc = FromRange.getBegin();
2694 
2695   ExprValueKind VK = From->getValueKind();
2696 
2697   // C++ [class.member.lookup]p8:
2698   //   [...] Ambiguities can often be resolved by qualifying a name with its
2699   //   class name.
2700   //
2701   // If the member was a qualified name and the qualified referred to a
2702   // specific base subobject type, we'll cast to that intermediate type
2703   // first and then to the object in which the member is declared. That allows
2704   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2705   //
2706   //   class Base { public: int x; };
2707   //   class Derived1 : public Base { };
2708   //   class Derived2 : public Base { };
2709   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2710   //
2711   //   void VeryDerived::f() {
2712   //     x = 17; // error: ambiguous base subobjects
2713   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2714   //   }
2715   if (Qualifier && Qualifier->getAsType()) {
2716     QualType QType = QualType(Qualifier->getAsType(), 0);
2717     assert(QType->isRecordType() && "lookup done with non-record type");
2718 
2719     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2720 
2721     // In C++98, the qualifier type doesn't actually have to be a base
2722     // type of the object type, in which case we just ignore it.
2723     // Otherwise build the appropriate casts.
2724     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2725       CXXCastPath BasePath;
2726       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2727                                        FromLoc, FromRange, &BasePath))
2728         return ExprError();
2729 
2730       if (PointerConversions)
2731         QType = Context.getPointerType(QType);
2732       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2733                                VK, &BasePath).get();
2734 
2735       FromType = QType;
2736       FromRecordType = QRecordType;
2737 
2738       // If the qualifier type was the same as the destination type,
2739       // we're done.
2740       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2741         return From;
2742     }
2743   }
2744 
2745   bool IgnoreAccess = false;
2746 
2747   // If we actually found the member through a using declaration, cast
2748   // down to the using declaration's type.
2749   //
2750   // Pointer equality is fine here because only one declaration of a
2751   // class ever has member declarations.
2752   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2753     assert(isa<UsingShadowDecl>(FoundDecl));
2754     QualType URecordType = Context.getTypeDeclType(
2755                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2756 
2757     // We only need to do this if the naming-class to declaring-class
2758     // conversion is non-trivial.
2759     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2760       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2761       CXXCastPath BasePath;
2762       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2763                                        FromLoc, FromRange, &BasePath))
2764         return ExprError();
2765 
2766       QualType UType = URecordType;
2767       if (PointerConversions)
2768         UType = Context.getPointerType(UType);
2769       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2770                                VK, &BasePath).get();
2771       FromType = UType;
2772       FromRecordType = URecordType;
2773     }
2774 
2775     // We don't do access control for the conversion from the
2776     // declaring class to the true declaring class.
2777     IgnoreAccess = true;
2778   }
2779 
2780   CXXCastPath BasePath;
2781   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2782                                    FromLoc, FromRange, &BasePath,
2783                                    IgnoreAccess))
2784     return ExprError();
2785 
2786   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2787                            VK, &BasePath);
2788 }
2789 
2790 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2791                                       const LookupResult &R,
2792                                       bool HasTrailingLParen) {
2793   // Only when used directly as the postfix-expression of a call.
2794   if (!HasTrailingLParen)
2795     return false;
2796 
2797   // Never if a scope specifier was provided.
2798   if (SS.isSet())
2799     return false;
2800 
2801   // Only in C++ or ObjC++.
2802   if (!getLangOpts().CPlusPlus)
2803     return false;
2804 
2805   // Turn off ADL when we find certain kinds of declarations during
2806   // normal lookup:
2807   for (NamedDecl *D : R) {
2808     // C++0x [basic.lookup.argdep]p3:
2809     //     -- a declaration of a class member
2810     // Since using decls preserve this property, we check this on the
2811     // original decl.
2812     if (D->isCXXClassMember())
2813       return false;
2814 
2815     // C++0x [basic.lookup.argdep]p3:
2816     //     -- a block-scope function declaration that is not a
2817     //        using-declaration
2818     // NOTE: we also trigger this for function templates (in fact, we
2819     // don't check the decl type at all, since all other decl types
2820     // turn off ADL anyway).
2821     if (isa<UsingShadowDecl>(D))
2822       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2823     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2824       return false;
2825 
2826     // C++0x [basic.lookup.argdep]p3:
2827     //     -- a declaration that is neither a function or a function
2828     //        template
2829     // And also for builtin functions.
2830     if (isa<FunctionDecl>(D)) {
2831       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2832 
2833       // But also builtin functions.
2834       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2835         return false;
2836     } else if (!isa<FunctionTemplateDecl>(D))
2837       return false;
2838   }
2839 
2840   return true;
2841 }
2842 
2843 
2844 /// Diagnoses obvious problems with the use of the given declaration
2845 /// as an expression.  This is only actually called for lookups that
2846 /// were not overloaded, and it doesn't promise that the declaration
2847 /// will in fact be used.
2848 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2849   if (D->isInvalidDecl())
2850     return true;
2851 
2852   if (isa<TypedefNameDecl>(D)) {
2853     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2854     return true;
2855   }
2856 
2857   if (isa<ObjCInterfaceDecl>(D)) {
2858     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2859     return true;
2860   }
2861 
2862   if (isa<NamespaceDecl>(D)) {
2863     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2864     return true;
2865   }
2866 
2867   return false;
2868 }
2869 
2870 // Certain multiversion types should be treated as overloaded even when there is
2871 // only one result.
2872 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2873   assert(R.isSingleResult() && "Expected only a single result");
2874   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2875   return FD &&
2876          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2877 }
2878 
2879 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2880                                           LookupResult &R, bool NeedsADL,
2881                                           bool AcceptInvalidDecl) {
2882   // If this is a single, fully-resolved result and we don't need ADL,
2883   // just build an ordinary singleton decl ref.
2884   if (!NeedsADL && R.isSingleResult() &&
2885       !R.getAsSingle<FunctionTemplateDecl>() &&
2886       !ShouldLookupResultBeMultiVersionOverload(R))
2887     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2888                                     R.getRepresentativeDecl(), nullptr,
2889                                     AcceptInvalidDecl);
2890 
2891   // We only need to check the declaration if there's exactly one
2892   // result, because in the overloaded case the results can only be
2893   // functions and function templates.
2894   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2895       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2896     return ExprError();
2897 
2898   // Otherwise, just build an unresolved lookup expression.  Suppress
2899   // any lookup-related diagnostics; we'll hash these out later, when
2900   // we've picked a target.
2901   R.suppressDiagnostics();
2902 
2903   UnresolvedLookupExpr *ULE
2904     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2905                                    SS.getWithLocInContext(Context),
2906                                    R.getLookupNameInfo(),
2907                                    NeedsADL, R.isOverloadedResult(),
2908                                    R.begin(), R.end());
2909 
2910   return ULE;
2911 }
2912 
2913 static void
2914 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2915                                    ValueDecl *var, DeclContext *DC);
2916 
2917 /// Complete semantic analysis for a reference to the given declaration.
2918 ExprResult Sema::BuildDeclarationNameExpr(
2919     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2920     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2921     bool AcceptInvalidDecl) {
2922   assert(D && "Cannot refer to a NULL declaration");
2923   assert(!isa<FunctionTemplateDecl>(D) &&
2924          "Cannot refer unambiguously to a function template");
2925 
2926   SourceLocation Loc = NameInfo.getLoc();
2927   if (CheckDeclInExpr(*this, Loc, D))
2928     return ExprError();
2929 
2930   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2931     // Specifically diagnose references to class templates that are missing
2932     // a template argument list.
2933     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2934     return ExprError();
2935   }
2936 
2937   // Make sure that we're referring to a value.
2938   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2939   if (!VD) {
2940     Diag(Loc, diag::err_ref_non_value)
2941       << D << SS.getRange();
2942     Diag(D->getLocation(), diag::note_declared_at);
2943     return ExprError();
2944   }
2945 
2946   // Check whether this declaration can be used. Note that we suppress
2947   // this check when we're going to perform argument-dependent lookup
2948   // on this function name, because this might not be the function
2949   // that overload resolution actually selects.
2950   if (DiagnoseUseOfDecl(VD, Loc))
2951     return ExprError();
2952 
2953   // Only create DeclRefExpr's for valid Decl's.
2954   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2955     return ExprError();
2956 
2957   // Handle members of anonymous structs and unions.  If we got here,
2958   // and the reference is to a class member indirect field, then this
2959   // must be the subject of a pointer-to-member expression.
2960   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2961     if (!indirectField->isCXXClassMember())
2962       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2963                                                       indirectField);
2964 
2965   {
2966     QualType type = VD->getType();
2967     if (type.isNull())
2968       return ExprError();
2969     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2970       // C++ [except.spec]p17:
2971       //   An exception-specification is considered to be needed when:
2972       //   - in an expression, the function is the unique lookup result or
2973       //     the selected member of a set of overloaded functions.
2974       ResolveExceptionSpec(Loc, FPT);
2975       type = VD->getType();
2976     }
2977     ExprValueKind valueKind = VK_RValue;
2978 
2979     switch (D->getKind()) {
2980     // Ignore all the non-ValueDecl kinds.
2981 #define ABSTRACT_DECL(kind)
2982 #define VALUE(type, base)
2983 #define DECL(type, base) \
2984     case Decl::type:
2985 #include "clang/AST/DeclNodes.inc"
2986       llvm_unreachable("invalid value decl kind");
2987 
2988     // These shouldn't make it here.
2989     case Decl::ObjCAtDefsField:
2990       llvm_unreachable("forming non-member reference to ivar?");
2991 
2992     // Enum constants are always r-values and never references.
2993     // Unresolved using declarations are dependent.
2994     case Decl::EnumConstant:
2995     case Decl::UnresolvedUsingValue:
2996     case Decl::OMPDeclareReduction:
2997     case Decl::OMPDeclareMapper:
2998       valueKind = VK_RValue;
2999       break;
3000 
3001     // Fields and indirect fields that got here must be for
3002     // pointer-to-member expressions; we just call them l-values for
3003     // internal consistency, because this subexpression doesn't really
3004     // exist in the high-level semantics.
3005     case Decl::Field:
3006     case Decl::IndirectField:
3007     case Decl::ObjCIvar:
3008       assert(getLangOpts().CPlusPlus &&
3009              "building reference to field in C?");
3010 
3011       // These can't have reference type in well-formed programs, but
3012       // for internal consistency we do this anyway.
3013       type = type.getNonReferenceType();
3014       valueKind = VK_LValue;
3015       break;
3016 
3017     // Non-type template parameters are either l-values or r-values
3018     // depending on the type.
3019     case Decl::NonTypeTemplateParm: {
3020       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3021         type = reftype->getPointeeType();
3022         valueKind = VK_LValue; // even if the parameter is an r-value reference
3023         break;
3024       }
3025 
3026       // For non-references, we need to strip qualifiers just in case
3027       // the template parameter was declared as 'const int' or whatever.
3028       valueKind = VK_RValue;
3029       type = type.getUnqualifiedType();
3030       break;
3031     }
3032 
3033     case Decl::Var:
3034     case Decl::VarTemplateSpecialization:
3035     case Decl::VarTemplatePartialSpecialization:
3036     case Decl::Decomposition:
3037     case Decl::OMPCapturedExpr:
3038       // In C, "extern void blah;" is valid and is an r-value.
3039       if (!getLangOpts().CPlusPlus &&
3040           !type.hasQualifiers() &&
3041           type->isVoidType()) {
3042         valueKind = VK_RValue;
3043         break;
3044       }
3045       LLVM_FALLTHROUGH;
3046 
3047     case Decl::ImplicitParam:
3048     case Decl::ParmVar: {
3049       // These are always l-values.
3050       valueKind = VK_LValue;
3051       type = type.getNonReferenceType();
3052 
3053       // FIXME: Does the addition of const really only apply in
3054       // potentially-evaluated contexts? Since the variable isn't actually
3055       // captured in an unevaluated context, it seems that the answer is no.
3056       if (!isUnevaluatedContext()) {
3057         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3058         if (!CapturedType.isNull())
3059           type = CapturedType;
3060       }
3061 
3062       break;
3063     }
3064 
3065     case Decl::Binding: {
3066       // These are always lvalues.
3067       valueKind = VK_LValue;
3068       type = type.getNonReferenceType();
3069       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3070       // decides how that's supposed to work.
3071       auto *BD = cast<BindingDecl>(VD);
3072       if (BD->getDeclContext()->isFunctionOrMethod() &&
3073           BD->getDeclContext() != CurContext)
3074         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3075       break;
3076     }
3077 
3078     case Decl::Function: {
3079       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3080         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3081           type = Context.BuiltinFnTy;
3082           valueKind = VK_RValue;
3083           break;
3084         }
3085       }
3086 
3087       const FunctionType *fty = type->castAs<FunctionType>();
3088 
3089       // If we're referring to a function with an __unknown_anytype
3090       // result type, make the entire expression __unknown_anytype.
3091       if (fty->getReturnType() == Context.UnknownAnyTy) {
3092         type = Context.UnknownAnyTy;
3093         valueKind = VK_RValue;
3094         break;
3095       }
3096 
3097       // Functions are l-values in C++.
3098       if (getLangOpts().CPlusPlus) {
3099         valueKind = VK_LValue;
3100         break;
3101       }
3102 
3103       // C99 DR 316 says that, if a function type comes from a
3104       // function definition (without a prototype), that type is only
3105       // used for checking compatibility. Therefore, when referencing
3106       // the function, we pretend that we don't have the full function
3107       // type.
3108       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3109           isa<FunctionProtoType>(fty))
3110         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3111                                               fty->getExtInfo());
3112 
3113       // Functions are r-values in C.
3114       valueKind = VK_RValue;
3115       break;
3116     }
3117 
3118     case Decl::CXXDeductionGuide:
3119       llvm_unreachable("building reference to deduction guide");
3120 
3121     case Decl::MSProperty:
3122       valueKind = VK_LValue;
3123       break;
3124 
3125     case Decl::CXXMethod:
3126       // If we're referring to a method with an __unknown_anytype
3127       // result type, make the entire expression __unknown_anytype.
3128       // This should only be possible with a type written directly.
3129       if (const FunctionProtoType *proto
3130             = dyn_cast<FunctionProtoType>(VD->getType()))
3131         if (proto->getReturnType() == Context.UnknownAnyTy) {
3132           type = Context.UnknownAnyTy;
3133           valueKind = VK_RValue;
3134           break;
3135         }
3136 
3137       // C++ methods are l-values if static, r-values if non-static.
3138       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3139         valueKind = VK_LValue;
3140         break;
3141       }
3142       LLVM_FALLTHROUGH;
3143 
3144     case Decl::CXXConversion:
3145     case Decl::CXXDestructor:
3146     case Decl::CXXConstructor:
3147       valueKind = VK_RValue;
3148       break;
3149     }
3150 
3151     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3152                             TemplateArgs);
3153   }
3154 }
3155 
3156 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3157                                     SmallString<32> &Target) {
3158   Target.resize(CharByteWidth * (Source.size() + 1));
3159   char *ResultPtr = &Target[0];
3160   const llvm::UTF8 *ErrorPtr;
3161   bool success =
3162       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3163   (void)success;
3164   assert(success);
3165   Target.resize(ResultPtr - &Target[0]);
3166 }
3167 
3168 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3169                                      PredefinedExpr::IdentKind IK) {
3170   // Pick the current block, lambda, captured statement or function.
3171   Decl *currentDecl = nullptr;
3172   if (const BlockScopeInfo *BSI = getCurBlock())
3173     currentDecl = BSI->TheDecl;
3174   else if (const LambdaScopeInfo *LSI = getCurLambda())
3175     currentDecl = LSI->CallOperator;
3176   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3177     currentDecl = CSI->TheCapturedDecl;
3178   else
3179     currentDecl = getCurFunctionOrMethodDecl();
3180 
3181   if (!currentDecl) {
3182     Diag(Loc, diag::ext_predef_outside_function);
3183     currentDecl = Context.getTranslationUnitDecl();
3184   }
3185 
3186   QualType ResTy;
3187   StringLiteral *SL = nullptr;
3188   if (cast<DeclContext>(currentDecl)->isDependentContext())
3189     ResTy = Context.DependentTy;
3190   else {
3191     // Pre-defined identifiers are of type char[x], where x is the length of
3192     // the string.
3193     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3194     unsigned Length = Str.length();
3195 
3196     llvm::APInt LengthI(32, Length + 1);
3197     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3198       ResTy =
3199           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3200       SmallString<32> RawChars;
3201       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3202                               Str, RawChars);
3203       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3204                                            /*IndexTypeQuals*/ 0);
3205       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3206                                  /*Pascal*/ false, ResTy, Loc);
3207     } else {
3208       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3209       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3210                                            /*IndexTypeQuals*/ 0);
3211       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3212                                  /*Pascal*/ false, ResTy, Loc);
3213     }
3214   }
3215 
3216   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3217 }
3218 
3219 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3220   PredefinedExpr::IdentKind IK;
3221 
3222   switch (Kind) {
3223   default: llvm_unreachable("Unknown simple primary expr!");
3224   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3225   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3226   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3227   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3228   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3229   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3230   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3231   }
3232 
3233   return BuildPredefinedExpr(Loc, IK);
3234 }
3235 
3236 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3237   SmallString<16> CharBuffer;
3238   bool Invalid = false;
3239   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3240   if (Invalid)
3241     return ExprError();
3242 
3243   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3244                             PP, Tok.getKind());
3245   if (Literal.hadError())
3246     return ExprError();
3247 
3248   QualType Ty;
3249   if (Literal.isWide())
3250     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3251   else if (Literal.isUTF8() && getLangOpts().Char8)
3252     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3253   else if (Literal.isUTF16())
3254     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3255   else if (Literal.isUTF32())
3256     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3257   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3258     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3259   else
3260     Ty = Context.CharTy;  // 'x' -> char in C++
3261 
3262   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3263   if (Literal.isWide())
3264     Kind = CharacterLiteral::Wide;
3265   else if (Literal.isUTF16())
3266     Kind = CharacterLiteral::UTF16;
3267   else if (Literal.isUTF32())
3268     Kind = CharacterLiteral::UTF32;
3269   else if (Literal.isUTF8())
3270     Kind = CharacterLiteral::UTF8;
3271 
3272   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3273                                              Tok.getLocation());
3274 
3275   if (Literal.getUDSuffix().empty())
3276     return Lit;
3277 
3278   // We're building a user-defined literal.
3279   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3280   SourceLocation UDSuffixLoc =
3281     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3282 
3283   // Make sure we're allowed user-defined literals here.
3284   if (!UDLScope)
3285     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3286 
3287   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3288   //   operator "" X (ch)
3289   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3290                                         Lit, Tok.getLocation());
3291 }
3292 
3293 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3294   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3295   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3296                                 Context.IntTy, Loc);
3297 }
3298 
3299 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3300                                   QualType Ty, SourceLocation Loc) {
3301   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3302 
3303   using llvm::APFloat;
3304   APFloat Val(Format);
3305 
3306   APFloat::opStatus result = Literal.GetFloatValue(Val);
3307 
3308   // Overflow is always an error, but underflow is only an error if
3309   // we underflowed to zero (APFloat reports denormals as underflow).
3310   if ((result & APFloat::opOverflow) ||
3311       ((result & APFloat::opUnderflow) && Val.isZero())) {
3312     unsigned diagnostic;
3313     SmallString<20> buffer;
3314     if (result & APFloat::opOverflow) {
3315       diagnostic = diag::warn_float_overflow;
3316       APFloat::getLargest(Format).toString(buffer);
3317     } else {
3318       diagnostic = diag::warn_float_underflow;
3319       APFloat::getSmallest(Format).toString(buffer);
3320     }
3321 
3322     S.Diag(Loc, diagnostic)
3323       << Ty
3324       << StringRef(buffer.data(), buffer.size());
3325   }
3326 
3327   bool isExact = (result == APFloat::opOK);
3328   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3329 }
3330 
3331 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3332   assert(E && "Invalid expression");
3333 
3334   if (E->isValueDependent())
3335     return false;
3336 
3337   QualType QT = E->getType();
3338   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3339     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3340     return true;
3341   }
3342 
3343   llvm::APSInt ValueAPS;
3344   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3345 
3346   if (R.isInvalid())
3347     return true;
3348 
3349   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3350   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3351     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3352         << ValueAPS.toString(10) << ValueIsPositive;
3353     return true;
3354   }
3355 
3356   return false;
3357 }
3358 
3359 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3360   // Fast path for a single digit (which is quite common).  A single digit
3361   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3362   if (Tok.getLength() == 1) {
3363     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3364     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3365   }
3366 
3367   SmallString<128> SpellingBuffer;
3368   // NumericLiteralParser wants to overread by one character.  Add padding to
3369   // the buffer in case the token is copied to the buffer.  If getSpelling()
3370   // returns a StringRef to the memory buffer, it should have a null char at
3371   // the EOF, so it is also safe.
3372   SpellingBuffer.resize(Tok.getLength() + 1);
3373 
3374   // Get the spelling of the token, which eliminates trigraphs, etc.
3375   bool Invalid = false;
3376   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3377   if (Invalid)
3378     return ExprError();
3379 
3380   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3381   if (Literal.hadError)
3382     return ExprError();
3383 
3384   if (Literal.hasUDSuffix()) {
3385     // We're building a user-defined literal.
3386     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3387     SourceLocation UDSuffixLoc =
3388       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3389 
3390     // Make sure we're allowed user-defined literals here.
3391     if (!UDLScope)
3392       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3393 
3394     QualType CookedTy;
3395     if (Literal.isFloatingLiteral()) {
3396       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3397       // long double, the literal is treated as a call of the form
3398       //   operator "" X (f L)
3399       CookedTy = Context.LongDoubleTy;
3400     } else {
3401       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3402       // unsigned long long, the literal is treated as a call of the form
3403       //   operator "" X (n ULL)
3404       CookedTy = Context.UnsignedLongLongTy;
3405     }
3406 
3407     DeclarationName OpName =
3408       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3409     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3410     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3411 
3412     SourceLocation TokLoc = Tok.getLocation();
3413 
3414     // Perform literal operator lookup to determine if we're building a raw
3415     // literal or a cooked one.
3416     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3417     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3418                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3419                                   /*AllowStringTemplate*/ false,
3420                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3421     case LOLR_ErrorNoDiagnostic:
3422       // Lookup failure for imaginary constants isn't fatal, there's still the
3423       // GNU extension producing _Complex types.
3424       break;
3425     case LOLR_Error:
3426       return ExprError();
3427     case LOLR_Cooked: {
3428       Expr *Lit;
3429       if (Literal.isFloatingLiteral()) {
3430         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3431       } else {
3432         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3433         if (Literal.GetIntegerValue(ResultVal))
3434           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3435               << /* Unsigned */ 1;
3436         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3437                                      Tok.getLocation());
3438       }
3439       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3440     }
3441 
3442     case LOLR_Raw: {
3443       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3444       // literal is treated as a call of the form
3445       //   operator "" X ("n")
3446       unsigned Length = Literal.getUDSuffixOffset();
3447       QualType StrTy = Context.getConstantArrayType(
3448           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3449           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3450       Expr *Lit = StringLiteral::Create(
3451           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3452           /*Pascal*/false, StrTy, &TokLoc, 1);
3453       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3454     }
3455 
3456     case LOLR_Template: {
3457       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3458       // template), L is treated as a call fo the form
3459       //   operator "" X <'c1', 'c2', ... 'ck'>()
3460       // where n is the source character sequence c1 c2 ... ck.
3461       TemplateArgumentListInfo ExplicitArgs;
3462       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3463       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3464       llvm::APSInt Value(CharBits, CharIsUnsigned);
3465       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3466         Value = TokSpelling[I];
3467         TemplateArgument Arg(Context, Value, Context.CharTy);
3468         TemplateArgumentLocInfo ArgInfo;
3469         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3470       }
3471       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3472                                       &ExplicitArgs);
3473     }
3474     case LOLR_StringTemplate:
3475       llvm_unreachable("unexpected literal operator lookup result");
3476     }
3477   }
3478 
3479   Expr *Res;
3480 
3481   if (Literal.isFixedPointLiteral()) {
3482     QualType Ty;
3483 
3484     if (Literal.isAccum) {
3485       if (Literal.isHalf) {
3486         Ty = Context.ShortAccumTy;
3487       } else if (Literal.isLong) {
3488         Ty = Context.LongAccumTy;
3489       } else {
3490         Ty = Context.AccumTy;
3491       }
3492     } else if (Literal.isFract) {
3493       if (Literal.isHalf) {
3494         Ty = Context.ShortFractTy;
3495       } else if (Literal.isLong) {
3496         Ty = Context.LongFractTy;
3497       } else {
3498         Ty = Context.FractTy;
3499       }
3500     }
3501 
3502     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3503 
3504     bool isSigned = !Literal.isUnsigned;
3505     unsigned scale = Context.getFixedPointScale(Ty);
3506     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3507 
3508     llvm::APInt Val(bit_width, 0, isSigned);
3509     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3510     bool ValIsZero = Val.isNullValue() && !Overflowed;
3511 
3512     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3513     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3514       // Clause 6.4.4 - The value of a constant shall be in the range of
3515       // representable values for its type, with exception for constants of a
3516       // fract type with a value of exactly 1; such a constant shall denote
3517       // the maximal value for the type.
3518       --Val;
3519     else if (Val.ugt(MaxVal) || Overflowed)
3520       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3521 
3522     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3523                                               Tok.getLocation(), scale);
3524   } else if (Literal.isFloatingLiteral()) {
3525     QualType Ty;
3526     if (Literal.isHalf){
3527       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3528         Ty = Context.HalfTy;
3529       else {
3530         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3531         return ExprError();
3532       }
3533     } else if (Literal.isFloat)
3534       Ty = Context.FloatTy;
3535     else if (Literal.isLong)
3536       Ty = Context.LongDoubleTy;
3537     else if (Literal.isFloat16)
3538       Ty = Context.Float16Ty;
3539     else if (Literal.isFloat128)
3540       Ty = Context.Float128Ty;
3541     else
3542       Ty = Context.DoubleTy;
3543 
3544     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3545 
3546     if (Ty == Context.DoubleTy) {
3547       if (getLangOpts().SinglePrecisionConstants) {
3548         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3549         if (BTy->getKind() != BuiltinType::Float) {
3550           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3551         }
3552       } else if (getLangOpts().OpenCL &&
3553                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3554         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3555         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3556         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3557       }
3558     }
3559   } else if (!Literal.isIntegerLiteral()) {
3560     return ExprError();
3561   } else {
3562     QualType Ty;
3563 
3564     // 'long long' is a C99 or C++11 feature.
3565     if (!getLangOpts().C99 && Literal.isLongLong) {
3566       if (getLangOpts().CPlusPlus)
3567         Diag(Tok.getLocation(),
3568              getLangOpts().CPlusPlus11 ?
3569              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3570       else
3571         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3572     }
3573 
3574     // Get the value in the widest-possible width.
3575     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3576     llvm::APInt ResultVal(MaxWidth, 0);
3577 
3578     if (Literal.GetIntegerValue(ResultVal)) {
3579       // If this value didn't fit into uintmax_t, error and force to ull.
3580       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3581           << /* Unsigned */ 1;
3582       Ty = Context.UnsignedLongLongTy;
3583       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3584              "long long is not intmax_t?");
3585     } else {
3586       // If this value fits into a ULL, try to figure out what else it fits into
3587       // according to the rules of C99 6.4.4.1p5.
3588 
3589       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3590       // be an unsigned int.
3591       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3592 
3593       // Check from smallest to largest, picking the smallest type we can.
3594       unsigned Width = 0;
3595 
3596       // Microsoft specific integer suffixes are explicitly sized.
3597       if (Literal.MicrosoftInteger) {
3598         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3599           Width = 8;
3600           Ty = Context.CharTy;
3601         } else {
3602           Width = Literal.MicrosoftInteger;
3603           Ty = Context.getIntTypeForBitwidth(Width,
3604                                              /*Signed=*/!Literal.isUnsigned);
3605         }
3606       }
3607 
3608       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3609         // Are int/unsigned possibilities?
3610         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3611 
3612         // Does it fit in a unsigned int?
3613         if (ResultVal.isIntN(IntSize)) {
3614           // Does it fit in a signed int?
3615           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3616             Ty = Context.IntTy;
3617           else if (AllowUnsigned)
3618             Ty = Context.UnsignedIntTy;
3619           Width = IntSize;
3620         }
3621       }
3622 
3623       // Are long/unsigned long possibilities?
3624       if (Ty.isNull() && !Literal.isLongLong) {
3625         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3626 
3627         // Does it fit in a unsigned long?
3628         if (ResultVal.isIntN(LongSize)) {
3629           // Does it fit in a signed long?
3630           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3631             Ty = Context.LongTy;
3632           else if (AllowUnsigned)
3633             Ty = Context.UnsignedLongTy;
3634           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3635           // is compatible.
3636           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3637             const unsigned LongLongSize =
3638                 Context.getTargetInfo().getLongLongWidth();
3639             Diag(Tok.getLocation(),
3640                  getLangOpts().CPlusPlus
3641                      ? Literal.isLong
3642                            ? diag::warn_old_implicitly_unsigned_long_cxx
3643                            : /*C++98 UB*/ diag::
3644                                  ext_old_implicitly_unsigned_long_cxx
3645                      : diag::warn_old_implicitly_unsigned_long)
3646                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3647                                             : /*will be ill-formed*/ 1);
3648             Ty = Context.UnsignedLongTy;
3649           }
3650           Width = LongSize;
3651         }
3652       }
3653 
3654       // Check long long if needed.
3655       if (Ty.isNull()) {
3656         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3657 
3658         // Does it fit in a unsigned long long?
3659         if (ResultVal.isIntN(LongLongSize)) {
3660           // Does it fit in a signed long long?
3661           // To be compatible with MSVC, hex integer literals ending with the
3662           // LL or i64 suffix are always signed in Microsoft mode.
3663           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3664               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3665             Ty = Context.LongLongTy;
3666           else if (AllowUnsigned)
3667             Ty = Context.UnsignedLongLongTy;
3668           Width = LongLongSize;
3669         }
3670       }
3671 
3672       // If we still couldn't decide a type, we probably have something that
3673       // does not fit in a signed long long, but has no U suffix.
3674       if (Ty.isNull()) {
3675         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3676         Ty = Context.UnsignedLongLongTy;
3677         Width = Context.getTargetInfo().getLongLongWidth();
3678       }
3679 
3680       if (ResultVal.getBitWidth() != Width)
3681         ResultVal = ResultVal.trunc(Width);
3682     }
3683     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3684   }
3685 
3686   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3687   if (Literal.isImaginary) {
3688     Res = new (Context) ImaginaryLiteral(Res,
3689                                         Context.getComplexType(Res->getType()));
3690 
3691     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3692   }
3693   return Res;
3694 }
3695 
3696 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3697   assert(E && "ActOnParenExpr() missing expr");
3698   return new (Context) ParenExpr(L, R, E);
3699 }
3700 
3701 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3702                                          SourceLocation Loc,
3703                                          SourceRange ArgRange) {
3704   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3705   // scalar or vector data type argument..."
3706   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3707   // type (C99 6.2.5p18) or void.
3708   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3709     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3710       << T << ArgRange;
3711     return true;
3712   }
3713 
3714   assert((T->isVoidType() || !T->isIncompleteType()) &&
3715          "Scalar types should always be complete");
3716   return false;
3717 }
3718 
3719 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3720                                            SourceLocation Loc,
3721                                            SourceRange ArgRange,
3722                                            UnaryExprOrTypeTrait TraitKind) {
3723   // Invalid types must be hard errors for SFINAE in C++.
3724   if (S.LangOpts.CPlusPlus)
3725     return true;
3726 
3727   // C99 6.5.3.4p1:
3728   if (T->isFunctionType() &&
3729       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3730        TraitKind == UETT_PreferredAlignOf)) {
3731     // sizeof(function)/alignof(function) is allowed as an extension.
3732     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3733       << TraitKind << ArgRange;
3734     return false;
3735   }
3736 
3737   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3738   // this is an error (OpenCL v1.1 s6.3.k)
3739   if (T->isVoidType()) {
3740     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3741                                         : diag::ext_sizeof_alignof_void_type;
3742     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3743     return false;
3744   }
3745 
3746   return true;
3747 }
3748 
3749 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3750                                              SourceLocation Loc,
3751                                              SourceRange ArgRange,
3752                                              UnaryExprOrTypeTrait TraitKind) {
3753   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3754   // runtime doesn't allow it.
3755   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3756     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3757       << T << (TraitKind == UETT_SizeOf)
3758       << ArgRange;
3759     return true;
3760   }
3761 
3762   return false;
3763 }
3764 
3765 /// Check whether E is a pointer from a decayed array type (the decayed
3766 /// pointer type is equal to T) and emit a warning if it is.
3767 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3768                                      Expr *E) {
3769   // Don't warn if the operation changed the type.
3770   if (T != E->getType())
3771     return;
3772 
3773   // Now look for array decays.
3774   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3775   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3776     return;
3777 
3778   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3779                                              << ICE->getType()
3780                                              << ICE->getSubExpr()->getType();
3781 }
3782 
3783 /// Check the constraints on expression operands to unary type expression
3784 /// and type traits.
3785 ///
3786 /// Completes any types necessary and validates the constraints on the operand
3787 /// expression. The logic mostly mirrors the type-based overload, but may modify
3788 /// the expression as it completes the type for that expression through template
3789 /// instantiation, etc.
3790 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3791                                             UnaryExprOrTypeTrait ExprKind) {
3792   QualType ExprTy = E->getType();
3793   assert(!ExprTy->isReferenceType());
3794 
3795   if (ExprKind == UETT_VecStep)
3796     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3797                                         E->getSourceRange());
3798 
3799   // Whitelist some types as extensions
3800   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3801                                       E->getSourceRange(), ExprKind))
3802     return false;
3803 
3804   // 'alignof' applied to an expression only requires the base element type of
3805   // the expression to be complete. 'sizeof' requires the expression's type to
3806   // be complete (and will attempt to complete it if it's an array of unknown
3807   // bound).
3808   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3809     if (RequireCompleteType(E->getExprLoc(),
3810                             Context.getBaseElementType(E->getType()),
3811                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3812                             E->getSourceRange()))
3813       return true;
3814   } else {
3815     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3816                                 ExprKind, E->getSourceRange()))
3817       return true;
3818   }
3819 
3820   // Completing the expression's type may have changed it.
3821   ExprTy = E->getType();
3822   assert(!ExprTy->isReferenceType());
3823 
3824   if (ExprTy->isFunctionType()) {
3825     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3826       << ExprKind << E->getSourceRange();
3827     return true;
3828   }
3829 
3830   // The operand for sizeof and alignof is in an unevaluated expression context,
3831   // so side effects could result in unintended consequences.
3832   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3833        ExprKind == UETT_PreferredAlignOf) &&
3834       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3835     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3836 
3837   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3838                                        E->getSourceRange(), ExprKind))
3839     return true;
3840 
3841   if (ExprKind == UETT_SizeOf) {
3842     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3843       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3844         QualType OType = PVD->getOriginalType();
3845         QualType Type = PVD->getType();
3846         if (Type->isPointerType() && OType->isArrayType()) {
3847           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3848             << Type << OType;
3849           Diag(PVD->getLocation(), diag::note_declared_at);
3850         }
3851       }
3852     }
3853 
3854     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3855     // decays into a pointer and returns an unintended result. This is most
3856     // likely a typo for "sizeof(array) op x".
3857     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3858       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3859                                BO->getLHS());
3860       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3861                                BO->getRHS());
3862     }
3863   }
3864 
3865   return false;
3866 }
3867 
3868 /// Check the constraints on operands to unary expression and type
3869 /// traits.
3870 ///
3871 /// This will complete any types necessary, and validate the various constraints
3872 /// on those operands.
3873 ///
3874 /// The UsualUnaryConversions() function is *not* called by this routine.
3875 /// C99 6.3.2.1p[2-4] all state:
3876 ///   Except when it is the operand of the sizeof operator ...
3877 ///
3878 /// C++ [expr.sizeof]p4
3879 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3880 ///   standard conversions are not applied to the operand of sizeof.
3881 ///
3882 /// This policy is followed for all of the unary trait expressions.
3883 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3884                                             SourceLocation OpLoc,
3885                                             SourceRange ExprRange,
3886                                             UnaryExprOrTypeTrait ExprKind) {
3887   if (ExprType->isDependentType())
3888     return false;
3889 
3890   // C++ [expr.sizeof]p2:
3891   //     When applied to a reference or a reference type, the result
3892   //     is the size of the referenced type.
3893   // C++11 [expr.alignof]p3:
3894   //     When alignof is applied to a reference type, the result
3895   //     shall be the alignment of the referenced type.
3896   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3897     ExprType = Ref->getPointeeType();
3898 
3899   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3900   //   When alignof or _Alignof is applied to an array type, the result
3901   //   is the alignment of the element type.
3902   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3903       ExprKind == UETT_OpenMPRequiredSimdAlign)
3904     ExprType = Context.getBaseElementType(ExprType);
3905 
3906   if (ExprKind == UETT_VecStep)
3907     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3908 
3909   // Whitelist some types as extensions
3910   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3911                                       ExprKind))
3912     return false;
3913 
3914   if (RequireCompleteType(OpLoc, ExprType,
3915                           diag::err_sizeof_alignof_incomplete_type,
3916                           ExprKind, ExprRange))
3917     return true;
3918 
3919   if (ExprType->isFunctionType()) {
3920     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3921       << ExprKind << ExprRange;
3922     return true;
3923   }
3924 
3925   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3926                                        ExprKind))
3927     return true;
3928 
3929   return false;
3930 }
3931 
3932 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3933   E = E->IgnoreParens();
3934 
3935   // Cannot know anything else if the expression is dependent.
3936   if (E->isTypeDependent())
3937     return false;
3938 
3939   if (E->getObjectKind() == OK_BitField) {
3940     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3941        << 1 << E->getSourceRange();
3942     return true;
3943   }
3944 
3945   ValueDecl *D = nullptr;
3946   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3947     D = DRE->getDecl();
3948   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3949     D = ME->getMemberDecl();
3950   }
3951 
3952   // If it's a field, require the containing struct to have a
3953   // complete definition so that we can compute the layout.
3954   //
3955   // This can happen in C++11 onwards, either by naming the member
3956   // in a way that is not transformed into a member access expression
3957   // (in an unevaluated operand, for instance), or by naming the member
3958   // in a trailing-return-type.
3959   //
3960   // For the record, since __alignof__ on expressions is a GCC
3961   // extension, GCC seems to permit this but always gives the
3962   // nonsensical answer 0.
3963   //
3964   // We don't really need the layout here --- we could instead just
3965   // directly check for all the appropriate alignment-lowing
3966   // attributes --- but that would require duplicating a lot of
3967   // logic that just isn't worth duplicating for such a marginal
3968   // use-case.
3969   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3970     // Fast path this check, since we at least know the record has a
3971     // definition if we can find a member of it.
3972     if (!FD->getParent()->isCompleteDefinition()) {
3973       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3974         << E->getSourceRange();
3975       return true;
3976     }
3977 
3978     // Otherwise, if it's a field, and the field doesn't have
3979     // reference type, then it must have a complete type (or be a
3980     // flexible array member, which we explicitly want to
3981     // white-list anyway), which makes the following checks trivial.
3982     if (!FD->getType()->isReferenceType())
3983       return false;
3984   }
3985 
3986   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3987 }
3988 
3989 bool Sema::CheckVecStepExpr(Expr *E) {
3990   E = E->IgnoreParens();
3991 
3992   // Cannot know anything else if the expression is dependent.
3993   if (E->isTypeDependent())
3994     return false;
3995 
3996   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3997 }
3998 
3999 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4000                                         CapturingScopeInfo *CSI) {
4001   assert(T->isVariablyModifiedType());
4002   assert(CSI != nullptr);
4003 
4004   // We're going to walk down into the type and look for VLA expressions.
4005   do {
4006     const Type *Ty = T.getTypePtr();
4007     switch (Ty->getTypeClass()) {
4008 #define TYPE(Class, Base)
4009 #define ABSTRACT_TYPE(Class, Base)
4010 #define NON_CANONICAL_TYPE(Class, Base)
4011 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4012 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4013 #include "clang/AST/TypeNodes.def"
4014       T = QualType();
4015       break;
4016     // These types are never variably-modified.
4017     case Type::Builtin:
4018     case Type::Complex:
4019     case Type::Vector:
4020     case Type::ExtVector:
4021     case Type::Record:
4022     case Type::Enum:
4023     case Type::Elaborated:
4024     case Type::TemplateSpecialization:
4025     case Type::ObjCObject:
4026     case Type::ObjCInterface:
4027     case Type::ObjCObjectPointer:
4028     case Type::ObjCTypeParam:
4029     case Type::Pipe:
4030       llvm_unreachable("type class is never variably-modified!");
4031     case Type::Adjusted:
4032       T = cast<AdjustedType>(Ty)->getOriginalType();
4033       break;
4034     case Type::Decayed:
4035       T = cast<DecayedType>(Ty)->getPointeeType();
4036       break;
4037     case Type::Pointer:
4038       T = cast<PointerType>(Ty)->getPointeeType();
4039       break;
4040     case Type::BlockPointer:
4041       T = cast<BlockPointerType>(Ty)->getPointeeType();
4042       break;
4043     case Type::LValueReference:
4044     case Type::RValueReference:
4045       T = cast<ReferenceType>(Ty)->getPointeeType();
4046       break;
4047     case Type::MemberPointer:
4048       T = cast<MemberPointerType>(Ty)->getPointeeType();
4049       break;
4050     case Type::ConstantArray:
4051     case Type::IncompleteArray:
4052       // Losing element qualification here is fine.
4053       T = cast<ArrayType>(Ty)->getElementType();
4054       break;
4055     case Type::VariableArray: {
4056       // Losing element qualification here is fine.
4057       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4058 
4059       // Unknown size indication requires no size computation.
4060       // Otherwise, evaluate and record it.
4061       if (auto Size = VAT->getSizeExpr()) {
4062         if (!CSI->isVLATypeCaptured(VAT)) {
4063           RecordDecl *CapRecord = nullptr;
4064           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
4065             CapRecord = LSI->Lambda;
4066           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
4067             CapRecord = CRSI->TheRecordDecl;
4068           }
4069           if (CapRecord) {
4070             auto ExprLoc = Size->getExprLoc();
4071             auto SizeType = Context.getSizeType();
4072             // Build the non-static data member.
4073             auto Field =
4074                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
4075                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
4076                                   /*BW*/ nullptr, /*Mutable*/ false,
4077                                   /*InitStyle*/ ICIS_NoInit);
4078             Field->setImplicit(true);
4079             Field->setAccess(AS_private);
4080             Field->setCapturedVLAType(VAT);
4081             CapRecord->addDecl(Field);
4082 
4083             CSI->addVLATypeCapture(ExprLoc, SizeType);
4084           }
4085         }
4086       }
4087       T = VAT->getElementType();
4088       break;
4089     }
4090     case Type::FunctionProto:
4091     case Type::FunctionNoProto:
4092       T = cast<FunctionType>(Ty)->getReturnType();
4093       break;
4094     case Type::Paren:
4095     case Type::TypeOf:
4096     case Type::UnaryTransform:
4097     case Type::Attributed:
4098     case Type::SubstTemplateTypeParm:
4099     case Type::PackExpansion:
4100       // Keep walking after single level desugaring.
4101       T = T.getSingleStepDesugaredType(Context);
4102       break;
4103     case Type::Typedef:
4104       T = cast<TypedefType>(Ty)->desugar();
4105       break;
4106     case Type::Decltype:
4107       T = cast<DecltypeType>(Ty)->desugar();
4108       break;
4109     case Type::Auto:
4110     case Type::DeducedTemplateSpecialization:
4111       T = cast<DeducedType>(Ty)->getDeducedType();
4112       break;
4113     case Type::TypeOfExpr:
4114       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4115       break;
4116     case Type::Atomic:
4117       T = cast<AtomicType>(Ty)->getValueType();
4118       break;
4119     }
4120   } while (!T.isNull() && T->isVariablyModifiedType());
4121 }
4122 
4123 /// Build a sizeof or alignof expression given a type operand.
4124 ExprResult
4125 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4126                                      SourceLocation OpLoc,
4127                                      UnaryExprOrTypeTrait ExprKind,
4128                                      SourceRange R) {
4129   if (!TInfo)
4130     return ExprError();
4131 
4132   QualType T = TInfo->getType();
4133 
4134   if (!T->isDependentType() &&
4135       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4136     return ExprError();
4137 
4138   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4139     if (auto *TT = T->getAs<TypedefType>()) {
4140       for (auto I = FunctionScopes.rbegin(),
4141                 E = std::prev(FunctionScopes.rend());
4142            I != E; ++I) {
4143         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4144         if (CSI == nullptr)
4145           break;
4146         DeclContext *DC = nullptr;
4147         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4148           DC = LSI->CallOperator;
4149         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4150           DC = CRSI->TheCapturedDecl;
4151         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4152           DC = BSI->TheDecl;
4153         if (DC) {
4154           if (DC->containsDecl(TT->getDecl()))
4155             break;
4156           captureVariablyModifiedType(Context, T, CSI);
4157         }
4158       }
4159     }
4160   }
4161 
4162   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4163   return new (Context) UnaryExprOrTypeTraitExpr(
4164       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4165 }
4166 
4167 /// Build a sizeof or alignof expression given an expression
4168 /// operand.
4169 ExprResult
4170 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4171                                      UnaryExprOrTypeTrait ExprKind) {
4172   ExprResult PE = CheckPlaceholderExpr(E);
4173   if (PE.isInvalid())
4174     return ExprError();
4175 
4176   E = PE.get();
4177 
4178   // Verify that the operand is valid.
4179   bool isInvalid = false;
4180   if (E->isTypeDependent()) {
4181     // Delay type-checking for type-dependent expressions.
4182   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4183     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4184   } else if (ExprKind == UETT_VecStep) {
4185     isInvalid = CheckVecStepExpr(E);
4186   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4187       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4188       isInvalid = true;
4189   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4190     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4191     isInvalid = true;
4192   } else {
4193     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4194   }
4195 
4196   if (isInvalid)
4197     return ExprError();
4198 
4199   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4200     PE = TransformToPotentiallyEvaluated(E);
4201     if (PE.isInvalid()) return ExprError();
4202     E = PE.get();
4203   }
4204 
4205   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4206   return new (Context) UnaryExprOrTypeTraitExpr(
4207       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4208 }
4209 
4210 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4211 /// expr and the same for @c alignof and @c __alignof
4212 /// Note that the ArgRange is invalid if isType is false.
4213 ExprResult
4214 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4215                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4216                                     void *TyOrEx, SourceRange ArgRange) {
4217   // If error parsing type, ignore.
4218   if (!TyOrEx) return ExprError();
4219 
4220   if (IsType) {
4221     TypeSourceInfo *TInfo;
4222     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4223     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4224   }
4225 
4226   Expr *ArgEx = (Expr *)TyOrEx;
4227   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4228   return Result;
4229 }
4230 
4231 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4232                                      bool IsReal) {
4233   if (V.get()->isTypeDependent())
4234     return S.Context.DependentTy;
4235 
4236   // _Real and _Imag are only l-values for normal l-values.
4237   if (V.get()->getObjectKind() != OK_Ordinary) {
4238     V = S.DefaultLvalueConversion(V.get());
4239     if (V.isInvalid())
4240       return QualType();
4241   }
4242 
4243   // These operators return the element type of a complex type.
4244   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4245     return CT->getElementType();
4246 
4247   // Otherwise they pass through real integer and floating point types here.
4248   if (V.get()->getType()->isArithmeticType())
4249     return V.get()->getType();
4250 
4251   // Test for placeholders.
4252   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4253   if (PR.isInvalid()) return QualType();
4254   if (PR.get() != V.get()) {
4255     V = PR;
4256     return CheckRealImagOperand(S, V, Loc, IsReal);
4257   }
4258 
4259   // Reject anything else.
4260   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4261     << (IsReal ? "__real" : "__imag");
4262   return QualType();
4263 }
4264 
4265 
4266 
4267 ExprResult
4268 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4269                           tok::TokenKind Kind, Expr *Input) {
4270   UnaryOperatorKind Opc;
4271   switch (Kind) {
4272   default: llvm_unreachable("Unknown unary op!");
4273   case tok::plusplus:   Opc = UO_PostInc; break;
4274   case tok::minusminus: Opc = UO_PostDec; break;
4275   }
4276 
4277   // Since this might is a postfix expression, get rid of ParenListExprs.
4278   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4279   if (Result.isInvalid()) return ExprError();
4280   Input = Result.get();
4281 
4282   return BuildUnaryOp(S, OpLoc, Opc, Input);
4283 }
4284 
4285 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4286 ///
4287 /// \return true on error
4288 static bool checkArithmeticOnObjCPointer(Sema &S,
4289                                          SourceLocation opLoc,
4290                                          Expr *op) {
4291   assert(op->getType()->isObjCObjectPointerType());
4292   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4293       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4294     return false;
4295 
4296   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4297     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4298     << op->getSourceRange();
4299   return true;
4300 }
4301 
4302 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4303   auto *BaseNoParens = Base->IgnoreParens();
4304   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4305     return MSProp->getPropertyDecl()->getType()->isArrayType();
4306   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4307 }
4308 
4309 ExprResult
4310 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4311                               Expr *idx, SourceLocation rbLoc) {
4312   if (base && !base->getType().isNull() &&
4313       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4314     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4315                                     /*Length=*/nullptr, rbLoc);
4316 
4317   // Since this might be a postfix expression, get rid of ParenListExprs.
4318   if (isa<ParenListExpr>(base)) {
4319     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4320     if (result.isInvalid()) return ExprError();
4321     base = result.get();
4322   }
4323 
4324   // Handle any non-overload placeholder types in the base and index
4325   // expressions.  We can't handle overloads here because the other
4326   // operand might be an overloadable type, in which case the overload
4327   // resolution for the operator overload should get the first crack
4328   // at the overload.
4329   bool IsMSPropertySubscript = false;
4330   if (base->getType()->isNonOverloadPlaceholderType()) {
4331     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4332     if (!IsMSPropertySubscript) {
4333       ExprResult result = CheckPlaceholderExpr(base);
4334       if (result.isInvalid())
4335         return ExprError();
4336       base = result.get();
4337     }
4338   }
4339   if (idx->getType()->isNonOverloadPlaceholderType()) {
4340     ExprResult result = CheckPlaceholderExpr(idx);
4341     if (result.isInvalid()) return ExprError();
4342     idx = result.get();
4343   }
4344 
4345   // Build an unanalyzed expression if either operand is type-dependent.
4346   if (getLangOpts().CPlusPlus &&
4347       (base->isTypeDependent() || idx->isTypeDependent())) {
4348     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4349                                             VK_LValue, OK_Ordinary, rbLoc);
4350   }
4351 
4352   // MSDN, property (C++)
4353   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4354   // This attribute can also be used in the declaration of an empty array in a
4355   // class or structure definition. For example:
4356   // __declspec(property(get=GetX, put=PutX)) int x[];
4357   // The above statement indicates that x[] can be used with one or more array
4358   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4359   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4360   if (IsMSPropertySubscript) {
4361     // Build MS property subscript expression if base is MS property reference
4362     // or MS property subscript.
4363     return new (Context) MSPropertySubscriptExpr(
4364         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4365   }
4366 
4367   // Use C++ overloaded-operator rules if either operand has record
4368   // type.  The spec says to do this if either type is *overloadable*,
4369   // but enum types can't declare subscript operators or conversion
4370   // operators, so there's nothing interesting for overload resolution
4371   // to do if there aren't any record types involved.
4372   //
4373   // ObjC pointers have their own subscripting logic that is not tied
4374   // to overload resolution and so should not take this path.
4375   if (getLangOpts().CPlusPlus &&
4376       (base->getType()->isRecordType() ||
4377        (!base->getType()->isObjCObjectPointerType() &&
4378         idx->getType()->isRecordType()))) {
4379     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4380   }
4381 
4382   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4383 
4384   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4385     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4386 
4387   return Res;
4388 }
4389 
4390 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4391   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4392   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4393 
4394   // For expressions like `&(*s).b`, the base is recorded and what should be
4395   // checked.
4396   const MemberExpr *Member = nullptr;
4397   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4398     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4399 
4400   LastRecord.PossibleDerefs.erase(StrippedExpr);
4401 }
4402 
4403 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4404   QualType ResultTy = E->getType();
4405   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4406 
4407   // Bail if the element is an array since it is not memory access.
4408   if (isa<ArrayType>(ResultTy))
4409     return;
4410 
4411   if (ResultTy->hasAttr(attr::NoDeref)) {
4412     LastRecord.PossibleDerefs.insert(E);
4413     return;
4414   }
4415 
4416   // Check if the base type is a pointer to a member access of a struct
4417   // marked with noderef.
4418   const Expr *Base = E->getBase();
4419   QualType BaseTy = Base->getType();
4420   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4421     // Not a pointer access
4422     return;
4423 
4424   const MemberExpr *Member = nullptr;
4425   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4426          Member->isArrow())
4427     Base = Member->getBase();
4428 
4429   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4430     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4431       LastRecord.PossibleDerefs.insert(E);
4432   }
4433 }
4434 
4435 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4436                                           Expr *LowerBound,
4437                                           SourceLocation ColonLoc, Expr *Length,
4438                                           SourceLocation RBLoc) {
4439   if (Base->getType()->isPlaceholderType() &&
4440       !Base->getType()->isSpecificPlaceholderType(
4441           BuiltinType::OMPArraySection)) {
4442     ExprResult Result = CheckPlaceholderExpr(Base);
4443     if (Result.isInvalid())
4444       return ExprError();
4445     Base = Result.get();
4446   }
4447   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4448     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4449     if (Result.isInvalid())
4450       return ExprError();
4451     Result = DefaultLvalueConversion(Result.get());
4452     if (Result.isInvalid())
4453       return ExprError();
4454     LowerBound = Result.get();
4455   }
4456   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4457     ExprResult Result = CheckPlaceholderExpr(Length);
4458     if (Result.isInvalid())
4459       return ExprError();
4460     Result = DefaultLvalueConversion(Result.get());
4461     if (Result.isInvalid())
4462       return ExprError();
4463     Length = Result.get();
4464   }
4465 
4466   // Build an unanalyzed expression if either operand is type-dependent.
4467   if (Base->isTypeDependent() ||
4468       (LowerBound &&
4469        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4470       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4471     return new (Context)
4472         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4473                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4474   }
4475 
4476   // Perform default conversions.
4477   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4478   QualType ResultTy;
4479   if (OriginalTy->isAnyPointerType()) {
4480     ResultTy = OriginalTy->getPointeeType();
4481   } else if (OriginalTy->isArrayType()) {
4482     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4483   } else {
4484     return ExprError(
4485         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4486         << Base->getSourceRange());
4487   }
4488   // C99 6.5.2.1p1
4489   if (LowerBound) {
4490     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4491                                                       LowerBound);
4492     if (Res.isInvalid())
4493       return ExprError(Diag(LowerBound->getExprLoc(),
4494                             diag::err_omp_typecheck_section_not_integer)
4495                        << 0 << LowerBound->getSourceRange());
4496     LowerBound = Res.get();
4497 
4498     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4499         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4500       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4501           << 0 << LowerBound->getSourceRange();
4502   }
4503   if (Length) {
4504     auto Res =
4505         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4506     if (Res.isInvalid())
4507       return ExprError(Diag(Length->getExprLoc(),
4508                             diag::err_omp_typecheck_section_not_integer)
4509                        << 1 << Length->getSourceRange());
4510     Length = Res.get();
4511 
4512     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4513         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4514       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4515           << 1 << Length->getSourceRange();
4516   }
4517 
4518   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4519   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4520   // type. Note that functions are not objects, and that (in C99 parlance)
4521   // incomplete types are not object types.
4522   if (ResultTy->isFunctionType()) {
4523     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4524         << ResultTy << Base->getSourceRange();
4525     return ExprError();
4526   }
4527 
4528   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4529                           diag::err_omp_section_incomplete_type, Base))
4530     return ExprError();
4531 
4532   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4533     Expr::EvalResult Result;
4534     if (LowerBound->EvaluateAsInt(Result, Context)) {
4535       // OpenMP 4.5, [2.4 Array Sections]
4536       // The array section must be a subset of the original array.
4537       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4538       if (LowerBoundValue.isNegative()) {
4539         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4540             << LowerBound->getSourceRange();
4541         return ExprError();
4542       }
4543     }
4544   }
4545 
4546   if (Length) {
4547     Expr::EvalResult Result;
4548     if (Length->EvaluateAsInt(Result, Context)) {
4549       // OpenMP 4.5, [2.4 Array Sections]
4550       // The length must evaluate to non-negative integers.
4551       llvm::APSInt LengthValue = Result.Val.getInt();
4552       if (LengthValue.isNegative()) {
4553         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4554             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4555             << Length->getSourceRange();
4556         return ExprError();
4557       }
4558     }
4559   } else if (ColonLoc.isValid() &&
4560              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4561                                       !OriginalTy->isVariableArrayType()))) {
4562     // OpenMP 4.5, [2.4 Array Sections]
4563     // When the size of the array dimension is not known, the length must be
4564     // specified explicitly.
4565     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4566         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4567     return ExprError();
4568   }
4569 
4570   if (!Base->getType()->isSpecificPlaceholderType(
4571           BuiltinType::OMPArraySection)) {
4572     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4573     if (Result.isInvalid())
4574       return ExprError();
4575     Base = Result.get();
4576   }
4577   return new (Context)
4578       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4579                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4580 }
4581 
4582 ExprResult
4583 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4584                                       Expr *Idx, SourceLocation RLoc) {
4585   Expr *LHSExp = Base;
4586   Expr *RHSExp = Idx;
4587 
4588   ExprValueKind VK = VK_LValue;
4589   ExprObjectKind OK = OK_Ordinary;
4590 
4591   // Per C++ core issue 1213, the result is an xvalue if either operand is
4592   // a non-lvalue array, and an lvalue otherwise.
4593   if (getLangOpts().CPlusPlus11) {
4594     for (auto *Op : {LHSExp, RHSExp}) {
4595       Op = Op->IgnoreImplicit();
4596       if (Op->getType()->isArrayType() && !Op->isLValue())
4597         VK = VK_XValue;
4598     }
4599   }
4600 
4601   // Perform default conversions.
4602   if (!LHSExp->getType()->getAs<VectorType>()) {
4603     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4604     if (Result.isInvalid())
4605       return ExprError();
4606     LHSExp = Result.get();
4607   }
4608   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4609   if (Result.isInvalid())
4610     return ExprError();
4611   RHSExp = Result.get();
4612 
4613   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4614 
4615   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4616   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4617   // in the subscript position. As a result, we need to derive the array base
4618   // and index from the expression types.
4619   Expr *BaseExpr, *IndexExpr;
4620   QualType ResultType;
4621   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4622     BaseExpr = LHSExp;
4623     IndexExpr = RHSExp;
4624     ResultType = Context.DependentTy;
4625   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4626     BaseExpr = LHSExp;
4627     IndexExpr = RHSExp;
4628     ResultType = PTy->getPointeeType();
4629   } else if (const ObjCObjectPointerType *PTy =
4630                LHSTy->getAs<ObjCObjectPointerType>()) {
4631     BaseExpr = LHSExp;
4632     IndexExpr = RHSExp;
4633 
4634     // Use custom logic if this should be the pseudo-object subscript
4635     // expression.
4636     if (!LangOpts.isSubscriptPointerArithmetic())
4637       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4638                                           nullptr);
4639 
4640     ResultType = PTy->getPointeeType();
4641   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4642      // Handle the uncommon case of "123[Ptr]".
4643     BaseExpr = RHSExp;
4644     IndexExpr = LHSExp;
4645     ResultType = PTy->getPointeeType();
4646   } else if (const ObjCObjectPointerType *PTy =
4647                RHSTy->getAs<ObjCObjectPointerType>()) {
4648      // Handle the uncommon case of "123[Ptr]".
4649     BaseExpr = RHSExp;
4650     IndexExpr = LHSExp;
4651     ResultType = PTy->getPointeeType();
4652     if (!LangOpts.isSubscriptPointerArithmetic()) {
4653       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4654         << ResultType << BaseExpr->getSourceRange();
4655       return ExprError();
4656     }
4657   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4658     BaseExpr = LHSExp;    // vectors: V[123]
4659     IndexExpr = RHSExp;
4660     // We apply C++ DR1213 to vector subscripting too.
4661     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4662       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4663       if (Materialized.isInvalid())
4664         return ExprError();
4665       LHSExp = Materialized.get();
4666     }
4667     VK = LHSExp->getValueKind();
4668     if (VK != VK_RValue)
4669       OK = OK_VectorComponent;
4670 
4671     ResultType = VTy->getElementType();
4672     QualType BaseType = BaseExpr->getType();
4673     Qualifiers BaseQuals = BaseType.getQualifiers();
4674     Qualifiers MemberQuals = ResultType.getQualifiers();
4675     Qualifiers Combined = BaseQuals + MemberQuals;
4676     if (Combined != MemberQuals)
4677       ResultType = Context.getQualifiedType(ResultType, Combined);
4678   } else if (LHSTy->isArrayType()) {
4679     // If we see an array that wasn't promoted by
4680     // DefaultFunctionArrayLvalueConversion, it must be an array that
4681     // wasn't promoted because of the C90 rule that doesn't
4682     // allow promoting non-lvalue arrays.  Warn, then
4683     // force the promotion here.
4684     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4685         << LHSExp->getSourceRange();
4686     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4687                                CK_ArrayToPointerDecay).get();
4688     LHSTy = LHSExp->getType();
4689 
4690     BaseExpr = LHSExp;
4691     IndexExpr = RHSExp;
4692     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4693   } else if (RHSTy->isArrayType()) {
4694     // Same as previous, except for 123[f().a] case
4695     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4696         << RHSExp->getSourceRange();
4697     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4698                                CK_ArrayToPointerDecay).get();
4699     RHSTy = RHSExp->getType();
4700 
4701     BaseExpr = RHSExp;
4702     IndexExpr = LHSExp;
4703     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4704   } else {
4705     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4706        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4707   }
4708   // C99 6.5.2.1p1
4709   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4710     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4711                      << IndexExpr->getSourceRange());
4712 
4713   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4714        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4715          && !IndexExpr->isTypeDependent())
4716     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4717 
4718   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4719   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4720   // type. Note that Functions are not objects, and that (in C99 parlance)
4721   // incomplete types are not object types.
4722   if (ResultType->isFunctionType()) {
4723     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4724         << ResultType << BaseExpr->getSourceRange();
4725     return ExprError();
4726   }
4727 
4728   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4729     // GNU extension: subscripting on pointer to void
4730     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4731       << BaseExpr->getSourceRange();
4732 
4733     // C forbids expressions of unqualified void type from being l-values.
4734     // See IsCForbiddenLValueType.
4735     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4736   } else if (!ResultType->isDependentType() &&
4737       RequireCompleteType(LLoc, ResultType,
4738                           diag::err_subscript_incomplete_type, BaseExpr))
4739     return ExprError();
4740 
4741   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4742          !ResultType.isCForbiddenLValueType());
4743 
4744   return new (Context)
4745       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4746 }
4747 
4748 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4749                                   ParmVarDecl *Param) {
4750   if (Param->hasUnparsedDefaultArg()) {
4751     Diag(CallLoc,
4752          diag::err_use_of_default_argument_to_function_declared_later) <<
4753       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4754     Diag(UnparsedDefaultArgLocs[Param],
4755          diag::note_default_argument_declared_here);
4756     return true;
4757   }
4758 
4759   if (Param->hasUninstantiatedDefaultArg()) {
4760     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4761 
4762     EnterExpressionEvaluationContext EvalContext(
4763         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4764 
4765     // Instantiate the expression.
4766     //
4767     // FIXME: Pass in a correct Pattern argument, otherwise
4768     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4769     //
4770     // template<typename T>
4771     // struct A {
4772     //   static int FooImpl();
4773     //
4774     //   template<typename Tp>
4775     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4776     //   // template argument list [[T], [Tp]], should be [[Tp]].
4777     //   friend A<Tp> Foo(int a);
4778     // };
4779     //
4780     // template<typename T>
4781     // A<T> Foo(int a = A<T>::FooImpl());
4782     MultiLevelTemplateArgumentList MutiLevelArgList
4783       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4784 
4785     InstantiatingTemplate Inst(*this, CallLoc, Param,
4786                                MutiLevelArgList.getInnermost());
4787     if (Inst.isInvalid())
4788       return true;
4789     if (Inst.isAlreadyInstantiating()) {
4790       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4791       Param->setInvalidDecl();
4792       return true;
4793     }
4794 
4795     ExprResult Result;
4796     {
4797       // C++ [dcl.fct.default]p5:
4798       //   The names in the [default argument] expression are bound, and
4799       //   the semantic constraints are checked, at the point where the
4800       //   default argument expression appears.
4801       ContextRAII SavedContext(*this, FD);
4802       LocalInstantiationScope Local(*this);
4803       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4804                                 /*DirectInit*/false);
4805     }
4806     if (Result.isInvalid())
4807       return true;
4808 
4809     // Check the expression as an initializer for the parameter.
4810     InitializedEntity Entity
4811       = InitializedEntity::InitializeParameter(Context, Param);
4812     InitializationKind Kind = InitializationKind::CreateCopy(
4813         Param->getLocation(),
4814         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4815     Expr *ResultE = Result.getAs<Expr>();
4816 
4817     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4818     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4819     if (Result.isInvalid())
4820       return true;
4821 
4822     Result =
4823         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4824                             /*DiscardedValue*/ false);
4825     if (Result.isInvalid())
4826       return true;
4827 
4828     // Remember the instantiated default argument.
4829     Param->setDefaultArg(Result.getAs<Expr>());
4830     if (ASTMutationListener *L = getASTMutationListener()) {
4831       L->DefaultArgumentInstantiated(Param);
4832     }
4833   }
4834 
4835   // If the default argument expression is not set yet, we are building it now.
4836   if (!Param->hasInit()) {
4837     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4838     Param->setInvalidDecl();
4839     return true;
4840   }
4841 
4842   // If the default expression creates temporaries, we need to
4843   // push them to the current stack of expression temporaries so they'll
4844   // be properly destroyed.
4845   // FIXME: We should really be rebuilding the default argument with new
4846   // bound temporaries; see the comment in PR5810.
4847   // We don't need to do that with block decls, though, because
4848   // blocks in default argument expression can never capture anything.
4849   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4850     // Set the "needs cleanups" bit regardless of whether there are
4851     // any explicit objects.
4852     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4853 
4854     // Append all the objects to the cleanup list.  Right now, this
4855     // should always be a no-op, because blocks in default argument
4856     // expressions should never be able to capture anything.
4857     assert(!Init->getNumObjects() &&
4858            "default argument expression has capturing blocks?");
4859   }
4860 
4861   // We already type-checked the argument, so we know it works.
4862   // Just mark all of the declarations in this potentially-evaluated expression
4863   // as being "referenced".
4864   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4865                                    /*SkipLocalVariables=*/true);
4866   return false;
4867 }
4868 
4869 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4870                                         FunctionDecl *FD, ParmVarDecl *Param) {
4871   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4872     return ExprError();
4873   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4874 }
4875 
4876 Sema::VariadicCallType
4877 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4878                           Expr *Fn) {
4879   if (Proto && Proto->isVariadic()) {
4880     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4881       return VariadicConstructor;
4882     else if (Fn && Fn->getType()->isBlockPointerType())
4883       return VariadicBlock;
4884     else if (FDecl) {
4885       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4886         if (Method->isInstance())
4887           return VariadicMethod;
4888     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4889       return VariadicMethod;
4890     return VariadicFunction;
4891   }
4892   return VariadicDoesNotApply;
4893 }
4894 
4895 namespace {
4896 class FunctionCallCCC : public FunctionCallFilterCCC {
4897 public:
4898   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4899                   unsigned NumArgs, MemberExpr *ME)
4900       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4901         FunctionName(FuncName) {}
4902 
4903   bool ValidateCandidate(const TypoCorrection &candidate) override {
4904     if (!candidate.getCorrectionSpecifier() ||
4905         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4906       return false;
4907     }
4908 
4909     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4910   }
4911 
4912 private:
4913   const IdentifierInfo *const FunctionName;
4914 };
4915 }
4916 
4917 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4918                                                FunctionDecl *FDecl,
4919                                                ArrayRef<Expr *> Args) {
4920   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4921   DeclarationName FuncName = FDecl->getDeclName();
4922   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4923 
4924   if (TypoCorrection Corrected = S.CorrectTypo(
4925           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4926           S.getScopeForContext(S.CurContext), nullptr,
4927           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4928                                              Args.size(), ME),
4929           Sema::CTK_ErrorRecovery)) {
4930     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4931       if (Corrected.isOverloaded()) {
4932         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4933         OverloadCandidateSet::iterator Best;
4934         for (NamedDecl *CD : Corrected) {
4935           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4936             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4937                                    OCS);
4938         }
4939         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4940         case OR_Success:
4941           ND = Best->FoundDecl;
4942           Corrected.setCorrectionDecl(ND);
4943           break;
4944         default:
4945           break;
4946         }
4947       }
4948       ND = ND->getUnderlyingDecl();
4949       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4950         return Corrected;
4951     }
4952   }
4953   return TypoCorrection();
4954 }
4955 
4956 /// ConvertArgumentsForCall - Converts the arguments specified in
4957 /// Args/NumArgs to the parameter types of the function FDecl with
4958 /// function prototype Proto. Call is the call expression itself, and
4959 /// Fn is the function expression. For a C++ member function, this
4960 /// routine does not attempt to convert the object argument. Returns
4961 /// true if the call is ill-formed.
4962 bool
4963 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4964                               FunctionDecl *FDecl,
4965                               const FunctionProtoType *Proto,
4966                               ArrayRef<Expr *> Args,
4967                               SourceLocation RParenLoc,
4968                               bool IsExecConfig) {
4969   // Bail out early if calling a builtin with custom typechecking.
4970   if (FDecl)
4971     if (unsigned ID = FDecl->getBuiltinID())
4972       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4973         return false;
4974 
4975   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4976   // assignment, to the types of the corresponding parameter, ...
4977   unsigned NumParams = Proto->getNumParams();
4978   bool Invalid = false;
4979   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4980   unsigned FnKind = Fn->getType()->isBlockPointerType()
4981                        ? 1 /* block */
4982                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4983                                        : 0 /* function */);
4984 
4985   // If too few arguments are available (and we don't have default
4986   // arguments for the remaining parameters), don't make the call.
4987   if (Args.size() < NumParams) {
4988     if (Args.size() < MinArgs) {
4989       TypoCorrection TC;
4990       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4991         unsigned diag_id =
4992             MinArgs == NumParams && !Proto->isVariadic()
4993                 ? diag::err_typecheck_call_too_few_args_suggest
4994                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4995         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4996                                         << static_cast<unsigned>(Args.size())
4997                                         << TC.getCorrectionRange());
4998       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4999         Diag(RParenLoc,
5000              MinArgs == NumParams && !Proto->isVariadic()
5001                  ? diag::err_typecheck_call_too_few_args_one
5002                  : diag::err_typecheck_call_too_few_args_at_least_one)
5003             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5004       else
5005         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5006                             ? diag::err_typecheck_call_too_few_args
5007                             : diag::err_typecheck_call_too_few_args_at_least)
5008             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5009             << Fn->getSourceRange();
5010 
5011       // Emit the location of the prototype.
5012       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5013         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5014 
5015       return true;
5016     }
5017     // We reserve space for the default arguments when we create
5018     // the call expression, before calling ConvertArgumentsForCall.
5019     assert((Call->getNumArgs() == NumParams) &&
5020            "We should have reserved space for the default arguments before!");
5021   }
5022 
5023   // If too many are passed and not variadic, error on the extras and drop
5024   // them.
5025   if (Args.size() > NumParams) {
5026     if (!Proto->isVariadic()) {
5027       TypoCorrection TC;
5028       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5029         unsigned diag_id =
5030             MinArgs == NumParams && !Proto->isVariadic()
5031                 ? diag::err_typecheck_call_too_many_args_suggest
5032                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5033         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5034                                         << static_cast<unsigned>(Args.size())
5035                                         << TC.getCorrectionRange());
5036       } else if (NumParams == 1 && FDecl &&
5037                  FDecl->getParamDecl(0)->getDeclName())
5038         Diag(Args[NumParams]->getBeginLoc(),
5039              MinArgs == NumParams
5040                  ? diag::err_typecheck_call_too_many_args_one
5041                  : diag::err_typecheck_call_too_many_args_at_most_one)
5042             << FnKind << FDecl->getParamDecl(0)
5043             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5044             << SourceRange(Args[NumParams]->getBeginLoc(),
5045                            Args.back()->getEndLoc());
5046       else
5047         Diag(Args[NumParams]->getBeginLoc(),
5048              MinArgs == NumParams
5049                  ? diag::err_typecheck_call_too_many_args
5050                  : diag::err_typecheck_call_too_many_args_at_most)
5051             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5052             << Fn->getSourceRange()
5053             << SourceRange(Args[NumParams]->getBeginLoc(),
5054                            Args.back()->getEndLoc());
5055 
5056       // Emit the location of the prototype.
5057       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5058         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5059 
5060       // This deletes the extra arguments.
5061       Call->shrinkNumArgs(NumParams);
5062       return true;
5063     }
5064   }
5065   SmallVector<Expr *, 8> AllArgs;
5066   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5067 
5068   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5069                                    AllArgs, CallType);
5070   if (Invalid)
5071     return true;
5072   unsigned TotalNumArgs = AllArgs.size();
5073   for (unsigned i = 0; i < TotalNumArgs; ++i)
5074     Call->setArg(i, AllArgs[i]);
5075 
5076   return false;
5077 }
5078 
5079 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5080                                   const FunctionProtoType *Proto,
5081                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5082                                   SmallVectorImpl<Expr *> &AllArgs,
5083                                   VariadicCallType CallType, bool AllowExplicit,
5084                                   bool IsListInitialization) {
5085   unsigned NumParams = Proto->getNumParams();
5086   bool Invalid = false;
5087   size_t ArgIx = 0;
5088   // Continue to check argument types (even if we have too few/many args).
5089   for (unsigned i = FirstParam; i < NumParams; i++) {
5090     QualType ProtoArgType = Proto->getParamType(i);
5091 
5092     Expr *Arg;
5093     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5094     if (ArgIx < Args.size()) {
5095       Arg = Args[ArgIx++];
5096 
5097       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5098                               diag::err_call_incomplete_argument, Arg))
5099         return true;
5100 
5101       // Strip the unbridged-cast placeholder expression off, if applicable.
5102       bool CFAudited = false;
5103       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5104           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5105           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5106         Arg = stripARCUnbridgedCast(Arg);
5107       else if (getLangOpts().ObjCAutoRefCount &&
5108                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5109                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5110         CFAudited = true;
5111 
5112       if (Proto->getExtParameterInfo(i).isNoEscape())
5113         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5114           BE->getBlockDecl()->setDoesNotEscape();
5115 
5116       InitializedEntity Entity =
5117           Param ? InitializedEntity::InitializeParameter(Context, Param,
5118                                                          ProtoArgType)
5119                 : InitializedEntity::InitializeParameter(
5120                       Context, ProtoArgType, Proto->isParamConsumed(i));
5121 
5122       // Remember that parameter belongs to a CF audited API.
5123       if (CFAudited)
5124         Entity.setParameterCFAudited();
5125 
5126       ExprResult ArgE = PerformCopyInitialization(
5127           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5128       if (ArgE.isInvalid())
5129         return true;
5130 
5131       Arg = ArgE.getAs<Expr>();
5132     } else {
5133       assert(Param && "can't use default arguments without a known callee");
5134 
5135       ExprResult ArgExpr =
5136         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5137       if (ArgExpr.isInvalid())
5138         return true;
5139 
5140       Arg = ArgExpr.getAs<Expr>();
5141     }
5142 
5143     // Check for array bounds violations for each argument to the call. This
5144     // check only triggers warnings when the argument isn't a more complex Expr
5145     // with its own checking, such as a BinaryOperator.
5146     CheckArrayAccess(Arg);
5147 
5148     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5149     CheckStaticArrayArgument(CallLoc, Param, Arg);
5150 
5151     AllArgs.push_back(Arg);
5152   }
5153 
5154   // If this is a variadic call, handle args passed through "...".
5155   if (CallType != VariadicDoesNotApply) {
5156     // Assume that extern "C" functions with variadic arguments that
5157     // return __unknown_anytype aren't *really* variadic.
5158     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5159         FDecl->isExternC()) {
5160       for (Expr *A : Args.slice(ArgIx)) {
5161         QualType paramType; // ignored
5162         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5163         Invalid |= arg.isInvalid();
5164         AllArgs.push_back(arg.get());
5165       }
5166 
5167     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5168     } else {
5169       for (Expr *A : Args.slice(ArgIx)) {
5170         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5171         Invalid |= Arg.isInvalid();
5172         AllArgs.push_back(Arg.get());
5173       }
5174     }
5175 
5176     // Check for array bounds violations.
5177     for (Expr *A : Args.slice(ArgIx))
5178       CheckArrayAccess(A);
5179   }
5180   return Invalid;
5181 }
5182 
5183 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5184   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5185   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5186     TL = DTL.getOriginalLoc();
5187   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5188     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5189       << ATL.getLocalSourceRange();
5190 }
5191 
5192 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5193 /// array parameter, check that it is non-null, and that if it is formed by
5194 /// array-to-pointer decay, the underlying array is sufficiently large.
5195 ///
5196 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5197 /// array type derivation, then for each call to the function, the value of the
5198 /// corresponding actual argument shall provide access to the first element of
5199 /// an array with at least as many elements as specified by the size expression.
5200 void
5201 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5202                                ParmVarDecl *Param,
5203                                const Expr *ArgExpr) {
5204   // Static array parameters are not supported in C++.
5205   if (!Param || getLangOpts().CPlusPlus)
5206     return;
5207 
5208   QualType OrigTy = Param->getOriginalType();
5209 
5210   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5211   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5212     return;
5213 
5214   if (ArgExpr->isNullPointerConstant(Context,
5215                                      Expr::NPC_NeverValueDependent)) {
5216     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5217     DiagnoseCalleeStaticArrayParam(*this, Param);
5218     return;
5219   }
5220 
5221   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5222   if (!CAT)
5223     return;
5224 
5225   const ConstantArrayType *ArgCAT =
5226     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5227   if (!ArgCAT)
5228     return;
5229 
5230   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5231                                              ArgCAT->getElementType())) {
5232     if (ArgCAT->getSize().ult(CAT->getSize())) {
5233       Diag(CallLoc, diag::warn_static_array_too_small)
5234           << ArgExpr->getSourceRange()
5235           << (unsigned)ArgCAT->getSize().getZExtValue()
5236           << (unsigned)CAT->getSize().getZExtValue() << 0;
5237       DiagnoseCalleeStaticArrayParam(*this, Param);
5238     }
5239     return;
5240   }
5241 
5242   Optional<CharUnits> ArgSize =
5243       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5244   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5245   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5246     Diag(CallLoc, diag::warn_static_array_too_small)
5247         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5248         << (unsigned)ParmSize->getQuantity() << 1;
5249     DiagnoseCalleeStaticArrayParam(*this, Param);
5250   }
5251 }
5252 
5253 /// Given a function expression of unknown-any type, try to rebuild it
5254 /// to have a function type.
5255 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5256 
5257 /// Is the given type a placeholder that we need to lower out
5258 /// immediately during argument processing?
5259 static bool isPlaceholderToRemoveAsArg(QualType type) {
5260   // Placeholders are never sugared.
5261   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5262   if (!placeholder) return false;
5263 
5264   switch (placeholder->getKind()) {
5265   // Ignore all the non-placeholder types.
5266 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5267   case BuiltinType::Id:
5268 #include "clang/Basic/OpenCLImageTypes.def"
5269 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5270   case BuiltinType::Id:
5271 #include "clang/Basic/OpenCLExtensionTypes.def"
5272 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5273 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5274 #include "clang/AST/BuiltinTypes.def"
5275     return false;
5276 
5277   // We cannot lower out overload sets; they might validly be resolved
5278   // by the call machinery.
5279   case BuiltinType::Overload:
5280     return false;
5281 
5282   // Unbridged casts in ARC can be handled in some call positions and
5283   // should be left in place.
5284   case BuiltinType::ARCUnbridgedCast:
5285     return false;
5286 
5287   // Pseudo-objects should be converted as soon as possible.
5288   case BuiltinType::PseudoObject:
5289     return true;
5290 
5291   // The debugger mode could theoretically but currently does not try
5292   // to resolve unknown-typed arguments based on known parameter types.
5293   case BuiltinType::UnknownAny:
5294     return true;
5295 
5296   // These are always invalid as call arguments and should be reported.
5297   case BuiltinType::BoundMember:
5298   case BuiltinType::BuiltinFn:
5299   case BuiltinType::OMPArraySection:
5300     return true;
5301 
5302   }
5303   llvm_unreachable("bad builtin type kind");
5304 }
5305 
5306 /// Check an argument list for placeholders that we won't try to
5307 /// handle later.
5308 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5309   // Apply this processing to all the arguments at once instead of
5310   // dying at the first failure.
5311   bool hasInvalid = false;
5312   for (size_t i = 0, e = args.size(); i != e; i++) {
5313     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5314       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5315       if (result.isInvalid()) hasInvalid = true;
5316       else args[i] = result.get();
5317     } else if (hasInvalid) {
5318       (void)S.CorrectDelayedTyposInExpr(args[i]);
5319     }
5320   }
5321   return hasInvalid;
5322 }
5323 
5324 /// If a builtin function has a pointer argument with no explicit address
5325 /// space, then it should be able to accept a pointer to any address
5326 /// space as input.  In order to do this, we need to replace the
5327 /// standard builtin declaration with one that uses the same address space
5328 /// as the call.
5329 ///
5330 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5331 ///                  it does not contain any pointer arguments without
5332 ///                  an address space qualifer.  Otherwise the rewritten
5333 ///                  FunctionDecl is returned.
5334 /// TODO: Handle pointer return types.
5335 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5336                                                 const FunctionDecl *FDecl,
5337                                                 MultiExprArg ArgExprs) {
5338 
5339   QualType DeclType = FDecl->getType();
5340   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5341 
5342   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5343       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5344     return nullptr;
5345 
5346   bool NeedsNewDecl = false;
5347   unsigned i = 0;
5348   SmallVector<QualType, 8> OverloadParams;
5349 
5350   for (QualType ParamType : FT->param_types()) {
5351 
5352     // Convert array arguments to pointer to simplify type lookup.
5353     ExprResult ArgRes =
5354         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5355     if (ArgRes.isInvalid())
5356       return nullptr;
5357     Expr *Arg = ArgRes.get();
5358     QualType ArgType = Arg->getType();
5359     if (!ParamType->isPointerType() ||
5360         ParamType.getQualifiers().hasAddressSpace() ||
5361         !ArgType->isPointerType() ||
5362         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5363       OverloadParams.push_back(ParamType);
5364       continue;
5365     }
5366 
5367     QualType PointeeType = ParamType->getPointeeType();
5368     if (PointeeType.getQualifiers().hasAddressSpace())
5369       continue;
5370 
5371     NeedsNewDecl = true;
5372     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5373 
5374     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5375     OverloadParams.push_back(Context.getPointerType(PointeeType));
5376   }
5377 
5378   if (!NeedsNewDecl)
5379     return nullptr;
5380 
5381   FunctionProtoType::ExtProtoInfo EPI;
5382   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5383                                                 OverloadParams, EPI);
5384   DeclContext *Parent = Context.getTranslationUnitDecl();
5385   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5386                                                     FDecl->getLocation(),
5387                                                     FDecl->getLocation(),
5388                                                     FDecl->getIdentifier(),
5389                                                     OverloadTy,
5390                                                     /*TInfo=*/nullptr,
5391                                                     SC_Extern, false,
5392                                                     /*hasPrototype=*/true);
5393   SmallVector<ParmVarDecl*, 16> Params;
5394   FT = cast<FunctionProtoType>(OverloadTy);
5395   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5396     QualType ParamType = FT->getParamType(i);
5397     ParmVarDecl *Parm =
5398         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5399                                 SourceLocation(), nullptr, ParamType,
5400                                 /*TInfo=*/nullptr, SC_None, nullptr);
5401     Parm->setScopeInfo(0, i);
5402     Params.push_back(Parm);
5403   }
5404   OverloadDecl->setParams(Params);
5405   return OverloadDecl;
5406 }
5407 
5408 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5409                                     FunctionDecl *Callee,
5410                                     MultiExprArg ArgExprs) {
5411   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5412   // similar attributes) really don't like it when functions are called with an
5413   // invalid number of args.
5414   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5415                          /*PartialOverloading=*/false) &&
5416       !Callee->isVariadic())
5417     return;
5418   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5419     return;
5420 
5421   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5422     S.Diag(Fn->getBeginLoc(),
5423            isa<CXXMethodDecl>(Callee)
5424                ? diag::err_ovl_no_viable_member_function_in_call
5425                : diag::err_ovl_no_viable_function_in_call)
5426         << Callee << Callee->getSourceRange();
5427     S.Diag(Callee->getLocation(),
5428            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5429         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5430     return;
5431   }
5432 }
5433 
5434 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5435     const UnresolvedMemberExpr *const UME, Sema &S) {
5436 
5437   const auto GetFunctionLevelDCIfCXXClass =
5438       [](Sema &S) -> const CXXRecordDecl * {
5439     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5440     if (!DC || !DC->getParent())
5441       return nullptr;
5442 
5443     // If the call to some member function was made from within a member
5444     // function body 'M' return return 'M's parent.
5445     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5446       return MD->getParent()->getCanonicalDecl();
5447     // else the call was made from within a default member initializer of a
5448     // class, so return the class.
5449     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5450       return RD->getCanonicalDecl();
5451     return nullptr;
5452   };
5453   // If our DeclContext is neither a member function nor a class (in the
5454   // case of a lambda in a default member initializer), we can't have an
5455   // enclosing 'this'.
5456 
5457   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5458   if (!CurParentClass)
5459     return false;
5460 
5461   // The naming class for implicit member functions call is the class in which
5462   // name lookup starts.
5463   const CXXRecordDecl *const NamingClass =
5464       UME->getNamingClass()->getCanonicalDecl();
5465   assert(NamingClass && "Must have naming class even for implicit access");
5466 
5467   // If the unresolved member functions were found in a 'naming class' that is
5468   // related (either the same or derived from) to the class that contains the
5469   // member function that itself contained the implicit member access.
5470 
5471   return CurParentClass == NamingClass ||
5472          CurParentClass->isDerivedFrom(NamingClass);
5473 }
5474 
5475 static void
5476 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5477     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5478 
5479   if (!UME)
5480     return;
5481 
5482   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5483   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5484   // already been captured, or if this is an implicit member function call (if
5485   // it isn't, an attempt to capture 'this' should already have been made).
5486   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5487       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5488     return;
5489 
5490   // Check if the naming class in which the unresolved members were found is
5491   // related (same as or is a base of) to the enclosing class.
5492 
5493   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5494     return;
5495 
5496 
5497   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5498   // If the enclosing function is not dependent, then this lambda is
5499   // capture ready, so if we can capture this, do so.
5500   if (!EnclosingFunctionCtx->isDependentContext()) {
5501     // If the current lambda and all enclosing lambdas can capture 'this' -
5502     // then go ahead and capture 'this' (since our unresolved overload set
5503     // contains at least one non-static member function).
5504     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5505       S.CheckCXXThisCapture(CallLoc);
5506   } else if (S.CurContext->isDependentContext()) {
5507     // ... since this is an implicit member reference, that might potentially
5508     // involve a 'this' capture, mark 'this' for potential capture in
5509     // enclosing lambdas.
5510     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5511       CurLSI->addPotentialThisCapture(CallLoc);
5512   }
5513 }
5514 
5515 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5516 /// This provides the location of the left/right parens and a list of comma
5517 /// locations.
5518 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5519                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5520                                Expr *ExecConfig, bool IsExecConfig) {
5521   // Since this might be a postfix expression, get rid of ParenListExprs.
5522   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5523   if (Result.isInvalid()) return ExprError();
5524   Fn = Result.get();
5525 
5526   if (checkArgsForPlaceholders(*this, ArgExprs))
5527     return ExprError();
5528 
5529   if (getLangOpts().CPlusPlus) {
5530     // If this is a pseudo-destructor expression, build the call immediately.
5531     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5532       if (!ArgExprs.empty()) {
5533         // Pseudo-destructor calls should not have any arguments.
5534         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5535             << FixItHint::CreateRemoval(
5536                    SourceRange(ArgExprs.front()->getBeginLoc(),
5537                                ArgExprs.back()->getEndLoc()));
5538       }
5539 
5540       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5541                               VK_RValue, RParenLoc);
5542     }
5543     if (Fn->getType() == Context.PseudoObjectTy) {
5544       ExprResult result = CheckPlaceholderExpr(Fn);
5545       if (result.isInvalid()) return ExprError();
5546       Fn = result.get();
5547     }
5548 
5549     // Determine whether this is a dependent call inside a C++ template,
5550     // in which case we won't do any semantic analysis now.
5551     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5552       if (ExecConfig) {
5553         return CUDAKernelCallExpr::Create(
5554             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5555             Context.DependentTy, VK_RValue, RParenLoc);
5556       } else {
5557 
5558         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5559             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5560             Fn->getBeginLoc());
5561 
5562         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5563                                 VK_RValue, RParenLoc);
5564       }
5565     }
5566 
5567     // Determine whether this is a call to an object (C++ [over.call.object]).
5568     if (Fn->getType()->isRecordType())
5569       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5570                                           RParenLoc);
5571 
5572     if (Fn->getType() == Context.UnknownAnyTy) {
5573       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5574       if (result.isInvalid()) return ExprError();
5575       Fn = result.get();
5576     }
5577 
5578     if (Fn->getType() == Context.BoundMemberTy) {
5579       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5580                                        RParenLoc);
5581     }
5582   }
5583 
5584   // Check for overloaded calls.  This can happen even in C due to extensions.
5585   if (Fn->getType() == Context.OverloadTy) {
5586     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5587 
5588     // We aren't supposed to apply this logic if there's an '&' involved.
5589     if (!find.HasFormOfMemberPointer) {
5590       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5591         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5592                                 VK_RValue, RParenLoc);
5593       OverloadExpr *ovl = find.Expression;
5594       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5595         return BuildOverloadedCallExpr(
5596             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5597             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5598       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5599                                        RParenLoc);
5600     }
5601   }
5602 
5603   // If we're directly calling a function, get the appropriate declaration.
5604   if (Fn->getType() == Context.UnknownAnyTy) {
5605     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5606     if (result.isInvalid()) return ExprError();
5607     Fn = result.get();
5608   }
5609 
5610   Expr *NakedFn = Fn->IgnoreParens();
5611 
5612   bool CallingNDeclIndirectly = false;
5613   NamedDecl *NDecl = nullptr;
5614   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5615     if (UnOp->getOpcode() == UO_AddrOf) {
5616       CallingNDeclIndirectly = true;
5617       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5618     }
5619   }
5620 
5621   if (isa<DeclRefExpr>(NakedFn)) {
5622     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5623 
5624     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5625     if (FDecl && FDecl->getBuiltinID()) {
5626       // Rewrite the function decl for this builtin by replacing parameters
5627       // with no explicit address space with the address space of the arguments
5628       // in ArgExprs.
5629       if ((FDecl =
5630                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5631         NDecl = FDecl;
5632         Fn = DeclRefExpr::Create(
5633             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5634             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5635       }
5636     }
5637   } else if (isa<MemberExpr>(NakedFn))
5638     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5639 
5640   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5641     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5642                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5643       return ExprError();
5644 
5645     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5646       return ExprError();
5647 
5648     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5649   }
5650 
5651   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5652                                ExecConfig, IsExecConfig);
5653 }
5654 
5655 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5656 ///
5657 /// __builtin_astype( value, dst type )
5658 ///
5659 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5660                                  SourceLocation BuiltinLoc,
5661                                  SourceLocation RParenLoc) {
5662   ExprValueKind VK = VK_RValue;
5663   ExprObjectKind OK = OK_Ordinary;
5664   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5665   QualType SrcTy = E->getType();
5666   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5667     return ExprError(Diag(BuiltinLoc,
5668                           diag::err_invalid_astype_of_different_size)
5669                      << DstTy
5670                      << SrcTy
5671                      << E->getSourceRange());
5672   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5673 }
5674 
5675 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5676 /// provided arguments.
5677 ///
5678 /// __builtin_convertvector( value, dst type )
5679 ///
5680 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5681                                         SourceLocation BuiltinLoc,
5682                                         SourceLocation RParenLoc) {
5683   TypeSourceInfo *TInfo;
5684   GetTypeFromParser(ParsedDestTy, &TInfo);
5685   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5686 }
5687 
5688 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5689 /// i.e. an expression not of \p OverloadTy.  The expression should
5690 /// unary-convert to an expression of function-pointer or
5691 /// block-pointer type.
5692 ///
5693 /// \param NDecl the declaration being called, if available
5694 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5695                                        SourceLocation LParenLoc,
5696                                        ArrayRef<Expr *> Args,
5697                                        SourceLocation RParenLoc, Expr *Config,
5698                                        bool IsExecConfig, ADLCallKind UsesADL) {
5699   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5700   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5701 
5702   // Functions with 'interrupt' attribute cannot be called directly.
5703   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5704     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5705     return ExprError();
5706   }
5707 
5708   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5709   // so there's some risk when calling out to non-interrupt handler functions
5710   // that the callee might not preserve them. This is easy to diagnose here,
5711   // but can be very challenging to debug.
5712   if (auto *Caller = getCurFunctionDecl())
5713     if (Caller->hasAttr<ARMInterruptAttr>()) {
5714       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5715       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5716         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5717     }
5718 
5719   // Promote the function operand.
5720   // We special-case function promotion here because we only allow promoting
5721   // builtin functions to function pointers in the callee of a call.
5722   ExprResult Result;
5723   QualType ResultTy;
5724   if (BuiltinID &&
5725       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5726     // Extract the return type from the (builtin) function pointer type.
5727     // FIXME Several builtins still have setType in
5728     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5729     // Builtins.def to ensure they are correct before removing setType calls.
5730     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5731     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5732     ResultTy = FDecl->getCallResultType();
5733   } else {
5734     Result = CallExprUnaryConversions(Fn);
5735     ResultTy = Context.BoolTy;
5736   }
5737   if (Result.isInvalid())
5738     return ExprError();
5739   Fn = Result.get();
5740 
5741   // Check for a valid function type, but only if it is not a builtin which
5742   // requires custom type checking. These will be handled by
5743   // CheckBuiltinFunctionCall below just after creation of the call expression.
5744   const FunctionType *FuncT = nullptr;
5745   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5746    retry:
5747     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5748       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5749       // have type pointer to function".
5750       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5751       if (!FuncT)
5752         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5753                            << Fn->getType() << Fn->getSourceRange());
5754     } else if (const BlockPointerType *BPT =
5755                  Fn->getType()->getAs<BlockPointerType>()) {
5756       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5757     } else {
5758       // Handle calls to expressions of unknown-any type.
5759       if (Fn->getType() == Context.UnknownAnyTy) {
5760         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5761         if (rewrite.isInvalid()) return ExprError();
5762         Fn = rewrite.get();
5763         goto retry;
5764       }
5765 
5766     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5767       << Fn->getType() << Fn->getSourceRange());
5768     }
5769   }
5770 
5771   // Get the number of parameters in the function prototype, if any.
5772   // We will allocate space for max(Args.size(), NumParams) arguments
5773   // in the call expression.
5774   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5775   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5776 
5777   CallExpr *TheCall;
5778   if (Config) {
5779     assert(UsesADL == ADLCallKind::NotADL &&
5780            "CUDAKernelCallExpr should not use ADL");
5781     TheCall =
5782         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5783                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5784   } else {
5785     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5786                                RParenLoc, NumParams, UsesADL);
5787   }
5788 
5789   if (!getLangOpts().CPlusPlus) {
5790     // Forget about the nulled arguments since typo correction
5791     // do not handle them well.
5792     TheCall->shrinkNumArgs(Args.size());
5793     // C cannot always handle TypoExpr nodes in builtin calls and direct
5794     // function calls as their argument checking don't necessarily handle
5795     // dependent types properly, so make sure any TypoExprs have been
5796     // dealt with.
5797     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5798     if (!Result.isUsable()) return ExprError();
5799     CallExpr *TheOldCall = TheCall;
5800     TheCall = dyn_cast<CallExpr>(Result.get());
5801     bool CorrectedTypos = TheCall != TheOldCall;
5802     if (!TheCall) return Result;
5803     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5804 
5805     // A new call expression node was created if some typos were corrected.
5806     // However it may not have been constructed with enough storage. In this
5807     // case, rebuild the node with enough storage. The waste of space is
5808     // immaterial since this only happens when some typos were corrected.
5809     if (CorrectedTypos && Args.size() < NumParams) {
5810       if (Config)
5811         TheCall = CUDAKernelCallExpr::Create(
5812             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5813             RParenLoc, NumParams);
5814       else
5815         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5816                                    RParenLoc, NumParams, UsesADL);
5817     }
5818     // We can now handle the nulled arguments for the default arguments.
5819     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5820   }
5821 
5822   // Bail out early if calling a builtin with custom type checking.
5823   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5824     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5825 
5826   if (getLangOpts().CUDA) {
5827     if (Config) {
5828       // CUDA: Kernel calls must be to global functions
5829       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5830         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5831             << FDecl << Fn->getSourceRange());
5832 
5833       // CUDA: Kernel function must have 'void' return type
5834       if (!FuncT->getReturnType()->isVoidType())
5835         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5836             << Fn->getType() << Fn->getSourceRange());
5837     } else {
5838       // CUDA: Calls to global functions must be configured
5839       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5840         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5841             << FDecl << Fn->getSourceRange());
5842     }
5843   }
5844 
5845   // Check for a valid return type
5846   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5847                           FDecl))
5848     return ExprError();
5849 
5850   // We know the result type of the call, set it.
5851   TheCall->setType(FuncT->getCallResultType(Context));
5852   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5853 
5854   if (Proto) {
5855     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5856                                 IsExecConfig))
5857       return ExprError();
5858   } else {
5859     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5860 
5861     if (FDecl) {
5862       // Check if we have too few/too many template arguments, based
5863       // on our knowledge of the function definition.
5864       const FunctionDecl *Def = nullptr;
5865       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5866         Proto = Def->getType()->getAs<FunctionProtoType>();
5867        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5868           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5869           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5870       }
5871 
5872       // If the function we're calling isn't a function prototype, but we have
5873       // a function prototype from a prior declaratiom, use that prototype.
5874       if (!FDecl->hasPrototype())
5875         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5876     }
5877 
5878     // Promote the arguments (C99 6.5.2.2p6).
5879     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5880       Expr *Arg = Args[i];
5881 
5882       if (Proto && i < Proto->getNumParams()) {
5883         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5884             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5885         ExprResult ArgE =
5886             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5887         if (ArgE.isInvalid())
5888           return true;
5889 
5890         Arg = ArgE.getAs<Expr>();
5891 
5892       } else {
5893         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5894 
5895         if (ArgE.isInvalid())
5896           return true;
5897 
5898         Arg = ArgE.getAs<Expr>();
5899       }
5900 
5901       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5902                               diag::err_call_incomplete_argument, Arg))
5903         return ExprError();
5904 
5905       TheCall->setArg(i, Arg);
5906     }
5907   }
5908 
5909   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5910     if (!Method->isStatic())
5911       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5912         << Fn->getSourceRange());
5913 
5914   // Check for sentinels
5915   if (NDecl)
5916     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5917 
5918   // Do special checking on direct calls to functions.
5919   if (FDecl) {
5920     if (CheckFunctionCall(FDecl, TheCall, Proto))
5921       return ExprError();
5922 
5923     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5924 
5925     if (BuiltinID)
5926       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5927   } else if (NDecl) {
5928     if (CheckPointerCall(NDecl, TheCall, Proto))
5929       return ExprError();
5930   } else {
5931     if (CheckOtherCall(TheCall, Proto))
5932       return ExprError();
5933   }
5934 
5935   return MaybeBindToTemporary(TheCall);
5936 }
5937 
5938 ExprResult
5939 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5940                            SourceLocation RParenLoc, Expr *InitExpr) {
5941   assert(Ty && "ActOnCompoundLiteral(): missing type");
5942   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5943 
5944   TypeSourceInfo *TInfo;
5945   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5946   if (!TInfo)
5947     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5948 
5949   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5950 }
5951 
5952 ExprResult
5953 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5954                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5955   QualType literalType = TInfo->getType();
5956 
5957   if (literalType->isArrayType()) {
5958     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5959           diag::err_illegal_decl_array_incomplete_type,
5960           SourceRange(LParenLoc,
5961                       LiteralExpr->getSourceRange().getEnd())))
5962       return ExprError();
5963     if (literalType->isVariableArrayType())
5964       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5965         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5966   } else if (!literalType->isDependentType() &&
5967              RequireCompleteType(LParenLoc, literalType,
5968                diag::err_typecheck_decl_incomplete_type,
5969                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5970     return ExprError();
5971 
5972   InitializedEntity Entity
5973     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5974   InitializationKind Kind
5975     = InitializationKind::CreateCStyleCast(LParenLoc,
5976                                            SourceRange(LParenLoc, RParenLoc),
5977                                            /*InitList=*/true);
5978   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5979   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5980                                       &literalType);
5981   if (Result.isInvalid())
5982     return ExprError();
5983   LiteralExpr = Result.get();
5984 
5985   bool isFileScope = !CurContext->isFunctionOrMethod();
5986 
5987   // In C, compound literals are l-values for some reason.
5988   // For GCC compatibility, in C++, file-scope array compound literals with
5989   // constant initializers are also l-values, and compound literals are
5990   // otherwise prvalues.
5991   //
5992   // (GCC also treats C++ list-initialized file-scope array prvalues with
5993   // constant initializers as l-values, but that's non-conforming, so we don't
5994   // follow it there.)
5995   //
5996   // FIXME: It would be better to handle the lvalue cases as materializing and
5997   // lifetime-extending a temporary object, but our materialized temporaries
5998   // representation only supports lifetime extension from a variable, not "out
5999   // of thin air".
6000   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6001   // is bound to the result of applying array-to-pointer decay to the compound
6002   // literal.
6003   // FIXME: GCC supports compound literals of reference type, which should
6004   // obviously have a value kind derived from the kind of reference involved.
6005   ExprValueKind VK =
6006       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6007           ? VK_RValue
6008           : VK_LValue;
6009 
6010   if (isFileScope)
6011     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6012       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6013         Expr *Init = ILE->getInit(i);
6014         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6015       }
6016 
6017   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6018                                               VK, LiteralExpr, isFileScope);
6019   if (isFileScope) {
6020     if (!LiteralExpr->isTypeDependent() &&
6021         !LiteralExpr->isValueDependent() &&
6022         !literalType->isDependentType()) // C99 6.5.2.5p3
6023       if (CheckForConstantInitializer(LiteralExpr, literalType))
6024         return ExprError();
6025   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6026              literalType.getAddressSpace() != LangAS::Default) {
6027     // Embedded-C extensions to C99 6.5.2.5:
6028     //   "If the compound literal occurs inside the body of a function, the
6029     //   type name shall not be qualified by an address-space qualifier."
6030     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6031       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6032     return ExprError();
6033   }
6034 
6035   return MaybeBindToTemporary(E);
6036 }
6037 
6038 ExprResult
6039 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6040                     SourceLocation RBraceLoc) {
6041   // Immediately handle non-overload placeholders.  Overloads can be
6042   // resolved contextually, but everything else here can't.
6043   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6044     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6045       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6046 
6047       // Ignore failures; dropping the entire initializer list because
6048       // of one failure would be terrible for indexing/etc.
6049       if (result.isInvalid()) continue;
6050 
6051       InitArgList[I] = result.get();
6052     }
6053   }
6054 
6055   // Semantic analysis for initializers is done by ActOnDeclarator() and
6056   // CheckInitializer() - it requires knowledge of the object being initialized.
6057 
6058   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6059                                                RBraceLoc);
6060   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6061   return E;
6062 }
6063 
6064 /// Do an explicit extend of the given block pointer if we're in ARC.
6065 void Sema::maybeExtendBlockObject(ExprResult &E) {
6066   assert(E.get()->getType()->isBlockPointerType());
6067   assert(E.get()->isRValue());
6068 
6069   // Only do this in an r-value context.
6070   if (!getLangOpts().ObjCAutoRefCount) return;
6071 
6072   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6073                                CK_ARCExtendBlockObject, E.get(),
6074                                /*base path*/ nullptr, VK_RValue);
6075   Cleanup.setExprNeedsCleanups(true);
6076 }
6077 
6078 /// Prepare a conversion of the given expression to an ObjC object
6079 /// pointer type.
6080 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6081   QualType type = E.get()->getType();
6082   if (type->isObjCObjectPointerType()) {
6083     return CK_BitCast;
6084   } else if (type->isBlockPointerType()) {
6085     maybeExtendBlockObject(E);
6086     return CK_BlockPointerToObjCPointerCast;
6087   } else {
6088     assert(type->isPointerType());
6089     return CK_CPointerToObjCPointerCast;
6090   }
6091 }
6092 
6093 /// Prepares for a scalar cast, performing all the necessary stages
6094 /// except the final cast and returning the kind required.
6095 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6096   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6097   // Also, callers should have filtered out the invalid cases with
6098   // pointers.  Everything else should be possible.
6099 
6100   QualType SrcTy = Src.get()->getType();
6101   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6102     return CK_NoOp;
6103 
6104   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6105   case Type::STK_MemberPointer:
6106     llvm_unreachable("member pointer type in C");
6107 
6108   case Type::STK_CPointer:
6109   case Type::STK_BlockPointer:
6110   case Type::STK_ObjCObjectPointer:
6111     switch (DestTy->getScalarTypeKind()) {
6112     case Type::STK_CPointer: {
6113       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6114       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6115       if (SrcAS != DestAS)
6116         return CK_AddressSpaceConversion;
6117       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6118         return CK_NoOp;
6119       return CK_BitCast;
6120     }
6121     case Type::STK_BlockPointer:
6122       return (SrcKind == Type::STK_BlockPointer
6123                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6124     case Type::STK_ObjCObjectPointer:
6125       if (SrcKind == Type::STK_ObjCObjectPointer)
6126         return CK_BitCast;
6127       if (SrcKind == Type::STK_CPointer)
6128         return CK_CPointerToObjCPointerCast;
6129       maybeExtendBlockObject(Src);
6130       return CK_BlockPointerToObjCPointerCast;
6131     case Type::STK_Bool:
6132       return CK_PointerToBoolean;
6133     case Type::STK_Integral:
6134       return CK_PointerToIntegral;
6135     case Type::STK_Floating:
6136     case Type::STK_FloatingComplex:
6137     case Type::STK_IntegralComplex:
6138     case Type::STK_MemberPointer:
6139     case Type::STK_FixedPoint:
6140       llvm_unreachable("illegal cast from pointer");
6141     }
6142     llvm_unreachable("Should have returned before this");
6143 
6144   case Type::STK_FixedPoint:
6145     switch (DestTy->getScalarTypeKind()) {
6146     case Type::STK_FixedPoint:
6147       return CK_FixedPointCast;
6148     case Type::STK_Bool:
6149       return CK_FixedPointToBoolean;
6150     case Type::STK_Integral:
6151       return CK_FixedPointToIntegral;
6152     case Type::STK_Floating:
6153     case Type::STK_IntegralComplex:
6154     case Type::STK_FloatingComplex:
6155       Diag(Src.get()->getExprLoc(),
6156            diag::err_unimplemented_conversion_with_fixed_point_type)
6157           << DestTy;
6158       return CK_IntegralCast;
6159     case Type::STK_CPointer:
6160     case Type::STK_ObjCObjectPointer:
6161     case Type::STK_BlockPointer:
6162     case Type::STK_MemberPointer:
6163       llvm_unreachable("illegal cast to pointer type");
6164     }
6165     llvm_unreachable("Should have returned before this");
6166 
6167   case Type::STK_Bool: // casting from bool is like casting from an integer
6168   case Type::STK_Integral:
6169     switch (DestTy->getScalarTypeKind()) {
6170     case Type::STK_CPointer:
6171     case Type::STK_ObjCObjectPointer:
6172     case Type::STK_BlockPointer:
6173       if (Src.get()->isNullPointerConstant(Context,
6174                                            Expr::NPC_ValueDependentIsNull))
6175         return CK_NullToPointer;
6176       return CK_IntegralToPointer;
6177     case Type::STK_Bool:
6178       return CK_IntegralToBoolean;
6179     case Type::STK_Integral:
6180       return CK_IntegralCast;
6181     case Type::STK_Floating:
6182       return CK_IntegralToFloating;
6183     case Type::STK_IntegralComplex:
6184       Src = ImpCastExprToType(Src.get(),
6185                       DestTy->castAs<ComplexType>()->getElementType(),
6186                       CK_IntegralCast);
6187       return CK_IntegralRealToComplex;
6188     case Type::STK_FloatingComplex:
6189       Src = ImpCastExprToType(Src.get(),
6190                       DestTy->castAs<ComplexType>()->getElementType(),
6191                       CK_IntegralToFloating);
6192       return CK_FloatingRealToComplex;
6193     case Type::STK_MemberPointer:
6194       llvm_unreachable("member pointer type in C");
6195     case Type::STK_FixedPoint:
6196       return CK_IntegralToFixedPoint;
6197     }
6198     llvm_unreachable("Should have returned before this");
6199 
6200   case Type::STK_Floating:
6201     switch (DestTy->getScalarTypeKind()) {
6202     case Type::STK_Floating:
6203       return CK_FloatingCast;
6204     case Type::STK_Bool:
6205       return CK_FloatingToBoolean;
6206     case Type::STK_Integral:
6207       return CK_FloatingToIntegral;
6208     case Type::STK_FloatingComplex:
6209       Src = ImpCastExprToType(Src.get(),
6210                               DestTy->castAs<ComplexType>()->getElementType(),
6211                               CK_FloatingCast);
6212       return CK_FloatingRealToComplex;
6213     case Type::STK_IntegralComplex:
6214       Src = ImpCastExprToType(Src.get(),
6215                               DestTy->castAs<ComplexType>()->getElementType(),
6216                               CK_FloatingToIntegral);
6217       return CK_IntegralRealToComplex;
6218     case Type::STK_CPointer:
6219     case Type::STK_ObjCObjectPointer:
6220     case Type::STK_BlockPointer:
6221       llvm_unreachable("valid float->pointer cast?");
6222     case Type::STK_MemberPointer:
6223       llvm_unreachable("member pointer type in C");
6224     case Type::STK_FixedPoint:
6225       Diag(Src.get()->getExprLoc(),
6226            diag::err_unimplemented_conversion_with_fixed_point_type)
6227           << SrcTy;
6228       return CK_IntegralCast;
6229     }
6230     llvm_unreachable("Should have returned before this");
6231 
6232   case Type::STK_FloatingComplex:
6233     switch (DestTy->getScalarTypeKind()) {
6234     case Type::STK_FloatingComplex:
6235       return CK_FloatingComplexCast;
6236     case Type::STK_IntegralComplex:
6237       return CK_FloatingComplexToIntegralComplex;
6238     case Type::STK_Floating: {
6239       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6240       if (Context.hasSameType(ET, DestTy))
6241         return CK_FloatingComplexToReal;
6242       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6243       return CK_FloatingCast;
6244     }
6245     case Type::STK_Bool:
6246       return CK_FloatingComplexToBoolean;
6247     case Type::STK_Integral:
6248       Src = ImpCastExprToType(Src.get(),
6249                               SrcTy->castAs<ComplexType>()->getElementType(),
6250                               CK_FloatingComplexToReal);
6251       return CK_FloatingToIntegral;
6252     case Type::STK_CPointer:
6253     case Type::STK_ObjCObjectPointer:
6254     case Type::STK_BlockPointer:
6255       llvm_unreachable("valid complex float->pointer cast?");
6256     case Type::STK_MemberPointer:
6257       llvm_unreachable("member pointer type in C");
6258     case Type::STK_FixedPoint:
6259       Diag(Src.get()->getExprLoc(),
6260            diag::err_unimplemented_conversion_with_fixed_point_type)
6261           << SrcTy;
6262       return CK_IntegralCast;
6263     }
6264     llvm_unreachable("Should have returned before this");
6265 
6266   case Type::STK_IntegralComplex:
6267     switch (DestTy->getScalarTypeKind()) {
6268     case Type::STK_FloatingComplex:
6269       return CK_IntegralComplexToFloatingComplex;
6270     case Type::STK_IntegralComplex:
6271       return CK_IntegralComplexCast;
6272     case Type::STK_Integral: {
6273       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6274       if (Context.hasSameType(ET, DestTy))
6275         return CK_IntegralComplexToReal;
6276       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6277       return CK_IntegralCast;
6278     }
6279     case Type::STK_Bool:
6280       return CK_IntegralComplexToBoolean;
6281     case Type::STK_Floating:
6282       Src = ImpCastExprToType(Src.get(),
6283                               SrcTy->castAs<ComplexType>()->getElementType(),
6284                               CK_IntegralComplexToReal);
6285       return CK_IntegralToFloating;
6286     case Type::STK_CPointer:
6287     case Type::STK_ObjCObjectPointer:
6288     case Type::STK_BlockPointer:
6289       llvm_unreachable("valid complex int->pointer cast?");
6290     case Type::STK_MemberPointer:
6291       llvm_unreachable("member pointer type in C");
6292     case Type::STK_FixedPoint:
6293       Diag(Src.get()->getExprLoc(),
6294            diag::err_unimplemented_conversion_with_fixed_point_type)
6295           << SrcTy;
6296       return CK_IntegralCast;
6297     }
6298     llvm_unreachable("Should have returned before this");
6299   }
6300 
6301   llvm_unreachable("Unhandled scalar cast");
6302 }
6303 
6304 static bool breakDownVectorType(QualType type, uint64_t &len,
6305                                 QualType &eltType) {
6306   // Vectors are simple.
6307   if (const VectorType *vecType = type->getAs<VectorType>()) {
6308     len = vecType->getNumElements();
6309     eltType = vecType->getElementType();
6310     assert(eltType->isScalarType());
6311     return true;
6312   }
6313 
6314   // We allow lax conversion to and from non-vector types, but only if
6315   // they're real types (i.e. non-complex, non-pointer scalar types).
6316   if (!type->isRealType()) return false;
6317 
6318   len = 1;
6319   eltType = type;
6320   return true;
6321 }
6322 
6323 /// Are the two types lax-compatible vector types?  That is, given
6324 /// that one of them is a vector, do they have equal storage sizes,
6325 /// where the storage size is the number of elements times the element
6326 /// size?
6327 ///
6328 /// This will also return false if either of the types is neither a
6329 /// vector nor a real type.
6330 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6331   assert(destTy->isVectorType() || srcTy->isVectorType());
6332 
6333   // Disallow lax conversions between scalars and ExtVectors (these
6334   // conversions are allowed for other vector types because common headers
6335   // depend on them).  Most scalar OP ExtVector cases are handled by the
6336   // splat path anyway, which does what we want (convert, not bitcast).
6337   // What this rules out for ExtVectors is crazy things like char4*float.
6338   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6339   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6340 
6341   uint64_t srcLen, destLen;
6342   QualType srcEltTy, destEltTy;
6343   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6344   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6345 
6346   // ASTContext::getTypeSize will return the size rounded up to a
6347   // power of 2, so instead of using that, we need to use the raw
6348   // element size multiplied by the element count.
6349   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6350   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6351 
6352   return (srcLen * srcEltSize == destLen * destEltSize);
6353 }
6354 
6355 /// Is this a legal conversion between two types, one of which is
6356 /// known to be a vector type?
6357 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6358   assert(destTy->isVectorType() || srcTy->isVectorType());
6359 
6360   if (!Context.getLangOpts().LaxVectorConversions)
6361     return false;
6362   return areLaxCompatibleVectorTypes(srcTy, destTy);
6363 }
6364 
6365 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6366                            CastKind &Kind) {
6367   assert(VectorTy->isVectorType() && "Not a vector type!");
6368 
6369   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6370     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6371       return Diag(R.getBegin(),
6372                   Ty->isVectorType() ?
6373                   diag::err_invalid_conversion_between_vectors :
6374                   diag::err_invalid_conversion_between_vector_and_integer)
6375         << VectorTy << Ty << R;
6376   } else
6377     return Diag(R.getBegin(),
6378                 diag::err_invalid_conversion_between_vector_and_scalar)
6379       << VectorTy << Ty << R;
6380 
6381   Kind = CK_BitCast;
6382   return false;
6383 }
6384 
6385 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6386   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6387 
6388   if (DestElemTy == SplattedExpr->getType())
6389     return SplattedExpr;
6390 
6391   assert(DestElemTy->isFloatingType() ||
6392          DestElemTy->isIntegralOrEnumerationType());
6393 
6394   CastKind CK;
6395   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6396     // OpenCL requires that we convert `true` boolean expressions to -1, but
6397     // only when splatting vectors.
6398     if (DestElemTy->isFloatingType()) {
6399       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6400       // in two steps: boolean to signed integral, then to floating.
6401       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6402                                                  CK_BooleanToSignedIntegral);
6403       SplattedExpr = CastExprRes.get();
6404       CK = CK_IntegralToFloating;
6405     } else {
6406       CK = CK_BooleanToSignedIntegral;
6407     }
6408   } else {
6409     ExprResult CastExprRes = SplattedExpr;
6410     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6411     if (CastExprRes.isInvalid())
6412       return ExprError();
6413     SplattedExpr = CastExprRes.get();
6414   }
6415   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6416 }
6417 
6418 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6419                                     Expr *CastExpr, CastKind &Kind) {
6420   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6421 
6422   QualType SrcTy = CastExpr->getType();
6423 
6424   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6425   // an ExtVectorType.
6426   // In OpenCL, casts between vectors of different types are not allowed.
6427   // (See OpenCL 6.2).
6428   if (SrcTy->isVectorType()) {
6429     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6430         (getLangOpts().OpenCL &&
6431          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6432       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6433         << DestTy << SrcTy << R;
6434       return ExprError();
6435     }
6436     Kind = CK_BitCast;
6437     return CastExpr;
6438   }
6439 
6440   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6441   // conversion will take place first from scalar to elt type, and then
6442   // splat from elt type to vector.
6443   if (SrcTy->isPointerType())
6444     return Diag(R.getBegin(),
6445                 diag::err_invalid_conversion_between_vector_and_scalar)
6446       << DestTy << SrcTy << R;
6447 
6448   Kind = CK_VectorSplat;
6449   return prepareVectorSplat(DestTy, CastExpr);
6450 }
6451 
6452 ExprResult
6453 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6454                     Declarator &D, ParsedType &Ty,
6455                     SourceLocation RParenLoc, Expr *CastExpr) {
6456   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6457          "ActOnCastExpr(): missing type or expr");
6458 
6459   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6460   if (D.isInvalidType())
6461     return ExprError();
6462 
6463   if (getLangOpts().CPlusPlus) {
6464     // Check that there are no default arguments (C++ only).
6465     CheckExtraCXXDefaultArguments(D);
6466   } else {
6467     // Make sure any TypoExprs have been dealt with.
6468     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6469     if (!Res.isUsable())
6470       return ExprError();
6471     CastExpr = Res.get();
6472   }
6473 
6474   checkUnusedDeclAttributes(D);
6475 
6476   QualType castType = castTInfo->getType();
6477   Ty = CreateParsedType(castType, castTInfo);
6478 
6479   bool isVectorLiteral = false;
6480 
6481   // Check for an altivec or OpenCL literal,
6482   // i.e. all the elements are integer constants.
6483   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6484   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6485   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6486        && castType->isVectorType() && (PE || PLE)) {
6487     if (PLE && PLE->getNumExprs() == 0) {
6488       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6489       return ExprError();
6490     }
6491     if (PE || PLE->getNumExprs() == 1) {
6492       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6493       if (!E->getType()->isVectorType())
6494         isVectorLiteral = true;
6495     }
6496     else
6497       isVectorLiteral = true;
6498   }
6499 
6500   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6501   // then handle it as such.
6502   if (isVectorLiteral)
6503     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6504 
6505   // If the Expr being casted is a ParenListExpr, handle it specially.
6506   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6507   // sequence of BinOp comma operators.
6508   if (isa<ParenListExpr>(CastExpr)) {
6509     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6510     if (Result.isInvalid()) return ExprError();
6511     CastExpr = Result.get();
6512   }
6513 
6514   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6515       !getSourceManager().isInSystemMacro(LParenLoc))
6516     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6517 
6518   CheckTollFreeBridgeCast(castType, CastExpr);
6519 
6520   CheckObjCBridgeRelatedCast(castType, CastExpr);
6521 
6522   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6523 
6524   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6525 }
6526 
6527 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6528                                     SourceLocation RParenLoc, Expr *E,
6529                                     TypeSourceInfo *TInfo) {
6530   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6531          "Expected paren or paren list expression");
6532 
6533   Expr **exprs;
6534   unsigned numExprs;
6535   Expr *subExpr;
6536   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6537   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6538     LiteralLParenLoc = PE->getLParenLoc();
6539     LiteralRParenLoc = PE->getRParenLoc();
6540     exprs = PE->getExprs();
6541     numExprs = PE->getNumExprs();
6542   } else { // isa<ParenExpr> by assertion at function entrance
6543     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6544     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6545     subExpr = cast<ParenExpr>(E)->getSubExpr();
6546     exprs = &subExpr;
6547     numExprs = 1;
6548   }
6549 
6550   QualType Ty = TInfo->getType();
6551   assert(Ty->isVectorType() && "Expected vector type");
6552 
6553   SmallVector<Expr *, 8> initExprs;
6554   const VectorType *VTy = Ty->getAs<VectorType>();
6555   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6556 
6557   // '(...)' form of vector initialization in AltiVec: the number of
6558   // initializers must be one or must match the size of the vector.
6559   // If a single value is specified in the initializer then it will be
6560   // replicated to all the components of the vector
6561   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6562     // The number of initializers must be one or must match the size of the
6563     // vector. If a single value is specified in the initializer then it will
6564     // be replicated to all the components of the vector
6565     if (numExprs == 1) {
6566       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6567       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6568       if (Literal.isInvalid())
6569         return ExprError();
6570       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6571                                   PrepareScalarCast(Literal, ElemTy));
6572       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6573     }
6574     else if (numExprs < numElems) {
6575       Diag(E->getExprLoc(),
6576            diag::err_incorrect_number_of_vector_initializers);
6577       return ExprError();
6578     }
6579     else
6580       initExprs.append(exprs, exprs + numExprs);
6581   }
6582   else {
6583     // For OpenCL, when the number of initializers is a single value,
6584     // it will be replicated to all components of the vector.
6585     if (getLangOpts().OpenCL &&
6586         VTy->getVectorKind() == VectorType::GenericVector &&
6587         numExprs == 1) {
6588         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6589         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6590         if (Literal.isInvalid())
6591           return ExprError();
6592         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6593                                     PrepareScalarCast(Literal, ElemTy));
6594         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6595     }
6596 
6597     initExprs.append(exprs, exprs + numExprs);
6598   }
6599   // FIXME: This means that pretty-printing the final AST will produce curly
6600   // braces instead of the original commas.
6601   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6602                                                    initExprs, LiteralRParenLoc);
6603   initE->setType(Ty);
6604   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6605 }
6606 
6607 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6608 /// the ParenListExpr into a sequence of comma binary operators.
6609 ExprResult
6610 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6611   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6612   if (!E)
6613     return OrigExpr;
6614 
6615   ExprResult Result(E->getExpr(0));
6616 
6617   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6618     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6619                         E->getExpr(i));
6620 
6621   if (Result.isInvalid()) return ExprError();
6622 
6623   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6624 }
6625 
6626 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6627                                     SourceLocation R,
6628                                     MultiExprArg Val) {
6629   return ParenListExpr::Create(Context, L, Val, R);
6630 }
6631 
6632 /// Emit a specialized diagnostic when one expression is a null pointer
6633 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6634 /// emitted.
6635 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6636                                       SourceLocation QuestionLoc) {
6637   Expr *NullExpr = LHSExpr;
6638   Expr *NonPointerExpr = RHSExpr;
6639   Expr::NullPointerConstantKind NullKind =
6640       NullExpr->isNullPointerConstant(Context,
6641                                       Expr::NPC_ValueDependentIsNotNull);
6642 
6643   if (NullKind == Expr::NPCK_NotNull) {
6644     NullExpr = RHSExpr;
6645     NonPointerExpr = LHSExpr;
6646     NullKind =
6647         NullExpr->isNullPointerConstant(Context,
6648                                         Expr::NPC_ValueDependentIsNotNull);
6649   }
6650 
6651   if (NullKind == Expr::NPCK_NotNull)
6652     return false;
6653 
6654   if (NullKind == Expr::NPCK_ZeroExpression)
6655     return false;
6656 
6657   if (NullKind == Expr::NPCK_ZeroLiteral) {
6658     // In this case, check to make sure that we got here from a "NULL"
6659     // string in the source code.
6660     NullExpr = NullExpr->IgnoreParenImpCasts();
6661     SourceLocation loc = NullExpr->getExprLoc();
6662     if (!findMacroSpelling(loc, "NULL"))
6663       return false;
6664   }
6665 
6666   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6667   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6668       << NonPointerExpr->getType() << DiagType
6669       << NonPointerExpr->getSourceRange();
6670   return true;
6671 }
6672 
6673 /// Return false if the condition expression is valid, true otherwise.
6674 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6675   QualType CondTy = Cond->getType();
6676 
6677   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6678   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6679     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6680       << CondTy << Cond->getSourceRange();
6681     return true;
6682   }
6683 
6684   // C99 6.5.15p2
6685   if (CondTy->isScalarType()) return false;
6686 
6687   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6688     << CondTy << Cond->getSourceRange();
6689   return true;
6690 }
6691 
6692 /// Handle when one or both operands are void type.
6693 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6694                                          ExprResult &RHS) {
6695     Expr *LHSExpr = LHS.get();
6696     Expr *RHSExpr = RHS.get();
6697 
6698     if (!LHSExpr->getType()->isVoidType())
6699       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6700           << RHSExpr->getSourceRange();
6701     if (!RHSExpr->getType()->isVoidType())
6702       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6703           << LHSExpr->getSourceRange();
6704     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6705     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6706     return S.Context.VoidTy;
6707 }
6708 
6709 /// Return false if the NullExpr can be promoted to PointerTy,
6710 /// true otherwise.
6711 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6712                                         QualType PointerTy) {
6713   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6714       !NullExpr.get()->isNullPointerConstant(S.Context,
6715                                             Expr::NPC_ValueDependentIsNull))
6716     return true;
6717 
6718   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6719   return false;
6720 }
6721 
6722 /// Checks compatibility between two pointers and return the resulting
6723 /// type.
6724 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6725                                                      ExprResult &RHS,
6726                                                      SourceLocation Loc) {
6727   QualType LHSTy = LHS.get()->getType();
6728   QualType RHSTy = RHS.get()->getType();
6729 
6730   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6731     // Two identical pointers types are always compatible.
6732     return LHSTy;
6733   }
6734 
6735   QualType lhptee, rhptee;
6736 
6737   // Get the pointee types.
6738   bool IsBlockPointer = false;
6739   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6740     lhptee = LHSBTy->getPointeeType();
6741     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6742     IsBlockPointer = true;
6743   } else {
6744     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6745     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6746   }
6747 
6748   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6749   // differently qualified versions of compatible types, the result type is
6750   // a pointer to an appropriately qualified version of the composite
6751   // type.
6752 
6753   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6754   // clause doesn't make sense for our extensions. E.g. address space 2 should
6755   // be incompatible with address space 3: they may live on different devices or
6756   // anything.
6757   Qualifiers lhQual = lhptee.getQualifiers();
6758   Qualifiers rhQual = rhptee.getQualifiers();
6759 
6760   LangAS ResultAddrSpace = LangAS::Default;
6761   LangAS LAddrSpace = lhQual.getAddressSpace();
6762   LangAS RAddrSpace = rhQual.getAddressSpace();
6763 
6764   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6765   // spaces is disallowed.
6766   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6767     ResultAddrSpace = LAddrSpace;
6768   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6769     ResultAddrSpace = RAddrSpace;
6770   else {
6771     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6772         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6773         << RHS.get()->getSourceRange();
6774     return QualType();
6775   }
6776 
6777   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6778   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6779   lhQual.removeCVRQualifiers();
6780   rhQual.removeCVRQualifiers();
6781 
6782   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6783   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6784   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6785   // qual types are compatible iff
6786   //  * corresponded types are compatible
6787   //  * CVR qualifiers are equal
6788   //  * address spaces are equal
6789   // Thus for conditional operator we merge CVR and address space unqualified
6790   // pointees and if there is a composite type we return a pointer to it with
6791   // merged qualifiers.
6792   LHSCastKind =
6793       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6794   RHSCastKind =
6795       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6796   lhQual.removeAddressSpace();
6797   rhQual.removeAddressSpace();
6798 
6799   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6800   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6801 
6802   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6803 
6804   if (CompositeTy.isNull()) {
6805     // In this situation, we assume void* type. No especially good
6806     // reason, but this is what gcc does, and we do have to pick
6807     // to get a consistent AST.
6808     QualType incompatTy;
6809     incompatTy = S.Context.getPointerType(
6810         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6811     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6812     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6813 
6814     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6815     // for casts between types with incompatible address space qualifiers.
6816     // For the following code the compiler produces casts between global and
6817     // local address spaces of the corresponded innermost pointees:
6818     // local int *global *a;
6819     // global int *global *b;
6820     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6821     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6822         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6823         << RHS.get()->getSourceRange();
6824 
6825     return incompatTy;
6826   }
6827 
6828   // The pointer types are compatible.
6829   // In case of OpenCL ResultTy should have the address space qualifier
6830   // which is a superset of address spaces of both the 2nd and the 3rd
6831   // operands of the conditional operator.
6832   QualType ResultTy = [&, ResultAddrSpace]() {
6833     if (S.getLangOpts().OpenCL) {
6834       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6835       CompositeQuals.setAddressSpace(ResultAddrSpace);
6836       return S.Context
6837           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6838           .withCVRQualifiers(MergedCVRQual);
6839     }
6840     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6841   }();
6842   if (IsBlockPointer)
6843     ResultTy = S.Context.getBlockPointerType(ResultTy);
6844   else
6845     ResultTy = S.Context.getPointerType(ResultTy);
6846 
6847   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6848   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6849   return ResultTy;
6850 }
6851 
6852 /// Return the resulting type when the operands are both block pointers.
6853 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6854                                                           ExprResult &LHS,
6855                                                           ExprResult &RHS,
6856                                                           SourceLocation Loc) {
6857   QualType LHSTy = LHS.get()->getType();
6858   QualType RHSTy = RHS.get()->getType();
6859 
6860   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6861     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6862       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6863       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6864       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6865       return destType;
6866     }
6867     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6868       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6869       << RHS.get()->getSourceRange();
6870     return QualType();
6871   }
6872 
6873   // We have 2 block pointer types.
6874   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6875 }
6876 
6877 /// Return the resulting type when the operands are both pointers.
6878 static QualType
6879 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6880                                             ExprResult &RHS,
6881                                             SourceLocation Loc) {
6882   // get the pointer types
6883   QualType LHSTy = LHS.get()->getType();
6884   QualType RHSTy = RHS.get()->getType();
6885 
6886   // get the "pointed to" types
6887   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6888   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6889 
6890   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6891   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6892     // Figure out necessary qualifiers (C99 6.5.15p6)
6893     QualType destPointee
6894       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6895     QualType destType = S.Context.getPointerType(destPointee);
6896     // Add qualifiers if necessary.
6897     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6898     // Promote to void*.
6899     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6900     return destType;
6901   }
6902   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6903     QualType destPointee
6904       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6905     QualType destType = S.Context.getPointerType(destPointee);
6906     // Add qualifiers if necessary.
6907     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6908     // Promote to void*.
6909     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6910     return destType;
6911   }
6912 
6913   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6914 }
6915 
6916 /// Return false if the first expression is not an integer and the second
6917 /// expression is not a pointer, true otherwise.
6918 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6919                                         Expr* PointerExpr, SourceLocation Loc,
6920                                         bool IsIntFirstExpr) {
6921   if (!PointerExpr->getType()->isPointerType() ||
6922       !Int.get()->getType()->isIntegerType())
6923     return false;
6924 
6925   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6926   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6927 
6928   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6929     << Expr1->getType() << Expr2->getType()
6930     << Expr1->getSourceRange() << Expr2->getSourceRange();
6931   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6932                             CK_IntegralToPointer);
6933   return true;
6934 }
6935 
6936 /// Simple conversion between integer and floating point types.
6937 ///
6938 /// Used when handling the OpenCL conditional operator where the
6939 /// condition is a vector while the other operands are scalar.
6940 ///
6941 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6942 /// types are either integer or floating type. Between the two
6943 /// operands, the type with the higher rank is defined as the "result
6944 /// type". The other operand needs to be promoted to the same type. No
6945 /// other type promotion is allowed. We cannot use
6946 /// UsualArithmeticConversions() for this purpose, since it always
6947 /// promotes promotable types.
6948 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6949                                             ExprResult &RHS,
6950                                             SourceLocation QuestionLoc) {
6951   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6952   if (LHS.isInvalid())
6953     return QualType();
6954   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6955   if (RHS.isInvalid())
6956     return QualType();
6957 
6958   // For conversion purposes, we ignore any qualifiers.
6959   // For example, "const float" and "float" are equivalent.
6960   QualType LHSType =
6961     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6962   QualType RHSType =
6963     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6964 
6965   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6966     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6967       << LHSType << LHS.get()->getSourceRange();
6968     return QualType();
6969   }
6970 
6971   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6972     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6973       << RHSType << RHS.get()->getSourceRange();
6974     return QualType();
6975   }
6976 
6977   // If both types are identical, no conversion is needed.
6978   if (LHSType == RHSType)
6979     return LHSType;
6980 
6981   // Now handle "real" floating types (i.e. float, double, long double).
6982   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6983     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6984                                  /*IsCompAssign = */ false);
6985 
6986   // Finally, we have two differing integer types.
6987   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6988   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6989 }
6990 
6991 /// Convert scalar operands to a vector that matches the
6992 ///        condition in length.
6993 ///
6994 /// Used when handling the OpenCL conditional operator where the
6995 /// condition is a vector while the other operands are scalar.
6996 ///
6997 /// We first compute the "result type" for the scalar operands
6998 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6999 /// into a vector of that type where the length matches the condition
7000 /// vector type. s6.11.6 requires that the element types of the result
7001 /// and the condition must have the same number of bits.
7002 static QualType
7003 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7004                               QualType CondTy, SourceLocation QuestionLoc) {
7005   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7006   if (ResTy.isNull()) return QualType();
7007 
7008   const VectorType *CV = CondTy->getAs<VectorType>();
7009   assert(CV);
7010 
7011   // Determine the vector result type
7012   unsigned NumElements = CV->getNumElements();
7013   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7014 
7015   // Ensure that all types have the same number of bits
7016   if (S.Context.getTypeSize(CV->getElementType())
7017       != S.Context.getTypeSize(ResTy)) {
7018     // Since VectorTy is created internally, it does not pretty print
7019     // with an OpenCL name. Instead, we just print a description.
7020     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7021     SmallString<64> Str;
7022     llvm::raw_svector_ostream OS(Str);
7023     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7024     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7025       << CondTy << OS.str();
7026     return QualType();
7027   }
7028 
7029   // Convert operands to the vector result type
7030   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7031   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7032 
7033   return VectorTy;
7034 }
7035 
7036 /// Return false if this is a valid OpenCL condition vector
7037 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7038                                        SourceLocation QuestionLoc) {
7039   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7040   // integral type.
7041   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7042   assert(CondTy);
7043   QualType EleTy = CondTy->getElementType();
7044   if (EleTy->isIntegerType()) return false;
7045 
7046   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7047     << Cond->getType() << Cond->getSourceRange();
7048   return true;
7049 }
7050 
7051 /// Return false if the vector condition type and the vector
7052 ///        result type are compatible.
7053 ///
7054 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7055 /// number of elements, and their element types have the same number
7056 /// of bits.
7057 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7058                               SourceLocation QuestionLoc) {
7059   const VectorType *CV = CondTy->getAs<VectorType>();
7060   const VectorType *RV = VecResTy->getAs<VectorType>();
7061   assert(CV && RV);
7062 
7063   if (CV->getNumElements() != RV->getNumElements()) {
7064     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7065       << CondTy << VecResTy;
7066     return true;
7067   }
7068 
7069   QualType CVE = CV->getElementType();
7070   QualType RVE = RV->getElementType();
7071 
7072   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7073     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7074       << CondTy << VecResTy;
7075     return true;
7076   }
7077 
7078   return false;
7079 }
7080 
7081 /// Return the resulting type for the conditional operator in
7082 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7083 ///        s6.3.i) when the condition is a vector type.
7084 static QualType
7085 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7086                              ExprResult &LHS, ExprResult &RHS,
7087                              SourceLocation QuestionLoc) {
7088   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7089   if (Cond.isInvalid())
7090     return QualType();
7091   QualType CondTy = Cond.get()->getType();
7092 
7093   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7094     return QualType();
7095 
7096   // If either operand is a vector then find the vector type of the
7097   // result as specified in OpenCL v1.1 s6.3.i.
7098   if (LHS.get()->getType()->isVectorType() ||
7099       RHS.get()->getType()->isVectorType()) {
7100     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7101                                               /*isCompAssign*/false,
7102                                               /*AllowBothBool*/true,
7103                                               /*AllowBoolConversions*/false);
7104     if (VecResTy.isNull()) return QualType();
7105     // The result type must match the condition type as specified in
7106     // OpenCL v1.1 s6.11.6.
7107     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7108       return QualType();
7109     return VecResTy;
7110   }
7111 
7112   // Both operands are scalar.
7113   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7114 }
7115 
7116 /// Return true if the Expr is block type
7117 static bool checkBlockType(Sema &S, const Expr *E) {
7118   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7119     QualType Ty = CE->getCallee()->getType();
7120     if (Ty->isBlockPointerType()) {
7121       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7122       return true;
7123     }
7124   }
7125   return false;
7126 }
7127 
7128 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7129 /// In that case, LHS = cond.
7130 /// C99 6.5.15
7131 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7132                                         ExprResult &RHS, ExprValueKind &VK,
7133                                         ExprObjectKind &OK,
7134                                         SourceLocation QuestionLoc) {
7135 
7136   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7137   if (!LHSResult.isUsable()) return QualType();
7138   LHS = LHSResult;
7139 
7140   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7141   if (!RHSResult.isUsable()) return QualType();
7142   RHS = RHSResult;
7143 
7144   // C++ is sufficiently different to merit its own checker.
7145   if (getLangOpts().CPlusPlus)
7146     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7147 
7148   VK = VK_RValue;
7149   OK = OK_Ordinary;
7150 
7151   // The OpenCL operator with a vector condition is sufficiently
7152   // different to merit its own checker.
7153   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7154     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7155 
7156   // First, check the condition.
7157   Cond = UsualUnaryConversions(Cond.get());
7158   if (Cond.isInvalid())
7159     return QualType();
7160   if (checkCondition(*this, Cond.get(), QuestionLoc))
7161     return QualType();
7162 
7163   // Now check the two expressions.
7164   if (LHS.get()->getType()->isVectorType() ||
7165       RHS.get()->getType()->isVectorType())
7166     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7167                                /*AllowBothBool*/true,
7168                                /*AllowBoolConversions*/false);
7169 
7170   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7171   if (LHS.isInvalid() || RHS.isInvalid())
7172     return QualType();
7173 
7174   QualType LHSTy = LHS.get()->getType();
7175   QualType RHSTy = RHS.get()->getType();
7176 
7177   // Diagnose attempts to convert between __float128 and long double where
7178   // such conversions currently can't be handled.
7179   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7180     Diag(QuestionLoc,
7181          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7182       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7183     return QualType();
7184   }
7185 
7186   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7187   // selection operator (?:).
7188   if (getLangOpts().OpenCL &&
7189       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7190     return QualType();
7191   }
7192 
7193   // If both operands have arithmetic type, do the usual arithmetic conversions
7194   // to find a common type: C99 6.5.15p3,5.
7195   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7196     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7197     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7198 
7199     return ResTy;
7200   }
7201 
7202   // If both operands are the same structure or union type, the result is that
7203   // type.
7204   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7205     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7206       if (LHSRT->getDecl() == RHSRT->getDecl())
7207         // "If both the operands have structure or union type, the result has
7208         // that type."  This implies that CV qualifiers are dropped.
7209         return LHSTy.getUnqualifiedType();
7210     // FIXME: Type of conditional expression must be complete in C mode.
7211   }
7212 
7213   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7214   // The following || allows only one side to be void (a GCC-ism).
7215   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7216     return checkConditionalVoidType(*this, LHS, RHS);
7217   }
7218 
7219   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7220   // the type of the other operand."
7221   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7222   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7223 
7224   // All objective-c pointer type analysis is done here.
7225   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7226                                                         QuestionLoc);
7227   if (LHS.isInvalid() || RHS.isInvalid())
7228     return QualType();
7229   if (!compositeType.isNull())
7230     return compositeType;
7231 
7232 
7233   // Handle block pointer types.
7234   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7235     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7236                                                      QuestionLoc);
7237 
7238   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7239   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7240     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7241                                                        QuestionLoc);
7242 
7243   // GCC compatibility: soften pointer/integer mismatch.  Note that
7244   // null pointers have been filtered out by this point.
7245   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7246       /*isIntFirstExpr=*/true))
7247     return RHSTy;
7248   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7249       /*isIntFirstExpr=*/false))
7250     return LHSTy;
7251 
7252   // Emit a better diagnostic if one of the expressions is a null pointer
7253   // constant and the other is not a pointer type. In this case, the user most
7254   // likely forgot to take the address of the other expression.
7255   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7256     return QualType();
7257 
7258   // Otherwise, the operands are not compatible.
7259   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7260     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7261     << RHS.get()->getSourceRange();
7262   return QualType();
7263 }
7264 
7265 /// FindCompositeObjCPointerType - Helper method to find composite type of
7266 /// two objective-c pointer types of the two input expressions.
7267 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7268                                             SourceLocation QuestionLoc) {
7269   QualType LHSTy = LHS.get()->getType();
7270   QualType RHSTy = RHS.get()->getType();
7271 
7272   // Handle things like Class and struct objc_class*.  Here we case the result
7273   // to the pseudo-builtin, because that will be implicitly cast back to the
7274   // redefinition type if an attempt is made to access its fields.
7275   if (LHSTy->isObjCClassType() &&
7276       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7277     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7278     return LHSTy;
7279   }
7280   if (RHSTy->isObjCClassType() &&
7281       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7282     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7283     return RHSTy;
7284   }
7285   // And the same for struct objc_object* / id
7286   if (LHSTy->isObjCIdType() &&
7287       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7288     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7289     return LHSTy;
7290   }
7291   if (RHSTy->isObjCIdType() &&
7292       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7293     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7294     return RHSTy;
7295   }
7296   // And the same for struct objc_selector* / SEL
7297   if (Context.isObjCSelType(LHSTy) &&
7298       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7299     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7300     return LHSTy;
7301   }
7302   if (Context.isObjCSelType(RHSTy) &&
7303       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7304     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7305     return RHSTy;
7306   }
7307   // Check constraints for Objective-C object pointers types.
7308   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7309 
7310     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7311       // Two identical object pointer types are always compatible.
7312       return LHSTy;
7313     }
7314     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7315     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7316     QualType compositeType = LHSTy;
7317 
7318     // If both operands are interfaces and either operand can be
7319     // assigned to the other, use that type as the composite
7320     // type. This allows
7321     //   xxx ? (A*) a : (B*) b
7322     // where B is a subclass of A.
7323     //
7324     // Additionally, as for assignment, if either type is 'id'
7325     // allow silent coercion. Finally, if the types are
7326     // incompatible then make sure to use 'id' as the composite
7327     // type so the result is acceptable for sending messages to.
7328 
7329     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7330     // It could return the composite type.
7331     if (!(compositeType =
7332           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7333       // Nothing more to do.
7334     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7335       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7336     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7337       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7338     } else if ((LHSTy->isObjCQualifiedIdType() ||
7339                 RHSTy->isObjCQualifiedIdType()) &&
7340                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7341       // Need to handle "id<xx>" explicitly.
7342       // GCC allows qualified id and any Objective-C type to devolve to
7343       // id. Currently localizing to here until clear this should be
7344       // part of ObjCQualifiedIdTypesAreCompatible.
7345       compositeType = Context.getObjCIdType();
7346     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7347       compositeType = Context.getObjCIdType();
7348     } else {
7349       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7350       << LHSTy << RHSTy
7351       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7352       QualType incompatTy = Context.getObjCIdType();
7353       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7354       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7355       return incompatTy;
7356     }
7357     // The object pointer types are compatible.
7358     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7359     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7360     return compositeType;
7361   }
7362   // Check Objective-C object pointer types and 'void *'
7363   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7364     if (getLangOpts().ObjCAutoRefCount) {
7365       // ARC forbids the implicit conversion of object pointers to 'void *',
7366       // so these types are not compatible.
7367       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7368           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7369       LHS = RHS = true;
7370       return QualType();
7371     }
7372     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7373     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7374     QualType destPointee
7375     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7376     QualType destType = Context.getPointerType(destPointee);
7377     // Add qualifiers if necessary.
7378     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7379     // Promote to void*.
7380     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7381     return destType;
7382   }
7383   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7384     if (getLangOpts().ObjCAutoRefCount) {
7385       // ARC forbids the implicit conversion of object pointers to 'void *',
7386       // so these types are not compatible.
7387       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7388           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7389       LHS = RHS = true;
7390       return QualType();
7391     }
7392     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7393     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7394     QualType destPointee
7395     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7396     QualType destType = Context.getPointerType(destPointee);
7397     // Add qualifiers if necessary.
7398     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7399     // Promote to void*.
7400     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7401     return destType;
7402   }
7403   return QualType();
7404 }
7405 
7406 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7407 /// ParenRange in parentheses.
7408 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7409                                const PartialDiagnostic &Note,
7410                                SourceRange ParenRange) {
7411   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7412   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7413       EndLoc.isValid()) {
7414     Self.Diag(Loc, Note)
7415       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7416       << FixItHint::CreateInsertion(EndLoc, ")");
7417   } else {
7418     // We can't display the parentheses, so just show the bare note.
7419     Self.Diag(Loc, Note) << ParenRange;
7420   }
7421 }
7422 
7423 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7424   return BinaryOperator::isAdditiveOp(Opc) ||
7425          BinaryOperator::isMultiplicativeOp(Opc) ||
7426          BinaryOperator::isShiftOp(Opc);
7427 }
7428 
7429 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7430 /// expression, either using a built-in or overloaded operator,
7431 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7432 /// expression.
7433 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7434                                    Expr **RHSExprs) {
7435   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7436   E = E->IgnoreImpCasts();
7437   E = E->IgnoreConversionOperator();
7438   E = E->IgnoreImpCasts();
7439   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7440     E = MTE->GetTemporaryExpr();
7441     E = E->IgnoreImpCasts();
7442   }
7443 
7444   // Built-in binary operator.
7445   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7446     if (IsArithmeticOp(OP->getOpcode())) {
7447       *Opcode = OP->getOpcode();
7448       *RHSExprs = OP->getRHS();
7449       return true;
7450     }
7451   }
7452 
7453   // Overloaded operator.
7454   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7455     if (Call->getNumArgs() != 2)
7456       return false;
7457 
7458     // Make sure this is really a binary operator that is safe to pass into
7459     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7460     OverloadedOperatorKind OO = Call->getOperator();
7461     if (OO < OO_Plus || OO > OO_Arrow ||
7462         OO == OO_PlusPlus || OO == OO_MinusMinus)
7463       return false;
7464 
7465     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7466     if (IsArithmeticOp(OpKind)) {
7467       *Opcode = OpKind;
7468       *RHSExprs = Call->getArg(1);
7469       return true;
7470     }
7471   }
7472 
7473   return false;
7474 }
7475 
7476 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7477 /// or is a logical expression such as (x==y) which has int type, but is
7478 /// commonly interpreted as boolean.
7479 static bool ExprLooksBoolean(Expr *E) {
7480   E = E->IgnoreParenImpCasts();
7481 
7482   if (E->getType()->isBooleanType())
7483     return true;
7484   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7485     return OP->isComparisonOp() || OP->isLogicalOp();
7486   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7487     return OP->getOpcode() == UO_LNot;
7488   if (E->getType()->isPointerType())
7489     return true;
7490   // FIXME: What about overloaded operator calls returning "unspecified boolean
7491   // type"s (commonly pointer-to-members)?
7492 
7493   return false;
7494 }
7495 
7496 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7497 /// and binary operator are mixed in a way that suggests the programmer assumed
7498 /// the conditional operator has higher precedence, for example:
7499 /// "int x = a + someBinaryCondition ? 1 : 2".
7500 static void DiagnoseConditionalPrecedence(Sema &Self,
7501                                           SourceLocation OpLoc,
7502                                           Expr *Condition,
7503                                           Expr *LHSExpr,
7504                                           Expr *RHSExpr) {
7505   BinaryOperatorKind CondOpcode;
7506   Expr *CondRHS;
7507 
7508   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7509     return;
7510   if (!ExprLooksBoolean(CondRHS))
7511     return;
7512 
7513   // The condition is an arithmetic binary expression, with a right-
7514   // hand side that looks boolean, so warn.
7515 
7516   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7517       << Condition->getSourceRange()
7518       << BinaryOperator::getOpcodeStr(CondOpcode);
7519 
7520   SuggestParentheses(
7521       Self, OpLoc,
7522       Self.PDiag(diag::note_precedence_silence)
7523           << BinaryOperator::getOpcodeStr(CondOpcode),
7524       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7525 
7526   SuggestParentheses(Self, OpLoc,
7527                      Self.PDiag(diag::note_precedence_conditional_first),
7528                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7529 }
7530 
7531 /// Compute the nullability of a conditional expression.
7532 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7533                                               QualType LHSTy, QualType RHSTy,
7534                                               ASTContext &Ctx) {
7535   if (!ResTy->isAnyPointerType())
7536     return ResTy;
7537 
7538   auto GetNullability = [&Ctx](QualType Ty) {
7539     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7540     if (Kind)
7541       return *Kind;
7542     return NullabilityKind::Unspecified;
7543   };
7544 
7545   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7546   NullabilityKind MergedKind;
7547 
7548   // Compute nullability of a binary conditional expression.
7549   if (IsBin) {
7550     if (LHSKind == NullabilityKind::NonNull)
7551       MergedKind = NullabilityKind::NonNull;
7552     else
7553       MergedKind = RHSKind;
7554   // Compute nullability of a normal conditional expression.
7555   } else {
7556     if (LHSKind == NullabilityKind::Nullable ||
7557         RHSKind == NullabilityKind::Nullable)
7558       MergedKind = NullabilityKind::Nullable;
7559     else if (LHSKind == NullabilityKind::NonNull)
7560       MergedKind = RHSKind;
7561     else if (RHSKind == NullabilityKind::NonNull)
7562       MergedKind = LHSKind;
7563     else
7564       MergedKind = NullabilityKind::Unspecified;
7565   }
7566 
7567   // Return if ResTy already has the correct nullability.
7568   if (GetNullability(ResTy) == MergedKind)
7569     return ResTy;
7570 
7571   // Strip all nullability from ResTy.
7572   while (ResTy->getNullability(Ctx))
7573     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7574 
7575   // Create a new AttributedType with the new nullability kind.
7576   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7577   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7578 }
7579 
7580 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7581 /// in the case of a the GNU conditional expr extension.
7582 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7583                                     SourceLocation ColonLoc,
7584                                     Expr *CondExpr, Expr *LHSExpr,
7585                                     Expr *RHSExpr) {
7586   if (!getLangOpts().CPlusPlus) {
7587     // C cannot handle TypoExpr nodes in the condition because it
7588     // doesn't handle dependent types properly, so make sure any TypoExprs have
7589     // been dealt with before checking the operands.
7590     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7591     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7592     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7593 
7594     if (!CondResult.isUsable())
7595       return ExprError();
7596 
7597     if (LHSExpr) {
7598       if (!LHSResult.isUsable())
7599         return ExprError();
7600     }
7601 
7602     if (!RHSResult.isUsable())
7603       return ExprError();
7604 
7605     CondExpr = CondResult.get();
7606     LHSExpr = LHSResult.get();
7607     RHSExpr = RHSResult.get();
7608   }
7609 
7610   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7611   // was the condition.
7612   OpaqueValueExpr *opaqueValue = nullptr;
7613   Expr *commonExpr = nullptr;
7614   if (!LHSExpr) {
7615     commonExpr = CondExpr;
7616     // Lower out placeholder types first.  This is important so that we don't
7617     // try to capture a placeholder. This happens in few cases in C++; such
7618     // as Objective-C++'s dictionary subscripting syntax.
7619     if (commonExpr->hasPlaceholderType()) {
7620       ExprResult result = CheckPlaceholderExpr(commonExpr);
7621       if (!result.isUsable()) return ExprError();
7622       commonExpr = result.get();
7623     }
7624     // We usually want to apply unary conversions *before* saving, except
7625     // in the special case of a C++ l-value conditional.
7626     if (!(getLangOpts().CPlusPlus
7627           && !commonExpr->isTypeDependent()
7628           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7629           && commonExpr->isGLValue()
7630           && commonExpr->isOrdinaryOrBitFieldObject()
7631           && RHSExpr->isOrdinaryOrBitFieldObject()
7632           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7633       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7634       if (commonRes.isInvalid())
7635         return ExprError();
7636       commonExpr = commonRes.get();
7637     }
7638 
7639     // If the common expression is a class or array prvalue, materialize it
7640     // so that we can safely refer to it multiple times.
7641     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7642                                    commonExpr->getType()->isArrayType())) {
7643       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7644       if (MatExpr.isInvalid())
7645         return ExprError();
7646       commonExpr = MatExpr.get();
7647     }
7648 
7649     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7650                                                 commonExpr->getType(),
7651                                                 commonExpr->getValueKind(),
7652                                                 commonExpr->getObjectKind(),
7653                                                 commonExpr);
7654     LHSExpr = CondExpr = opaqueValue;
7655   }
7656 
7657   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7658   ExprValueKind VK = VK_RValue;
7659   ExprObjectKind OK = OK_Ordinary;
7660   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7661   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7662                                              VK, OK, QuestionLoc);
7663   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7664       RHS.isInvalid())
7665     return ExprError();
7666 
7667   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7668                                 RHS.get());
7669 
7670   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7671 
7672   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7673                                          Context);
7674 
7675   if (!commonExpr)
7676     return new (Context)
7677         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7678                             RHS.get(), result, VK, OK);
7679 
7680   return new (Context) BinaryConditionalOperator(
7681       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7682       ColonLoc, result, VK, OK);
7683 }
7684 
7685 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7686 // being closely modeled after the C99 spec:-). The odd characteristic of this
7687 // routine is it effectively iqnores the qualifiers on the top level pointee.
7688 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7689 // FIXME: add a couple examples in this comment.
7690 static Sema::AssignConvertType
7691 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7692   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7693   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7694 
7695   // get the "pointed to" type (ignoring qualifiers at the top level)
7696   const Type *lhptee, *rhptee;
7697   Qualifiers lhq, rhq;
7698   std::tie(lhptee, lhq) =
7699       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7700   std::tie(rhptee, rhq) =
7701       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7702 
7703   Sema::AssignConvertType ConvTy = Sema::Compatible;
7704 
7705   // C99 6.5.16.1p1: This following citation is common to constraints
7706   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7707   // qualifiers of the type *pointed to* by the right;
7708 
7709   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7710   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7711       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7712     // Ignore lifetime for further calculation.
7713     lhq.removeObjCLifetime();
7714     rhq.removeObjCLifetime();
7715   }
7716 
7717   if (!lhq.compatiblyIncludes(rhq)) {
7718     // Treat address-space mismatches as fatal.  TODO: address subspaces
7719     if (!lhq.isAddressSpaceSupersetOf(rhq))
7720       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7721 
7722     // It's okay to add or remove GC or lifetime qualifiers when converting to
7723     // and from void*.
7724     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7725                         .compatiblyIncludes(
7726                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7727              && (lhptee->isVoidType() || rhptee->isVoidType()))
7728       ; // keep old
7729 
7730     // Treat lifetime mismatches as fatal.
7731     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7732       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7733 
7734     // For GCC/MS compatibility, other qualifier mismatches are treated
7735     // as still compatible in C.
7736     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7737   }
7738 
7739   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7740   // incomplete type and the other is a pointer to a qualified or unqualified
7741   // version of void...
7742   if (lhptee->isVoidType()) {
7743     if (rhptee->isIncompleteOrObjectType())
7744       return ConvTy;
7745 
7746     // As an extension, we allow cast to/from void* to function pointer.
7747     assert(rhptee->isFunctionType());
7748     return Sema::FunctionVoidPointer;
7749   }
7750 
7751   if (rhptee->isVoidType()) {
7752     if (lhptee->isIncompleteOrObjectType())
7753       return ConvTy;
7754 
7755     // As an extension, we allow cast to/from void* to function pointer.
7756     assert(lhptee->isFunctionType());
7757     return Sema::FunctionVoidPointer;
7758   }
7759 
7760   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7761   // unqualified versions of compatible types, ...
7762   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7763   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7764     // Check if the pointee types are compatible ignoring the sign.
7765     // We explicitly check for char so that we catch "char" vs
7766     // "unsigned char" on systems where "char" is unsigned.
7767     if (lhptee->isCharType())
7768       ltrans = S.Context.UnsignedCharTy;
7769     else if (lhptee->hasSignedIntegerRepresentation())
7770       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7771 
7772     if (rhptee->isCharType())
7773       rtrans = S.Context.UnsignedCharTy;
7774     else if (rhptee->hasSignedIntegerRepresentation())
7775       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7776 
7777     if (ltrans == rtrans) {
7778       // Types are compatible ignoring the sign. Qualifier incompatibility
7779       // takes priority over sign incompatibility because the sign
7780       // warning can be disabled.
7781       if (ConvTy != Sema::Compatible)
7782         return ConvTy;
7783 
7784       return Sema::IncompatiblePointerSign;
7785     }
7786 
7787     // If we are a multi-level pointer, it's possible that our issue is simply
7788     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7789     // the eventual target type is the same and the pointers have the same
7790     // level of indirection, this must be the issue.
7791     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7792       do {
7793         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7794         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7795       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7796 
7797       if (lhptee == rhptee)
7798         return Sema::IncompatibleNestedPointerQualifiers;
7799     }
7800 
7801     // General pointer incompatibility takes priority over qualifiers.
7802     return Sema::IncompatiblePointer;
7803   }
7804   if (!S.getLangOpts().CPlusPlus &&
7805       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7806     return Sema::IncompatiblePointer;
7807   return ConvTy;
7808 }
7809 
7810 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7811 /// block pointer types are compatible or whether a block and normal pointer
7812 /// are compatible. It is more restrict than comparing two function pointer
7813 // types.
7814 static Sema::AssignConvertType
7815 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7816                                     QualType RHSType) {
7817   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7818   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7819 
7820   QualType lhptee, rhptee;
7821 
7822   // get the "pointed to" type (ignoring qualifiers at the top level)
7823   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7824   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7825 
7826   // In C++, the types have to match exactly.
7827   if (S.getLangOpts().CPlusPlus)
7828     return Sema::IncompatibleBlockPointer;
7829 
7830   Sema::AssignConvertType ConvTy = Sema::Compatible;
7831 
7832   // For blocks we enforce that qualifiers are identical.
7833   Qualifiers LQuals = lhptee.getLocalQualifiers();
7834   Qualifiers RQuals = rhptee.getLocalQualifiers();
7835   if (S.getLangOpts().OpenCL) {
7836     LQuals.removeAddressSpace();
7837     RQuals.removeAddressSpace();
7838   }
7839   if (LQuals != RQuals)
7840     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7841 
7842   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7843   // assignment.
7844   // The current behavior is similar to C++ lambdas. A block might be
7845   // assigned to a variable iff its return type and parameters are compatible
7846   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7847   // an assignment. Presumably it should behave in way that a function pointer
7848   // assignment does in C, so for each parameter and return type:
7849   //  * CVR and address space of LHS should be a superset of CVR and address
7850   //  space of RHS.
7851   //  * unqualified types should be compatible.
7852   if (S.getLangOpts().OpenCL) {
7853     if (!S.Context.typesAreBlockPointerCompatible(
7854             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7855             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7856       return Sema::IncompatibleBlockPointer;
7857   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7858     return Sema::IncompatibleBlockPointer;
7859 
7860   return ConvTy;
7861 }
7862 
7863 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7864 /// for assignment compatibility.
7865 static Sema::AssignConvertType
7866 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7867                                    QualType RHSType) {
7868   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7869   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7870 
7871   if (LHSType->isObjCBuiltinType()) {
7872     // Class is not compatible with ObjC object pointers.
7873     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7874         !RHSType->isObjCQualifiedClassType())
7875       return Sema::IncompatiblePointer;
7876     return Sema::Compatible;
7877   }
7878   if (RHSType->isObjCBuiltinType()) {
7879     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7880         !LHSType->isObjCQualifiedClassType())
7881       return Sema::IncompatiblePointer;
7882     return Sema::Compatible;
7883   }
7884   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7885   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7886 
7887   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7888       // make an exception for id<P>
7889       !LHSType->isObjCQualifiedIdType())
7890     return Sema::CompatiblePointerDiscardsQualifiers;
7891 
7892   if (S.Context.typesAreCompatible(LHSType, RHSType))
7893     return Sema::Compatible;
7894   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7895     return Sema::IncompatibleObjCQualifiedId;
7896   return Sema::IncompatiblePointer;
7897 }
7898 
7899 Sema::AssignConvertType
7900 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7901                                  QualType LHSType, QualType RHSType) {
7902   // Fake up an opaque expression.  We don't actually care about what
7903   // cast operations are required, so if CheckAssignmentConstraints
7904   // adds casts to this they'll be wasted, but fortunately that doesn't
7905   // usually happen on valid code.
7906   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7907   ExprResult RHSPtr = &RHSExpr;
7908   CastKind K;
7909 
7910   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7911 }
7912 
7913 /// This helper function returns true if QT is a vector type that has element
7914 /// type ElementType.
7915 static bool isVector(QualType QT, QualType ElementType) {
7916   if (const VectorType *VT = QT->getAs<VectorType>())
7917     return VT->getElementType() == ElementType;
7918   return false;
7919 }
7920 
7921 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7922 /// has code to accommodate several GCC extensions when type checking
7923 /// pointers. Here are some objectionable examples that GCC considers warnings:
7924 ///
7925 ///  int a, *pint;
7926 ///  short *pshort;
7927 ///  struct foo *pfoo;
7928 ///
7929 ///  pint = pshort; // warning: assignment from incompatible pointer type
7930 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7931 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7932 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7933 ///
7934 /// As a result, the code for dealing with pointers is more complex than the
7935 /// C99 spec dictates.
7936 ///
7937 /// Sets 'Kind' for any result kind except Incompatible.
7938 Sema::AssignConvertType
7939 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7940                                  CastKind &Kind, bool ConvertRHS) {
7941   QualType RHSType = RHS.get()->getType();
7942   QualType OrigLHSType = LHSType;
7943 
7944   // Get canonical types.  We're not formatting these types, just comparing
7945   // them.
7946   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7947   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7948 
7949   // Common case: no conversion required.
7950   if (LHSType == RHSType) {
7951     Kind = CK_NoOp;
7952     return Compatible;
7953   }
7954 
7955   // If we have an atomic type, try a non-atomic assignment, then just add an
7956   // atomic qualification step.
7957   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7958     Sema::AssignConvertType result =
7959       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7960     if (result != Compatible)
7961       return result;
7962     if (Kind != CK_NoOp && ConvertRHS)
7963       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7964     Kind = CK_NonAtomicToAtomic;
7965     return Compatible;
7966   }
7967 
7968   // If the left-hand side is a reference type, then we are in a
7969   // (rare!) case where we've allowed the use of references in C,
7970   // e.g., as a parameter type in a built-in function. In this case,
7971   // just make sure that the type referenced is compatible with the
7972   // right-hand side type. The caller is responsible for adjusting
7973   // LHSType so that the resulting expression does not have reference
7974   // type.
7975   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7976     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7977       Kind = CK_LValueBitCast;
7978       return Compatible;
7979     }
7980     return Incompatible;
7981   }
7982 
7983   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7984   // to the same ExtVector type.
7985   if (LHSType->isExtVectorType()) {
7986     if (RHSType->isExtVectorType())
7987       return Incompatible;
7988     if (RHSType->isArithmeticType()) {
7989       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7990       if (ConvertRHS)
7991         RHS = prepareVectorSplat(LHSType, RHS.get());
7992       Kind = CK_VectorSplat;
7993       return Compatible;
7994     }
7995   }
7996 
7997   // Conversions to or from vector type.
7998   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7999     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8000       // Allow assignments of an AltiVec vector type to an equivalent GCC
8001       // vector type and vice versa
8002       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8003         Kind = CK_BitCast;
8004         return Compatible;
8005       }
8006 
8007       // If we are allowing lax vector conversions, and LHS and RHS are both
8008       // vectors, the total size only needs to be the same. This is a bitcast;
8009       // no bits are changed but the result type is different.
8010       if (isLaxVectorConversion(RHSType, LHSType)) {
8011         Kind = CK_BitCast;
8012         return IncompatibleVectors;
8013       }
8014     }
8015 
8016     // When the RHS comes from another lax conversion (e.g. binops between
8017     // scalars and vectors) the result is canonicalized as a vector. When the
8018     // LHS is also a vector, the lax is allowed by the condition above. Handle
8019     // the case where LHS is a scalar.
8020     if (LHSType->isScalarType()) {
8021       const VectorType *VecType = RHSType->getAs<VectorType>();
8022       if (VecType && VecType->getNumElements() == 1 &&
8023           isLaxVectorConversion(RHSType, LHSType)) {
8024         ExprResult *VecExpr = &RHS;
8025         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8026         Kind = CK_BitCast;
8027         return Compatible;
8028       }
8029     }
8030 
8031     return Incompatible;
8032   }
8033 
8034   // Diagnose attempts to convert between __float128 and long double where
8035   // such conversions currently can't be handled.
8036   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8037     return Incompatible;
8038 
8039   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8040   // discards the imaginary part.
8041   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8042       !LHSType->getAs<ComplexType>())
8043     return Incompatible;
8044 
8045   // Arithmetic conversions.
8046   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8047       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8048     if (ConvertRHS)
8049       Kind = PrepareScalarCast(RHS, LHSType);
8050     return Compatible;
8051   }
8052 
8053   // Conversions to normal pointers.
8054   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8055     // U* -> T*
8056     if (isa<PointerType>(RHSType)) {
8057       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8058       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8059       if (AddrSpaceL != AddrSpaceR)
8060         Kind = CK_AddressSpaceConversion;
8061       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8062         Kind = CK_NoOp;
8063       else
8064         Kind = CK_BitCast;
8065       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8066     }
8067 
8068     // int -> T*
8069     if (RHSType->isIntegerType()) {
8070       Kind = CK_IntegralToPointer; // FIXME: null?
8071       return IntToPointer;
8072     }
8073 
8074     // C pointers are not compatible with ObjC object pointers,
8075     // with two exceptions:
8076     if (isa<ObjCObjectPointerType>(RHSType)) {
8077       //  - conversions to void*
8078       if (LHSPointer->getPointeeType()->isVoidType()) {
8079         Kind = CK_BitCast;
8080         return Compatible;
8081       }
8082 
8083       //  - conversions from 'Class' to the redefinition type
8084       if (RHSType->isObjCClassType() &&
8085           Context.hasSameType(LHSType,
8086                               Context.getObjCClassRedefinitionType())) {
8087         Kind = CK_BitCast;
8088         return Compatible;
8089       }
8090 
8091       Kind = CK_BitCast;
8092       return IncompatiblePointer;
8093     }
8094 
8095     // U^ -> void*
8096     if (RHSType->getAs<BlockPointerType>()) {
8097       if (LHSPointer->getPointeeType()->isVoidType()) {
8098         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8099         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8100                                 ->getPointeeType()
8101                                 .getAddressSpace();
8102         Kind =
8103             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8104         return Compatible;
8105       }
8106     }
8107 
8108     return Incompatible;
8109   }
8110 
8111   // Conversions to block pointers.
8112   if (isa<BlockPointerType>(LHSType)) {
8113     // U^ -> T^
8114     if (RHSType->isBlockPointerType()) {
8115       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8116                               ->getPointeeType()
8117                               .getAddressSpace();
8118       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8119                               ->getPointeeType()
8120                               .getAddressSpace();
8121       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8122       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8123     }
8124 
8125     // int or null -> T^
8126     if (RHSType->isIntegerType()) {
8127       Kind = CK_IntegralToPointer; // FIXME: null
8128       return IntToBlockPointer;
8129     }
8130 
8131     // id -> T^
8132     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8133       Kind = CK_AnyPointerToBlockPointerCast;
8134       return Compatible;
8135     }
8136 
8137     // void* -> T^
8138     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8139       if (RHSPT->getPointeeType()->isVoidType()) {
8140         Kind = CK_AnyPointerToBlockPointerCast;
8141         return Compatible;
8142       }
8143 
8144     return Incompatible;
8145   }
8146 
8147   // Conversions to Objective-C pointers.
8148   if (isa<ObjCObjectPointerType>(LHSType)) {
8149     // A* -> B*
8150     if (RHSType->isObjCObjectPointerType()) {
8151       Kind = CK_BitCast;
8152       Sema::AssignConvertType result =
8153         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8154       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8155           result == Compatible &&
8156           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8157         result = IncompatibleObjCWeakRef;
8158       return result;
8159     }
8160 
8161     // int or null -> A*
8162     if (RHSType->isIntegerType()) {
8163       Kind = CK_IntegralToPointer; // FIXME: null
8164       return IntToPointer;
8165     }
8166 
8167     // In general, C pointers are not compatible with ObjC object pointers,
8168     // with two exceptions:
8169     if (isa<PointerType>(RHSType)) {
8170       Kind = CK_CPointerToObjCPointerCast;
8171 
8172       //  - conversions from 'void*'
8173       if (RHSType->isVoidPointerType()) {
8174         return Compatible;
8175       }
8176 
8177       //  - conversions to 'Class' from its redefinition type
8178       if (LHSType->isObjCClassType() &&
8179           Context.hasSameType(RHSType,
8180                               Context.getObjCClassRedefinitionType())) {
8181         return Compatible;
8182       }
8183 
8184       return IncompatiblePointer;
8185     }
8186 
8187     // Only under strict condition T^ is compatible with an Objective-C pointer.
8188     if (RHSType->isBlockPointerType() &&
8189         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8190       if (ConvertRHS)
8191         maybeExtendBlockObject(RHS);
8192       Kind = CK_BlockPointerToObjCPointerCast;
8193       return Compatible;
8194     }
8195 
8196     return Incompatible;
8197   }
8198 
8199   // Conversions from pointers that are not covered by the above.
8200   if (isa<PointerType>(RHSType)) {
8201     // T* -> _Bool
8202     if (LHSType == Context.BoolTy) {
8203       Kind = CK_PointerToBoolean;
8204       return Compatible;
8205     }
8206 
8207     // T* -> int
8208     if (LHSType->isIntegerType()) {
8209       Kind = CK_PointerToIntegral;
8210       return PointerToInt;
8211     }
8212 
8213     return Incompatible;
8214   }
8215 
8216   // Conversions from Objective-C pointers that are not covered by the above.
8217   if (isa<ObjCObjectPointerType>(RHSType)) {
8218     // T* -> _Bool
8219     if (LHSType == Context.BoolTy) {
8220       Kind = CK_PointerToBoolean;
8221       return Compatible;
8222     }
8223 
8224     // T* -> int
8225     if (LHSType->isIntegerType()) {
8226       Kind = CK_PointerToIntegral;
8227       return PointerToInt;
8228     }
8229 
8230     return Incompatible;
8231   }
8232 
8233   // struct A -> struct B
8234   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8235     if (Context.typesAreCompatible(LHSType, RHSType)) {
8236       Kind = CK_NoOp;
8237       return Compatible;
8238     }
8239   }
8240 
8241   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8242     Kind = CK_IntToOCLSampler;
8243     return Compatible;
8244   }
8245 
8246   return Incompatible;
8247 }
8248 
8249 /// Constructs a transparent union from an expression that is
8250 /// used to initialize the transparent union.
8251 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8252                                       ExprResult &EResult, QualType UnionType,
8253                                       FieldDecl *Field) {
8254   // Build an initializer list that designates the appropriate member
8255   // of the transparent union.
8256   Expr *E = EResult.get();
8257   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8258                                                    E, SourceLocation());
8259   Initializer->setType(UnionType);
8260   Initializer->setInitializedFieldInUnion(Field);
8261 
8262   // Build a compound literal constructing a value of the transparent
8263   // union type from this initializer list.
8264   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8265   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8266                                         VK_RValue, Initializer, false);
8267 }
8268 
8269 Sema::AssignConvertType
8270 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8271                                                ExprResult &RHS) {
8272   QualType RHSType = RHS.get()->getType();
8273 
8274   // If the ArgType is a Union type, we want to handle a potential
8275   // transparent_union GCC extension.
8276   const RecordType *UT = ArgType->getAsUnionType();
8277   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8278     return Incompatible;
8279 
8280   // The field to initialize within the transparent union.
8281   RecordDecl *UD = UT->getDecl();
8282   FieldDecl *InitField = nullptr;
8283   // It's compatible if the expression matches any of the fields.
8284   for (auto *it : UD->fields()) {
8285     if (it->getType()->isPointerType()) {
8286       // If the transparent union contains a pointer type, we allow:
8287       // 1) void pointer
8288       // 2) null pointer constant
8289       if (RHSType->isPointerType())
8290         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8291           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8292           InitField = it;
8293           break;
8294         }
8295 
8296       if (RHS.get()->isNullPointerConstant(Context,
8297                                            Expr::NPC_ValueDependentIsNull)) {
8298         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8299                                 CK_NullToPointer);
8300         InitField = it;
8301         break;
8302       }
8303     }
8304 
8305     CastKind Kind;
8306     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8307           == Compatible) {
8308       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8309       InitField = it;
8310       break;
8311     }
8312   }
8313 
8314   if (!InitField)
8315     return Incompatible;
8316 
8317   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8318   return Compatible;
8319 }
8320 
8321 Sema::AssignConvertType
8322 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8323                                        bool Diagnose,
8324                                        bool DiagnoseCFAudited,
8325                                        bool ConvertRHS) {
8326   // We need to be able to tell the caller whether we diagnosed a problem, if
8327   // they ask us to issue diagnostics.
8328   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8329 
8330   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8331   // we can't avoid *all* modifications at the moment, so we need some somewhere
8332   // to put the updated value.
8333   ExprResult LocalRHS = CallerRHS;
8334   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8335 
8336   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8337     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8338       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8339           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8340         Diag(RHS.get()->getExprLoc(),
8341              diag::warn_noderef_to_dereferenceable_pointer)
8342             << RHS.get()->getSourceRange();
8343       }
8344     }
8345   }
8346 
8347   if (getLangOpts().CPlusPlus) {
8348     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8349       // C++ 5.17p3: If the left operand is not of class type, the
8350       // expression is implicitly converted (C++ 4) to the
8351       // cv-unqualified type of the left operand.
8352       QualType RHSType = RHS.get()->getType();
8353       if (Diagnose) {
8354         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8355                                         AA_Assigning);
8356       } else {
8357         ImplicitConversionSequence ICS =
8358             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8359                                   /*SuppressUserConversions=*/false,
8360                                   /*AllowExplicit=*/false,
8361                                   /*InOverloadResolution=*/false,
8362                                   /*CStyle=*/false,
8363                                   /*AllowObjCWritebackConversion=*/false);
8364         if (ICS.isFailure())
8365           return Incompatible;
8366         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8367                                         ICS, AA_Assigning);
8368       }
8369       if (RHS.isInvalid())
8370         return Incompatible;
8371       Sema::AssignConvertType result = Compatible;
8372       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8373           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8374         result = IncompatibleObjCWeakRef;
8375       return result;
8376     }
8377 
8378     // FIXME: Currently, we fall through and treat C++ classes like C
8379     // structures.
8380     // FIXME: We also fall through for atomics; not sure what should
8381     // happen there, though.
8382   } else if (RHS.get()->getType() == Context.OverloadTy) {
8383     // As a set of extensions to C, we support overloading on functions. These
8384     // functions need to be resolved here.
8385     DeclAccessPair DAP;
8386     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8387             RHS.get(), LHSType, /*Complain=*/false, DAP))
8388       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8389     else
8390       return Incompatible;
8391   }
8392 
8393   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8394   // a null pointer constant.
8395   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8396        LHSType->isBlockPointerType()) &&
8397       RHS.get()->isNullPointerConstant(Context,
8398                                        Expr::NPC_ValueDependentIsNull)) {
8399     if (Diagnose || ConvertRHS) {
8400       CastKind Kind;
8401       CXXCastPath Path;
8402       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8403                              /*IgnoreBaseAccess=*/false, Diagnose);
8404       if (ConvertRHS)
8405         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8406     }
8407     return Compatible;
8408   }
8409 
8410   // OpenCL queue_t type assignment.
8411   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8412                                  Context, Expr::NPC_ValueDependentIsNull)) {
8413     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8414     return Compatible;
8415   }
8416 
8417   // This check seems unnatural, however it is necessary to ensure the proper
8418   // conversion of functions/arrays. If the conversion were done for all
8419   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8420   // expressions that suppress this implicit conversion (&, sizeof).
8421   //
8422   // Suppress this for references: C++ 8.5.3p5.
8423   if (!LHSType->isReferenceType()) {
8424     // FIXME: We potentially allocate here even if ConvertRHS is false.
8425     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8426     if (RHS.isInvalid())
8427       return Incompatible;
8428   }
8429   CastKind Kind;
8430   Sema::AssignConvertType result =
8431     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8432 
8433   // C99 6.5.16.1p2: The value of the right operand is converted to the
8434   // type of the assignment expression.
8435   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8436   // so that we can use references in built-in functions even in C.
8437   // The getNonReferenceType() call makes sure that the resulting expression
8438   // does not have reference type.
8439   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8440     QualType Ty = LHSType.getNonLValueExprType(Context);
8441     Expr *E = RHS.get();
8442 
8443     // Check for various Objective-C errors. If we are not reporting
8444     // diagnostics and just checking for errors, e.g., during overload
8445     // resolution, return Incompatible to indicate the failure.
8446     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8447         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8448                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8449       if (!Diagnose)
8450         return Incompatible;
8451     }
8452     if (getLangOpts().ObjC &&
8453         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8454                                            E->getType(), E, Diagnose) ||
8455          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8456       if (!Diagnose)
8457         return Incompatible;
8458       // Replace the expression with a corrected version and continue so we
8459       // can find further errors.
8460       RHS = E;
8461       return Compatible;
8462     }
8463 
8464     if (ConvertRHS)
8465       RHS = ImpCastExprToType(E, Ty, Kind);
8466   }
8467 
8468   return result;
8469 }
8470 
8471 namespace {
8472 /// The original operand to an operator, prior to the application of the usual
8473 /// arithmetic conversions and converting the arguments of a builtin operator
8474 /// candidate.
8475 struct OriginalOperand {
8476   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8477     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8478       Op = MTE->GetTemporaryExpr();
8479     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8480       Op = BTE->getSubExpr();
8481     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8482       Orig = ICE->getSubExprAsWritten();
8483       Conversion = ICE->getConversionFunction();
8484     }
8485   }
8486 
8487   QualType getType() const { return Orig->getType(); }
8488 
8489   Expr *Orig;
8490   NamedDecl *Conversion;
8491 };
8492 }
8493 
8494 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8495                                ExprResult &RHS) {
8496   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8497 
8498   Diag(Loc, diag::err_typecheck_invalid_operands)
8499     << OrigLHS.getType() << OrigRHS.getType()
8500     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8501 
8502   // If a user-defined conversion was applied to either of the operands prior
8503   // to applying the built-in operator rules, tell the user about it.
8504   if (OrigLHS.Conversion) {
8505     Diag(OrigLHS.Conversion->getLocation(),
8506          diag::note_typecheck_invalid_operands_converted)
8507       << 0 << LHS.get()->getType();
8508   }
8509   if (OrigRHS.Conversion) {
8510     Diag(OrigRHS.Conversion->getLocation(),
8511          diag::note_typecheck_invalid_operands_converted)
8512       << 1 << RHS.get()->getType();
8513   }
8514 
8515   return QualType();
8516 }
8517 
8518 // Diagnose cases where a scalar was implicitly converted to a vector and
8519 // diagnose the underlying types. Otherwise, diagnose the error
8520 // as invalid vector logical operands for non-C++ cases.
8521 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8522                                             ExprResult &RHS) {
8523   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8524   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8525 
8526   bool LHSNatVec = LHSType->isVectorType();
8527   bool RHSNatVec = RHSType->isVectorType();
8528 
8529   if (!(LHSNatVec && RHSNatVec)) {
8530     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8531     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8532     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8533         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8534         << Vector->getSourceRange();
8535     return QualType();
8536   }
8537 
8538   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8539       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8540       << RHS.get()->getSourceRange();
8541 
8542   return QualType();
8543 }
8544 
8545 /// Try to convert a value of non-vector type to a vector type by converting
8546 /// the type to the element type of the vector and then performing a splat.
8547 /// If the language is OpenCL, we only use conversions that promote scalar
8548 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8549 /// for float->int.
8550 ///
8551 /// OpenCL V2.0 6.2.6.p2:
8552 /// An error shall occur if any scalar operand type has greater rank
8553 /// than the type of the vector element.
8554 ///
8555 /// \param scalar - if non-null, actually perform the conversions
8556 /// \return true if the operation fails (but without diagnosing the failure)
8557 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8558                                      QualType scalarTy,
8559                                      QualType vectorEltTy,
8560                                      QualType vectorTy,
8561                                      unsigned &DiagID) {
8562   // The conversion to apply to the scalar before splatting it,
8563   // if necessary.
8564   CastKind scalarCast = CK_NoOp;
8565 
8566   if (vectorEltTy->isIntegralType(S.Context)) {
8567     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8568         (scalarTy->isIntegerType() &&
8569          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8570       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8571       return true;
8572     }
8573     if (!scalarTy->isIntegralType(S.Context))
8574       return true;
8575     scalarCast = CK_IntegralCast;
8576   } else if (vectorEltTy->isRealFloatingType()) {
8577     if (scalarTy->isRealFloatingType()) {
8578       if (S.getLangOpts().OpenCL &&
8579           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8580         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8581         return true;
8582       }
8583       scalarCast = CK_FloatingCast;
8584     }
8585     else if (scalarTy->isIntegralType(S.Context))
8586       scalarCast = CK_IntegralToFloating;
8587     else
8588       return true;
8589   } else {
8590     return true;
8591   }
8592 
8593   // Adjust scalar if desired.
8594   if (scalar) {
8595     if (scalarCast != CK_NoOp)
8596       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8597     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8598   }
8599   return false;
8600 }
8601 
8602 /// Convert vector E to a vector with the same number of elements but different
8603 /// element type.
8604 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8605   const auto *VecTy = E->getType()->getAs<VectorType>();
8606   assert(VecTy && "Expression E must be a vector");
8607   QualType NewVecTy = S.Context.getVectorType(ElementType,
8608                                               VecTy->getNumElements(),
8609                                               VecTy->getVectorKind());
8610 
8611   // Look through the implicit cast. Return the subexpression if its type is
8612   // NewVecTy.
8613   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8614     if (ICE->getSubExpr()->getType() == NewVecTy)
8615       return ICE->getSubExpr();
8616 
8617   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8618   return S.ImpCastExprToType(E, NewVecTy, Cast);
8619 }
8620 
8621 /// Test if a (constant) integer Int can be casted to another integer type
8622 /// IntTy without losing precision.
8623 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8624                                       QualType OtherIntTy) {
8625   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8626 
8627   // Reject cases where the value of the Int is unknown as that would
8628   // possibly cause truncation, but accept cases where the scalar can be
8629   // demoted without loss of precision.
8630   Expr::EvalResult EVResult;
8631   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8632   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8633   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8634   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8635 
8636   if (CstInt) {
8637     // If the scalar is constant and is of a higher order and has more active
8638     // bits that the vector element type, reject it.
8639     llvm::APSInt Result = EVResult.Val.getInt();
8640     unsigned NumBits = IntSigned
8641                            ? (Result.isNegative() ? Result.getMinSignedBits()
8642                                                   : Result.getActiveBits())
8643                            : Result.getActiveBits();
8644     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8645       return true;
8646 
8647     // If the signedness of the scalar type and the vector element type
8648     // differs and the number of bits is greater than that of the vector
8649     // element reject it.
8650     return (IntSigned != OtherIntSigned &&
8651             NumBits > S.Context.getIntWidth(OtherIntTy));
8652   }
8653 
8654   // Reject cases where the value of the scalar is not constant and it's
8655   // order is greater than that of the vector element type.
8656   return (Order < 0);
8657 }
8658 
8659 /// Test if a (constant) integer Int can be casted to floating point type
8660 /// FloatTy without losing precision.
8661 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8662                                      QualType FloatTy) {
8663   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8664 
8665   // Determine if the integer constant can be expressed as a floating point
8666   // number of the appropriate type.
8667   Expr::EvalResult EVResult;
8668   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8669 
8670   uint64_t Bits = 0;
8671   if (CstInt) {
8672     // Reject constants that would be truncated if they were converted to
8673     // the floating point type. Test by simple to/from conversion.
8674     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8675     //        could be avoided if there was a convertFromAPInt method
8676     //        which could signal back if implicit truncation occurred.
8677     llvm::APSInt Result = EVResult.Val.getInt();
8678     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8679     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8680                            llvm::APFloat::rmTowardZero);
8681     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8682                              !IntTy->hasSignedIntegerRepresentation());
8683     bool Ignored = false;
8684     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8685                            &Ignored);
8686     if (Result != ConvertBack)
8687       return true;
8688   } else {
8689     // Reject types that cannot be fully encoded into the mantissa of
8690     // the float.
8691     Bits = S.Context.getTypeSize(IntTy);
8692     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8693         S.Context.getFloatTypeSemantics(FloatTy));
8694     if (Bits > FloatPrec)
8695       return true;
8696   }
8697 
8698   return false;
8699 }
8700 
8701 /// Attempt to convert and splat Scalar into a vector whose types matches
8702 /// Vector following GCC conversion rules. The rule is that implicit
8703 /// conversion can occur when Scalar can be casted to match Vector's element
8704 /// type without causing truncation of Scalar.
8705 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8706                                         ExprResult *Vector) {
8707   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8708   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8709   const VectorType *VT = VectorTy->getAs<VectorType>();
8710 
8711   assert(!isa<ExtVectorType>(VT) &&
8712          "ExtVectorTypes should not be handled here!");
8713 
8714   QualType VectorEltTy = VT->getElementType();
8715 
8716   // Reject cases where the vector element type or the scalar element type are
8717   // not integral or floating point types.
8718   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8719     return true;
8720 
8721   // The conversion to apply to the scalar before splatting it,
8722   // if necessary.
8723   CastKind ScalarCast = CK_NoOp;
8724 
8725   // Accept cases where the vector elements are integers and the scalar is
8726   // an integer.
8727   // FIXME: Notionally if the scalar was a floating point value with a precise
8728   //        integral representation, we could cast it to an appropriate integer
8729   //        type and then perform the rest of the checks here. GCC will perform
8730   //        this conversion in some cases as determined by the input language.
8731   //        We should accept it on a language independent basis.
8732   if (VectorEltTy->isIntegralType(S.Context) &&
8733       ScalarTy->isIntegralType(S.Context) &&
8734       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8735 
8736     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8737       return true;
8738 
8739     ScalarCast = CK_IntegralCast;
8740   } else if (VectorEltTy->isRealFloatingType()) {
8741     if (ScalarTy->isRealFloatingType()) {
8742 
8743       // Reject cases where the scalar type is not a constant and has a higher
8744       // Order than the vector element type.
8745       llvm::APFloat Result(0.0);
8746       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8747       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8748       if (!CstScalar && Order < 0)
8749         return true;
8750 
8751       // If the scalar cannot be safely casted to the vector element type,
8752       // reject it.
8753       if (CstScalar) {
8754         bool Truncated = false;
8755         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8756                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8757         if (Truncated)
8758           return true;
8759       }
8760 
8761       ScalarCast = CK_FloatingCast;
8762     } else if (ScalarTy->isIntegralType(S.Context)) {
8763       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8764         return true;
8765 
8766       ScalarCast = CK_IntegralToFloating;
8767     } else
8768       return true;
8769   }
8770 
8771   // Adjust scalar if desired.
8772   if (Scalar) {
8773     if (ScalarCast != CK_NoOp)
8774       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8775     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8776   }
8777   return false;
8778 }
8779 
8780 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8781                                    SourceLocation Loc, bool IsCompAssign,
8782                                    bool AllowBothBool,
8783                                    bool AllowBoolConversions) {
8784   if (!IsCompAssign) {
8785     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8786     if (LHS.isInvalid())
8787       return QualType();
8788   }
8789   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8790   if (RHS.isInvalid())
8791     return QualType();
8792 
8793   // For conversion purposes, we ignore any qualifiers.
8794   // For example, "const float" and "float" are equivalent.
8795   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8796   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8797 
8798   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8799   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8800   assert(LHSVecType || RHSVecType);
8801 
8802   // AltiVec-style "vector bool op vector bool" combinations are allowed
8803   // for some operators but not others.
8804   if (!AllowBothBool &&
8805       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8806       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8807     return InvalidOperands(Loc, LHS, RHS);
8808 
8809   // If the vector types are identical, return.
8810   if (Context.hasSameType(LHSType, RHSType))
8811     return LHSType;
8812 
8813   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8814   if (LHSVecType && RHSVecType &&
8815       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8816     if (isa<ExtVectorType>(LHSVecType)) {
8817       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8818       return LHSType;
8819     }
8820 
8821     if (!IsCompAssign)
8822       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8823     return RHSType;
8824   }
8825 
8826   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8827   // can be mixed, with the result being the non-bool type.  The non-bool
8828   // operand must have integer element type.
8829   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8830       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8831       (Context.getTypeSize(LHSVecType->getElementType()) ==
8832        Context.getTypeSize(RHSVecType->getElementType()))) {
8833     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8834         LHSVecType->getElementType()->isIntegerType() &&
8835         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8836       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8837       return LHSType;
8838     }
8839     if (!IsCompAssign &&
8840         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8841         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8842         RHSVecType->getElementType()->isIntegerType()) {
8843       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8844       return RHSType;
8845     }
8846   }
8847 
8848   // If there's a vector type and a scalar, try to convert the scalar to
8849   // the vector element type and splat.
8850   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8851   if (!RHSVecType) {
8852     if (isa<ExtVectorType>(LHSVecType)) {
8853       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8854                                     LHSVecType->getElementType(), LHSType,
8855                                     DiagID))
8856         return LHSType;
8857     } else {
8858       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8859         return LHSType;
8860     }
8861   }
8862   if (!LHSVecType) {
8863     if (isa<ExtVectorType>(RHSVecType)) {
8864       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8865                                     LHSType, RHSVecType->getElementType(),
8866                                     RHSType, DiagID))
8867         return RHSType;
8868     } else {
8869       if (LHS.get()->getValueKind() == VK_LValue ||
8870           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8871         return RHSType;
8872     }
8873   }
8874 
8875   // FIXME: The code below also handles conversion between vectors and
8876   // non-scalars, we should break this down into fine grained specific checks
8877   // and emit proper diagnostics.
8878   QualType VecType = LHSVecType ? LHSType : RHSType;
8879   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8880   QualType OtherType = LHSVecType ? RHSType : LHSType;
8881   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8882   if (isLaxVectorConversion(OtherType, VecType)) {
8883     // If we're allowing lax vector conversions, only the total (data) size
8884     // needs to be the same. For non compound assignment, if one of the types is
8885     // scalar, the result is always the vector type.
8886     if (!IsCompAssign) {
8887       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8888       return VecType;
8889     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8890     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8891     // type. Note that this is already done by non-compound assignments in
8892     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8893     // <1 x T> -> T. The result is also a vector type.
8894     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8895                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8896       ExprResult *RHSExpr = &RHS;
8897       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8898       return VecType;
8899     }
8900   }
8901 
8902   // Okay, the expression is invalid.
8903 
8904   // If there's a non-vector, non-real operand, diagnose that.
8905   if ((!RHSVecType && !RHSType->isRealType()) ||
8906       (!LHSVecType && !LHSType->isRealType())) {
8907     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8908       << LHSType << RHSType
8909       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8910     return QualType();
8911   }
8912 
8913   // OpenCL V1.1 6.2.6.p1:
8914   // If the operands are of more than one vector type, then an error shall
8915   // occur. Implicit conversions between vector types are not permitted, per
8916   // section 6.2.1.
8917   if (getLangOpts().OpenCL &&
8918       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8919       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8920     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8921                                                            << RHSType;
8922     return QualType();
8923   }
8924 
8925 
8926   // If there is a vector type that is not a ExtVector and a scalar, we reach
8927   // this point if scalar could not be converted to the vector's element type
8928   // without truncation.
8929   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8930       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8931     QualType Scalar = LHSVecType ? RHSType : LHSType;
8932     QualType Vector = LHSVecType ? LHSType : RHSType;
8933     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8934     Diag(Loc,
8935          diag::err_typecheck_vector_not_convertable_implict_truncation)
8936         << ScalarOrVector << Scalar << Vector;
8937 
8938     return QualType();
8939   }
8940 
8941   // Otherwise, use the generic diagnostic.
8942   Diag(Loc, DiagID)
8943     << LHSType << RHSType
8944     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8945   return QualType();
8946 }
8947 
8948 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8949 // expression.  These are mainly cases where the null pointer is used as an
8950 // integer instead of a pointer.
8951 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8952                                 SourceLocation Loc, bool IsCompare) {
8953   // The canonical way to check for a GNU null is with isNullPointerConstant,
8954   // but we use a bit of a hack here for speed; this is a relatively
8955   // hot path, and isNullPointerConstant is slow.
8956   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8957   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8958 
8959   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8960 
8961   // Avoid analyzing cases where the result will either be invalid (and
8962   // diagnosed as such) or entirely valid and not something to warn about.
8963   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8964       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8965     return;
8966 
8967   // Comparison operations would not make sense with a null pointer no matter
8968   // what the other expression is.
8969   if (!IsCompare) {
8970     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8971         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8972         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8973     return;
8974   }
8975 
8976   // The rest of the operations only make sense with a null pointer
8977   // if the other expression is a pointer.
8978   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8979       NonNullType->canDecayToPointerType())
8980     return;
8981 
8982   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8983       << LHSNull /* LHS is NULL */ << NonNullType
8984       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8985 }
8986 
8987 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8988                                           SourceLocation Loc) {
8989   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8990   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
8991   if (!LUE || !RUE)
8992     return;
8993   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
8994       RUE->getKind() != UETT_SizeOf)
8995     return;
8996 
8997   QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
8998   QualType RHSTy;
8999 
9000   if (RUE->isArgumentType())
9001     RHSTy = RUE->getArgumentType();
9002   else
9003     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9004 
9005   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
9006     return;
9007   if (LHSTy->getPointeeType() != RHSTy)
9008     return;
9009 
9010   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9011 }
9012 
9013 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9014                                                ExprResult &RHS,
9015                                                SourceLocation Loc, bool IsDiv) {
9016   // Check for division/remainder by zero.
9017   Expr::EvalResult RHSValue;
9018   if (!RHS.get()->isValueDependent() &&
9019       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9020       RHSValue.Val.getInt() == 0)
9021     S.DiagRuntimeBehavior(Loc, RHS.get(),
9022                           S.PDiag(diag::warn_remainder_division_by_zero)
9023                             << IsDiv << RHS.get()->getSourceRange());
9024 }
9025 
9026 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9027                                            SourceLocation Loc,
9028                                            bool IsCompAssign, bool IsDiv) {
9029   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9030 
9031   if (LHS.get()->getType()->isVectorType() ||
9032       RHS.get()->getType()->isVectorType())
9033     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9034                                /*AllowBothBool*/getLangOpts().AltiVec,
9035                                /*AllowBoolConversions*/false);
9036 
9037   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9038   if (LHS.isInvalid() || RHS.isInvalid())
9039     return QualType();
9040 
9041 
9042   if (compType.isNull() || !compType->isArithmeticType())
9043     return InvalidOperands(Loc, LHS, RHS);
9044   if (IsDiv) {
9045     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9046     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9047   }
9048   return compType;
9049 }
9050 
9051 QualType Sema::CheckRemainderOperands(
9052   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9053   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9054 
9055   if (LHS.get()->getType()->isVectorType() ||
9056       RHS.get()->getType()->isVectorType()) {
9057     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9058         RHS.get()->getType()->hasIntegerRepresentation())
9059       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9060                                  /*AllowBothBool*/getLangOpts().AltiVec,
9061                                  /*AllowBoolConversions*/false);
9062     return InvalidOperands(Loc, LHS, RHS);
9063   }
9064 
9065   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9066   if (LHS.isInvalid() || RHS.isInvalid())
9067     return QualType();
9068 
9069   if (compType.isNull() || !compType->isIntegerType())
9070     return InvalidOperands(Loc, LHS, RHS);
9071   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9072   return compType;
9073 }
9074 
9075 /// Diagnose invalid arithmetic on two void pointers.
9076 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9077                                                 Expr *LHSExpr, Expr *RHSExpr) {
9078   S.Diag(Loc, S.getLangOpts().CPlusPlus
9079                 ? diag::err_typecheck_pointer_arith_void_type
9080                 : diag::ext_gnu_void_ptr)
9081     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9082                             << RHSExpr->getSourceRange();
9083 }
9084 
9085 /// Diagnose invalid arithmetic on a void pointer.
9086 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9087                                             Expr *Pointer) {
9088   S.Diag(Loc, S.getLangOpts().CPlusPlus
9089                 ? diag::err_typecheck_pointer_arith_void_type
9090                 : diag::ext_gnu_void_ptr)
9091     << 0 /* one pointer */ << Pointer->getSourceRange();
9092 }
9093 
9094 /// Diagnose invalid arithmetic on a null pointer.
9095 ///
9096 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9097 /// idiom, which we recognize as a GNU extension.
9098 ///
9099 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9100                                             Expr *Pointer, bool IsGNUIdiom) {
9101   if (IsGNUIdiom)
9102     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9103       << Pointer->getSourceRange();
9104   else
9105     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9106       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9107 }
9108 
9109 /// Diagnose invalid arithmetic on two function pointers.
9110 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9111                                                     Expr *LHS, Expr *RHS) {
9112   assert(LHS->getType()->isAnyPointerType());
9113   assert(RHS->getType()->isAnyPointerType());
9114   S.Diag(Loc, S.getLangOpts().CPlusPlus
9115                 ? diag::err_typecheck_pointer_arith_function_type
9116                 : diag::ext_gnu_ptr_func_arith)
9117     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9118     // We only show the second type if it differs from the first.
9119     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9120                                                    RHS->getType())
9121     << RHS->getType()->getPointeeType()
9122     << LHS->getSourceRange() << RHS->getSourceRange();
9123 }
9124 
9125 /// Diagnose invalid arithmetic on a function pointer.
9126 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9127                                                 Expr *Pointer) {
9128   assert(Pointer->getType()->isAnyPointerType());
9129   S.Diag(Loc, S.getLangOpts().CPlusPlus
9130                 ? diag::err_typecheck_pointer_arith_function_type
9131                 : diag::ext_gnu_ptr_func_arith)
9132     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9133     << 0 /* one pointer, so only one type */
9134     << Pointer->getSourceRange();
9135 }
9136 
9137 /// Emit error if Operand is incomplete pointer type
9138 ///
9139 /// \returns True if pointer has incomplete type
9140 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9141                                                  Expr *Operand) {
9142   QualType ResType = Operand->getType();
9143   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9144     ResType = ResAtomicType->getValueType();
9145 
9146   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9147   QualType PointeeTy = ResType->getPointeeType();
9148   return S.RequireCompleteType(Loc, PointeeTy,
9149                                diag::err_typecheck_arithmetic_incomplete_type,
9150                                PointeeTy, Operand->getSourceRange());
9151 }
9152 
9153 /// Check the validity of an arithmetic pointer operand.
9154 ///
9155 /// If the operand has pointer type, this code will check for pointer types
9156 /// which are invalid in arithmetic operations. These will be diagnosed
9157 /// appropriately, including whether or not the use is supported as an
9158 /// extension.
9159 ///
9160 /// \returns True when the operand is valid to use (even if as an extension).
9161 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9162                                             Expr *Operand) {
9163   QualType ResType = Operand->getType();
9164   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9165     ResType = ResAtomicType->getValueType();
9166 
9167   if (!ResType->isAnyPointerType()) return true;
9168 
9169   QualType PointeeTy = ResType->getPointeeType();
9170   if (PointeeTy->isVoidType()) {
9171     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9172     return !S.getLangOpts().CPlusPlus;
9173   }
9174   if (PointeeTy->isFunctionType()) {
9175     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9176     return !S.getLangOpts().CPlusPlus;
9177   }
9178 
9179   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9180 
9181   return true;
9182 }
9183 
9184 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9185 /// operands.
9186 ///
9187 /// This routine will diagnose any invalid arithmetic on pointer operands much
9188 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9189 /// for emitting a single diagnostic even for operations where both LHS and RHS
9190 /// are (potentially problematic) pointers.
9191 ///
9192 /// \returns True when the operand is valid to use (even if as an extension).
9193 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9194                                                 Expr *LHSExpr, Expr *RHSExpr) {
9195   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9196   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9197   if (!isLHSPointer && !isRHSPointer) return true;
9198 
9199   QualType LHSPointeeTy, RHSPointeeTy;
9200   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9201   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9202 
9203   // if both are pointers check if operation is valid wrt address spaces
9204   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9205     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9206     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9207     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9208       S.Diag(Loc,
9209              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9210           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9211           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9212       return false;
9213     }
9214   }
9215 
9216   // Check for arithmetic on pointers to incomplete types.
9217   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9218   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9219   if (isLHSVoidPtr || isRHSVoidPtr) {
9220     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9221     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9222     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9223 
9224     return !S.getLangOpts().CPlusPlus;
9225   }
9226 
9227   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9228   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9229   if (isLHSFuncPtr || isRHSFuncPtr) {
9230     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9231     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9232                                                                 RHSExpr);
9233     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9234 
9235     return !S.getLangOpts().CPlusPlus;
9236   }
9237 
9238   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9239     return false;
9240   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9241     return false;
9242 
9243   return true;
9244 }
9245 
9246 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9247 /// literal.
9248 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9249                                   Expr *LHSExpr, Expr *RHSExpr) {
9250   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9251   Expr* IndexExpr = RHSExpr;
9252   if (!StrExpr) {
9253     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9254     IndexExpr = LHSExpr;
9255   }
9256 
9257   bool IsStringPlusInt = StrExpr &&
9258       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9259   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9260     return;
9261 
9262   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9263   Self.Diag(OpLoc, diag::warn_string_plus_int)
9264       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9265 
9266   // Only print a fixit for "str" + int, not for int + "str".
9267   if (IndexExpr == RHSExpr) {
9268     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9269     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9270         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9271         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9272         << FixItHint::CreateInsertion(EndLoc, "]");
9273   } else
9274     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9275 }
9276 
9277 /// Emit a warning when adding a char literal to a string.
9278 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9279                                    Expr *LHSExpr, Expr *RHSExpr) {
9280   const Expr *StringRefExpr = LHSExpr;
9281   const CharacterLiteral *CharExpr =
9282       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9283 
9284   if (!CharExpr) {
9285     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9286     StringRefExpr = RHSExpr;
9287   }
9288 
9289   if (!CharExpr || !StringRefExpr)
9290     return;
9291 
9292   const QualType StringType = StringRefExpr->getType();
9293 
9294   // Return if not a PointerType.
9295   if (!StringType->isAnyPointerType())
9296     return;
9297 
9298   // Return if not a CharacterType.
9299   if (!StringType->getPointeeType()->isAnyCharacterType())
9300     return;
9301 
9302   ASTContext &Ctx = Self.getASTContext();
9303   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9304 
9305   const QualType CharType = CharExpr->getType();
9306   if (!CharType->isAnyCharacterType() &&
9307       CharType->isIntegerType() &&
9308       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9309     Self.Diag(OpLoc, diag::warn_string_plus_char)
9310         << DiagRange << Ctx.CharTy;
9311   } else {
9312     Self.Diag(OpLoc, diag::warn_string_plus_char)
9313         << DiagRange << CharExpr->getType();
9314   }
9315 
9316   // Only print a fixit for str + char, not for char + str.
9317   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9318     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9319     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9320         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9321         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9322         << FixItHint::CreateInsertion(EndLoc, "]");
9323   } else {
9324     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9325   }
9326 }
9327 
9328 /// Emit error when two pointers are incompatible.
9329 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9330                                            Expr *LHSExpr, Expr *RHSExpr) {
9331   assert(LHSExpr->getType()->isAnyPointerType());
9332   assert(RHSExpr->getType()->isAnyPointerType());
9333   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9334     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9335     << RHSExpr->getSourceRange();
9336 }
9337 
9338 // C99 6.5.6
9339 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9340                                      SourceLocation Loc, BinaryOperatorKind Opc,
9341                                      QualType* CompLHSTy) {
9342   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9343 
9344   if (LHS.get()->getType()->isVectorType() ||
9345       RHS.get()->getType()->isVectorType()) {
9346     QualType compType = CheckVectorOperands(
9347         LHS, RHS, Loc, CompLHSTy,
9348         /*AllowBothBool*/getLangOpts().AltiVec,
9349         /*AllowBoolConversions*/getLangOpts().ZVector);
9350     if (CompLHSTy) *CompLHSTy = compType;
9351     return compType;
9352   }
9353 
9354   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9355   if (LHS.isInvalid() || RHS.isInvalid())
9356     return QualType();
9357 
9358   // Diagnose "string literal" '+' int and string '+' "char literal".
9359   if (Opc == BO_Add) {
9360     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9361     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9362   }
9363 
9364   // handle the common case first (both operands are arithmetic).
9365   if (!compType.isNull() && compType->isArithmeticType()) {
9366     if (CompLHSTy) *CompLHSTy = compType;
9367     return compType;
9368   }
9369 
9370   // Type-checking.  Ultimately the pointer's going to be in PExp;
9371   // note that we bias towards the LHS being the pointer.
9372   Expr *PExp = LHS.get(), *IExp = RHS.get();
9373 
9374   bool isObjCPointer;
9375   if (PExp->getType()->isPointerType()) {
9376     isObjCPointer = false;
9377   } else if (PExp->getType()->isObjCObjectPointerType()) {
9378     isObjCPointer = true;
9379   } else {
9380     std::swap(PExp, IExp);
9381     if (PExp->getType()->isPointerType()) {
9382       isObjCPointer = false;
9383     } else if (PExp->getType()->isObjCObjectPointerType()) {
9384       isObjCPointer = true;
9385     } else {
9386       return InvalidOperands(Loc, LHS, RHS);
9387     }
9388   }
9389   assert(PExp->getType()->isAnyPointerType());
9390 
9391   if (!IExp->getType()->isIntegerType())
9392     return InvalidOperands(Loc, LHS, RHS);
9393 
9394   // Adding to a null pointer results in undefined behavior.
9395   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9396           Context, Expr::NPC_ValueDependentIsNotNull)) {
9397     // In C++ adding zero to a null pointer is defined.
9398     Expr::EvalResult KnownVal;
9399     if (!getLangOpts().CPlusPlus ||
9400         (!IExp->isValueDependent() &&
9401          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9402           KnownVal.Val.getInt() != 0))) {
9403       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9404       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9405           Context, BO_Add, PExp, IExp);
9406       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9407     }
9408   }
9409 
9410   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9411     return QualType();
9412 
9413   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9414     return QualType();
9415 
9416   // Check array bounds for pointer arithemtic
9417   CheckArrayAccess(PExp, IExp);
9418 
9419   if (CompLHSTy) {
9420     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9421     if (LHSTy.isNull()) {
9422       LHSTy = LHS.get()->getType();
9423       if (LHSTy->isPromotableIntegerType())
9424         LHSTy = Context.getPromotedIntegerType(LHSTy);
9425     }
9426     *CompLHSTy = LHSTy;
9427   }
9428 
9429   return PExp->getType();
9430 }
9431 
9432 // C99 6.5.6
9433 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9434                                         SourceLocation Loc,
9435                                         QualType* CompLHSTy) {
9436   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9437 
9438   if (LHS.get()->getType()->isVectorType() ||
9439       RHS.get()->getType()->isVectorType()) {
9440     QualType compType = CheckVectorOperands(
9441         LHS, RHS, Loc, CompLHSTy,
9442         /*AllowBothBool*/getLangOpts().AltiVec,
9443         /*AllowBoolConversions*/getLangOpts().ZVector);
9444     if (CompLHSTy) *CompLHSTy = compType;
9445     return compType;
9446   }
9447 
9448   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9449   if (LHS.isInvalid() || RHS.isInvalid())
9450     return QualType();
9451 
9452   // Enforce type constraints: C99 6.5.6p3.
9453 
9454   // Handle the common case first (both operands are arithmetic).
9455   if (!compType.isNull() && compType->isArithmeticType()) {
9456     if (CompLHSTy) *CompLHSTy = compType;
9457     return compType;
9458   }
9459 
9460   // Either ptr - int   or   ptr - ptr.
9461   if (LHS.get()->getType()->isAnyPointerType()) {
9462     QualType lpointee = LHS.get()->getType()->getPointeeType();
9463 
9464     // Diagnose bad cases where we step over interface counts.
9465     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9466         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9467       return QualType();
9468 
9469     // The result type of a pointer-int computation is the pointer type.
9470     if (RHS.get()->getType()->isIntegerType()) {
9471       // Subtracting from a null pointer should produce a warning.
9472       // The last argument to the diagnose call says this doesn't match the
9473       // GNU int-to-pointer idiom.
9474       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9475                                            Expr::NPC_ValueDependentIsNotNull)) {
9476         // In C++ adding zero to a null pointer is defined.
9477         Expr::EvalResult KnownVal;
9478         if (!getLangOpts().CPlusPlus ||
9479             (!RHS.get()->isValueDependent() &&
9480              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9481               KnownVal.Val.getInt() != 0))) {
9482           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9483         }
9484       }
9485 
9486       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9487         return QualType();
9488 
9489       // Check array bounds for pointer arithemtic
9490       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9491                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9492 
9493       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9494       return LHS.get()->getType();
9495     }
9496 
9497     // Handle pointer-pointer subtractions.
9498     if (const PointerType *RHSPTy
9499           = RHS.get()->getType()->getAs<PointerType>()) {
9500       QualType rpointee = RHSPTy->getPointeeType();
9501 
9502       if (getLangOpts().CPlusPlus) {
9503         // Pointee types must be the same: C++ [expr.add]
9504         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9505           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9506         }
9507       } else {
9508         // Pointee types must be compatible C99 6.5.6p3
9509         if (!Context.typesAreCompatible(
9510                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9511                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9512           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9513           return QualType();
9514         }
9515       }
9516 
9517       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9518                                                LHS.get(), RHS.get()))
9519         return QualType();
9520 
9521       // FIXME: Add warnings for nullptr - ptr.
9522 
9523       // The pointee type may have zero size.  As an extension, a structure or
9524       // union may have zero size or an array may have zero length.  In this
9525       // case subtraction does not make sense.
9526       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9527         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9528         if (ElementSize.isZero()) {
9529           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9530             << rpointee.getUnqualifiedType()
9531             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9532         }
9533       }
9534 
9535       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9536       return Context.getPointerDiffType();
9537     }
9538   }
9539 
9540   return InvalidOperands(Loc, LHS, RHS);
9541 }
9542 
9543 static bool isScopedEnumerationType(QualType T) {
9544   if (const EnumType *ET = T->getAs<EnumType>())
9545     return ET->getDecl()->isScoped();
9546   return false;
9547 }
9548 
9549 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9550                                    SourceLocation Loc, BinaryOperatorKind Opc,
9551                                    QualType LHSType) {
9552   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9553   // so skip remaining warnings as we don't want to modify values within Sema.
9554   if (S.getLangOpts().OpenCL)
9555     return;
9556 
9557   // Check right/shifter operand
9558   Expr::EvalResult RHSResult;
9559   if (RHS.get()->isValueDependent() ||
9560       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9561     return;
9562   llvm::APSInt Right = RHSResult.Val.getInt();
9563 
9564   if (Right.isNegative()) {
9565     S.DiagRuntimeBehavior(Loc, RHS.get(),
9566                           S.PDiag(diag::warn_shift_negative)
9567                             << RHS.get()->getSourceRange());
9568     return;
9569   }
9570   llvm::APInt LeftBits(Right.getBitWidth(),
9571                        S.Context.getTypeSize(LHS.get()->getType()));
9572   if (Right.uge(LeftBits)) {
9573     S.DiagRuntimeBehavior(Loc, RHS.get(),
9574                           S.PDiag(diag::warn_shift_gt_typewidth)
9575                             << RHS.get()->getSourceRange());
9576     return;
9577   }
9578   if (Opc != BO_Shl)
9579     return;
9580 
9581   // When left shifting an ICE which is signed, we can check for overflow which
9582   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9583   // integers have defined behavior modulo one more than the maximum value
9584   // representable in the result type, so never warn for those.
9585   Expr::EvalResult LHSResult;
9586   if (LHS.get()->isValueDependent() ||
9587       LHSType->hasUnsignedIntegerRepresentation() ||
9588       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9589     return;
9590   llvm::APSInt Left = LHSResult.Val.getInt();
9591 
9592   // If LHS does not have a signed type and non-negative value
9593   // then, the behavior is undefined. Warn about it.
9594   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9595     S.DiagRuntimeBehavior(Loc, LHS.get(),
9596                           S.PDiag(diag::warn_shift_lhs_negative)
9597                             << LHS.get()->getSourceRange());
9598     return;
9599   }
9600 
9601   llvm::APInt ResultBits =
9602       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9603   if (LeftBits.uge(ResultBits))
9604     return;
9605   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9606   Result = Result.shl(Right);
9607 
9608   // Print the bit representation of the signed integer as an unsigned
9609   // hexadecimal number.
9610   SmallString<40> HexResult;
9611   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9612 
9613   // If we are only missing a sign bit, this is less likely to result in actual
9614   // bugs -- if the result is cast back to an unsigned type, it will have the
9615   // expected value. Thus we place this behind a different warning that can be
9616   // turned off separately if needed.
9617   if (LeftBits == ResultBits - 1) {
9618     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9619         << HexResult << LHSType
9620         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9621     return;
9622   }
9623 
9624   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9625     << HexResult.str() << Result.getMinSignedBits() << LHSType
9626     << Left.getBitWidth() << LHS.get()->getSourceRange()
9627     << RHS.get()->getSourceRange();
9628 }
9629 
9630 /// Return the resulting type when a vector is shifted
9631 ///        by a scalar or vector shift amount.
9632 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9633                                  SourceLocation Loc, bool IsCompAssign) {
9634   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9635   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9636       !LHS.get()->getType()->isVectorType()) {
9637     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9638       << RHS.get()->getType() << LHS.get()->getType()
9639       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9640     return QualType();
9641   }
9642 
9643   if (!IsCompAssign) {
9644     LHS = S.UsualUnaryConversions(LHS.get());
9645     if (LHS.isInvalid()) return QualType();
9646   }
9647 
9648   RHS = S.UsualUnaryConversions(RHS.get());
9649   if (RHS.isInvalid()) return QualType();
9650 
9651   QualType LHSType = LHS.get()->getType();
9652   // Note that LHS might be a scalar because the routine calls not only in
9653   // OpenCL case.
9654   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9655   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9656 
9657   // Note that RHS might not be a vector.
9658   QualType RHSType = RHS.get()->getType();
9659   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9660   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9661 
9662   // The operands need to be integers.
9663   if (!LHSEleType->isIntegerType()) {
9664     S.Diag(Loc, diag::err_typecheck_expect_int)
9665       << LHS.get()->getType() << LHS.get()->getSourceRange();
9666     return QualType();
9667   }
9668 
9669   if (!RHSEleType->isIntegerType()) {
9670     S.Diag(Loc, diag::err_typecheck_expect_int)
9671       << RHS.get()->getType() << RHS.get()->getSourceRange();
9672     return QualType();
9673   }
9674 
9675   if (!LHSVecTy) {
9676     assert(RHSVecTy);
9677     if (IsCompAssign)
9678       return RHSType;
9679     if (LHSEleType != RHSEleType) {
9680       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9681       LHSEleType = RHSEleType;
9682     }
9683     QualType VecTy =
9684         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9685     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9686     LHSType = VecTy;
9687   } else if (RHSVecTy) {
9688     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9689     // are applied component-wise. So if RHS is a vector, then ensure
9690     // that the number of elements is the same as LHS...
9691     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9692       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9693         << LHS.get()->getType() << RHS.get()->getType()
9694         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9695       return QualType();
9696     }
9697     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9698       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9699       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9700       if (LHSBT != RHSBT &&
9701           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9702         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9703             << LHS.get()->getType() << RHS.get()->getType()
9704             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9705       }
9706     }
9707   } else {
9708     // ...else expand RHS to match the number of elements in LHS.
9709     QualType VecTy =
9710       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9711     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9712   }
9713 
9714   return LHSType;
9715 }
9716 
9717 // C99 6.5.7
9718 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9719                                   SourceLocation Loc, BinaryOperatorKind Opc,
9720                                   bool IsCompAssign) {
9721   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9722 
9723   // Vector shifts promote their scalar inputs to vector type.
9724   if (LHS.get()->getType()->isVectorType() ||
9725       RHS.get()->getType()->isVectorType()) {
9726     if (LangOpts.ZVector) {
9727       // The shift operators for the z vector extensions work basically
9728       // like general shifts, except that neither the LHS nor the RHS is
9729       // allowed to be a "vector bool".
9730       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9731         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9732           return InvalidOperands(Loc, LHS, RHS);
9733       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9734         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9735           return InvalidOperands(Loc, LHS, RHS);
9736     }
9737     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9738   }
9739 
9740   // Shifts don't perform usual arithmetic conversions, they just do integer
9741   // promotions on each operand. C99 6.5.7p3
9742 
9743   // For the LHS, do usual unary conversions, but then reset them away
9744   // if this is a compound assignment.
9745   ExprResult OldLHS = LHS;
9746   LHS = UsualUnaryConversions(LHS.get());
9747   if (LHS.isInvalid())
9748     return QualType();
9749   QualType LHSType = LHS.get()->getType();
9750   if (IsCompAssign) LHS = OldLHS;
9751 
9752   // The RHS is simpler.
9753   RHS = UsualUnaryConversions(RHS.get());
9754   if (RHS.isInvalid())
9755     return QualType();
9756   QualType RHSType = RHS.get()->getType();
9757 
9758   // C99 6.5.7p2: Each of the operands shall have integer type.
9759   if (!LHSType->hasIntegerRepresentation() ||
9760       !RHSType->hasIntegerRepresentation())
9761     return InvalidOperands(Loc, LHS, RHS);
9762 
9763   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9764   // hasIntegerRepresentation() above instead of this.
9765   if (isScopedEnumerationType(LHSType) ||
9766       isScopedEnumerationType(RHSType)) {
9767     return InvalidOperands(Loc, LHS, RHS);
9768   }
9769   // Sanity-check shift operands
9770   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9771 
9772   // "The type of the result is that of the promoted left operand."
9773   return LHSType;
9774 }
9775 
9776 /// If two different enums are compared, raise a warning.
9777 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9778                                 Expr *RHS) {
9779   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9780   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9781 
9782   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9783   if (!LHSEnumType)
9784     return;
9785   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9786   if (!RHSEnumType)
9787     return;
9788 
9789   // Ignore anonymous enums.
9790   if (!LHSEnumType->getDecl()->getIdentifier() &&
9791       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9792     return;
9793   if (!RHSEnumType->getDecl()->getIdentifier() &&
9794       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9795     return;
9796 
9797   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9798     return;
9799 
9800   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9801       << LHSStrippedType << RHSStrippedType
9802       << LHS->getSourceRange() << RHS->getSourceRange();
9803 }
9804 
9805 /// Diagnose bad pointer comparisons.
9806 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9807                                               ExprResult &LHS, ExprResult &RHS,
9808                                               bool IsError) {
9809   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9810                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9811     << LHS.get()->getType() << RHS.get()->getType()
9812     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9813 }
9814 
9815 /// Returns false if the pointers are converted to a composite type,
9816 /// true otherwise.
9817 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9818                                            ExprResult &LHS, ExprResult &RHS) {
9819   // C++ [expr.rel]p2:
9820   //   [...] Pointer conversions (4.10) and qualification
9821   //   conversions (4.4) are performed on pointer operands (or on
9822   //   a pointer operand and a null pointer constant) to bring
9823   //   them to their composite pointer type. [...]
9824   //
9825   // C++ [expr.eq]p1 uses the same notion for (in)equality
9826   // comparisons of pointers.
9827 
9828   QualType LHSType = LHS.get()->getType();
9829   QualType RHSType = RHS.get()->getType();
9830   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9831          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9832 
9833   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9834   if (T.isNull()) {
9835     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9836         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9837       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9838     else
9839       S.InvalidOperands(Loc, LHS, RHS);
9840     return true;
9841   }
9842 
9843   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9844   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9845   return false;
9846 }
9847 
9848 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9849                                                     ExprResult &LHS,
9850                                                     ExprResult &RHS,
9851                                                     bool IsError) {
9852   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9853                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9854     << LHS.get()->getType() << RHS.get()->getType()
9855     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9856 }
9857 
9858 static bool isObjCObjectLiteral(ExprResult &E) {
9859   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9860   case Stmt::ObjCArrayLiteralClass:
9861   case Stmt::ObjCDictionaryLiteralClass:
9862   case Stmt::ObjCStringLiteralClass:
9863   case Stmt::ObjCBoxedExprClass:
9864     return true;
9865   default:
9866     // Note that ObjCBoolLiteral is NOT an object literal!
9867     return false;
9868   }
9869 }
9870 
9871 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9872   const ObjCObjectPointerType *Type =
9873     LHS->getType()->getAs<ObjCObjectPointerType>();
9874 
9875   // If this is not actually an Objective-C object, bail out.
9876   if (!Type)
9877     return false;
9878 
9879   // Get the LHS object's interface type.
9880   QualType InterfaceType = Type->getPointeeType();
9881 
9882   // If the RHS isn't an Objective-C object, bail out.
9883   if (!RHS->getType()->isObjCObjectPointerType())
9884     return false;
9885 
9886   // Try to find the -isEqual: method.
9887   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9888   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9889                                                       InterfaceType,
9890                                                       /*instance=*/true);
9891   if (!Method) {
9892     if (Type->isObjCIdType()) {
9893       // For 'id', just check the global pool.
9894       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9895                                                   /*receiverId=*/true);
9896     } else {
9897       // Check protocols.
9898       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9899                                              /*instance=*/true);
9900     }
9901   }
9902 
9903   if (!Method)
9904     return false;
9905 
9906   QualType T = Method->parameters()[0]->getType();
9907   if (!T->isObjCObjectPointerType())
9908     return false;
9909 
9910   QualType R = Method->getReturnType();
9911   if (!R->isScalarType())
9912     return false;
9913 
9914   return true;
9915 }
9916 
9917 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9918   FromE = FromE->IgnoreParenImpCasts();
9919   switch (FromE->getStmtClass()) {
9920     default:
9921       break;
9922     case Stmt::ObjCStringLiteralClass:
9923       // "string literal"
9924       return LK_String;
9925     case Stmt::ObjCArrayLiteralClass:
9926       // "array literal"
9927       return LK_Array;
9928     case Stmt::ObjCDictionaryLiteralClass:
9929       // "dictionary literal"
9930       return LK_Dictionary;
9931     case Stmt::BlockExprClass:
9932       return LK_Block;
9933     case Stmt::ObjCBoxedExprClass: {
9934       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9935       switch (Inner->getStmtClass()) {
9936         case Stmt::IntegerLiteralClass:
9937         case Stmt::FloatingLiteralClass:
9938         case Stmt::CharacterLiteralClass:
9939         case Stmt::ObjCBoolLiteralExprClass:
9940         case Stmt::CXXBoolLiteralExprClass:
9941           // "numeric literal"
9942           return LK_Numeric;
9943         case Stmt::ImplicitCastExprClass: {
9944           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9945           // Boolean literals can be represented by implicit casts.
9946           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9947             return LK_Numeric;
9948           break;
9949         }
9950         default:
9951           break;
9952       }
9953       return LK_Boxed;
9954     }
9955   }
9956   return LK_None;
9957 }
9958 
9959 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9960                                           ExprResult &LHS, ExprResult &RHS,
9961                                           BinaryOperator::Opcode Opc){
9962   Expr *Literal;
9963   Expr *Other;
9964   if (isObjCObjectLiteral(LHS)) {
9965     Literal = LHS.get();
9966     Other = RHS.get();
9967   } else {
9968     Literal = RHS.get();
9969     Other = LHS.get();
9970   }
9971 
9972   // Don't warn on comparisons against nil.
9973   Other = Other->IgnoreParenCasts();
9974   if (Other->isNullPointerConstant(S.getASTContext(),
9975                                    Expr::NPC_ValueDependentIsNotNull))
9976     return;
9977 
9978   // This should be kept in sync with warn_objc_literal_comparison.
9979   // LK_String should always be after the other literals, since it has its own
9980   // warning flag.
9981   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9982   assert(LiteralKind != Sema::LK_Block);
9983   if (LiteralKind == Sema::LK_None) {
9984     llvm_unreachable("Unknown Objective-C object literal kind");
9985   }
9986 
9987   if (LiteralKind == Sema::LK_String)
9988     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9989       << Literal->getSourceRange();
9990   else
9991     S.Diag(Loc, diag::warn_objc_literal_comparison)
9992       << LiteralKind << Literal->getSourceRange();
9993 
9994   if (BinaryOperator::isEqualityOp(Opc) &&
9995       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9996     SourceLocation Start = LHS.get()->getBeginLoc();
9997     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
9998     CharSourceRange OpRange =
9999       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10000 
10001     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10002       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10003       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10004       << FixItHint::CreateInsertion(End, "]");
10005   }
10006 }
10007 
10008 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10009 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10010                                            ExprResult &RHS, SourceLocation Loc,
10011                                            BinaryOperatorKind Opc) {
10012   // Check that left hand side is !something.
10013   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10014   if (!UO || UO->getOpcode() != UO_LNot) return;
10015 
10016   // Only check if the right hand side is non-bool arithmetic type.
10017   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10018 
10019   // Make sure that the something in !something is not bool.
10020   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10021   if (SubExpr->isKnownToHaveBooleanValue()) return;
10022 
10023   // Emit warning.
10024   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10025   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10026       << Loc << IsBitwiseOp;
10027 
10028   // First note suggest !(x < y)
10029   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10030   SourceLocation FirstClose = RHS.get()->getEndLoc();
10031   FirstClose = S.getLocForEndOfToken(FirstClose);
10032   if (FirstClose.isInvalid())
10033     FirstOpen = SourceLocation();
10034   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10035       << IsBitwiseOp
10036       << FixItHint::CreateInsertion(FirstOpen, "(")
10037       << FixItHint::CreateInsertion(FirstClose, ")");
10038 
10039   // Second note suggests (!x) < y
10040   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10041   SourceLocation SecondClose = LHS.get()->getEndLoc();
10042   SecondClose = S.getLocForEndOfToken(SecondClose);
10043   if (SecondClose.isInvalid())
10044     SecondOpen = SourceLocation();
10045   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10046       << FixItHint::CreateInsertion(SecondOpen, "(")
10047       << FixItHint::CreateInsertion(SecondClose, ")");
10048 }
10049 
10050 // Get the decl for a simple expression: a reference to a variable,
10051 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10052 static ValueDecl *getCompareDecl(Expr *E) {
10053   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10054     return DR->getDecl();
10055   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10056     if (Ivar->isFreeIvar())
10057       return Ivar->getDecl();
10058   }
10059   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10060     if (Mem->isImplicitAccess())
10061       return Mem->getMemberDecl();
10062   }
10063   return nullptr;
10064 }
10065 
10066 /// Diagnose some forms of syntactically-obvious tautological comparison.
10067 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10068                                            Expr *LHS, Expr *RHS,
10069                                            BinaryOperatorKind Opc) {
10070   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10071   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10072 
10073   QualType LHSType = LHS->getType();
10074   QualType RHSType = RHS->getType();
10075   if (LHSType->hasFloatingRepresentation() ||
10076       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10077       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10078       S.inTemplateInstantiation())
10079     return;
10080 
10081   // Comparisons between two array types are ill-formed for operator<=>, so
10082   // we shouldn't emit any additional warnings about it.
10083   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10084     return;
10085 
10086   // For non-floating point types, check for self-comparisons of the form
10087   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10088   // often indicate logic errors in the program.
10089   //
10090   // NOTE: Don't warn about comparison expressions resulting from macro
10091   // expansion. Also don't warn about comparisons which are only self
10092   // comparisons within a template instantiation. The warnings should catch
10093   // obvious cases in the definition of the template anyways. The idea is to
10094   // warn when the typed comparison operator will always evaluate to the same
10095   // result.
10096   ValueDecl *DL = getCompareDecl(LHSStripped);
10097   ValueDecl *DR = getCompareDecl(RHSStripped);
10098   if (DL && DR && declaresSameEntity(DL, DR)) {
10099     StringRef Result;
10100     switch (Opc) {
10101     case BO_EQ: case BO_LE: case BO_GE:
10102       Result = "true";
10103       break;
10104     case BO_NE: case BO_LT: case BO_GT:
10105       Result = "false";
10106       break;
10107     case BO_Cmp:
10108       Result = "'std::strong_ordering::equal'";
10109       break;
10110     default:
10111       break;
10112     }
10113     S.DiagRuntimeBehavior(Loc, nullptr,
10114                           S.PDiag(diag::warn_comparison_always)
10115                               << 0 /*self-comparison*/ << !Result.empty()
10116                               << Result);
10117   } else if (DL && DR &&
10118              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10119              !DL->isWeak() && !DR->isWeak()) {
10120     // What is it always going to evaluate to?
10121     StringRef Result;
10122     switch(Opc) {
10123     case BO_EQ: // e.g. array1 == array2
10124       Result = "false";
10125       break;
10126     case BO_NE: // e.g. array1 != array2
10127       Result = "true";
10128       break;
10129     default: // e.g. array1 <= array2
10130       // The best we can say is 'a constant'
10131       break;
10132     }
10133     S.DiagRuntimeBehavior(Loc, nullptr,
10134                           S.PDiag(diag::warn_comparison_always)
10135                               << 1 /*array comparison*/
10136                               << !Result.empty() << Result);
10137   }
10138 
10139   if (isa<CastExpr>(LHSStripped))
10140     LHSStripped = LHSStripped->IgnoreParenCasts();
10141   if (isa<CastExpr>(RHSStripped))
10142     RHSStripped = RHSStripped->IgnoreParenCasts();
10143 
10144   // Warn about comparisons against a string constant (unless the other
10145   // operand is null); the user probably wants strcmp.
10146   Expr *LiteralString = nullptr;
10147   Expr *LiteralStringStripped = nullptr;
10148   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10149       !RHSStripped->isNullPointerConstant(S.Context,
10150                                           Expr::NPC_ValueDependentIsNull)) {
10151     LiteralString = LHS;
10152     LiteralStringStripped = LHSStripped;
10153   } else if ((isa<StringLiteral>(RHSStripped) ||
10154               isa<ObjCEncodeExpr>(RHSStripped)) &&
10155              !LHSStripped->isNullPointerConstant(S.Context,
10156                                           Expr::NPC_ValueDependentIsNull)) {
10157     LiteralString = RHS;
10158     LiteralStringStripped = RHSStripped;
10159   }
10160 
10161   if (LiteralString) {
10162     S.DiagRuntimeBehavior(Loc, nullptr,
10163                           S.PDiag(diag::warn_stringcompare)
10164                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10165                               << LiteralString->getSourceRange());
10166   }
10167 }
10168 
10169 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10170   switch (CK) {
10171   default: {
10172 #ifndef NDEBUG
10173     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10174                  << "\n";
10175 #endif
10176     llvm_unreachable("unhandled cast kind");
10177   }
10178   case CK_UserDefinedConversion:
10179     return ICK_Identity;
10180   case CK_LValueToRValue:
10181     return ICK_Lvalue_To_Rvalue;
10182   case CK_ArrayToPointerDecay:
10183     return ICK_Array_To_Pointer;
10184   case CK_FunctionToPointerDecay:
10185     return ICK_Function_To_Pointer;
10186   case CK_IntegralCast:
10187     return ICK_Integral_Conversion;
10188   case CK_FloatingCast:
10189     return ICK_Floating_Conversion;
10190   case CK_IntegralToFloating:
10191   case CK_FloatingToIntegral:
10192     return ICK_Floating_Integral;
10193   case CK_IntegralComplexCast:
10194   case CK_FloatingComplexCast:
10195   case CK_FloatingComplexToIntegralComplex:
10196   case CK_IntegralComplexToFloatingComplex:
10197     return ICK_Complex_Conversion;
10198   case CK_FloatingComplexToReal:
10199   case CK_FloatingRealToComplex:
10200   case CK_IntegralComplexToReal:
10201   case CK_IntegralRealToComplex:
10202     return ICK_Complex_Real;
10203   }
10204 }
10205 
10206 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10207                                              QualType FromType,
10208                                              SourceLocation Loc) {
10209   // Check for a narrowing implicit conversion.
10210   StandardConversionSequence SCS;
10211   SCS.setAsIdentityConversion();
10212   SCS.setToType(0, FromType);
10213   SCS.setToType(1, ToType);
10214   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10215     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10216 
10217   APValue PreNarrowingValue;
10218   QualType PreNarrowingType;
10219   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10220                                PreNarrowingType,
10221                                /*IgnoreFloatToIntegralConversion*/ true)) {
10222   case NK_Dependent_Narrowing:
10223     // Implicit conversion to a narrower type, but the expression is
10224     // value-dependent so we can't tell whether it's actually narrowing.
10225   case NK_Not_Narrowing:
10226     return false;
10227 
10228   case NK_Constant_Narrowing:
10229     // Implicit conversion to a narrower type, and the value is not a constant
10230     // expression.
10231     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10232         << /*Constant*/ 1
10233         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10234     return true;
10235 
10236   case NK_Variable_Narrowing:
10237     // Implicit conversion to a narrower type, and the value is not a constant
10238     // expression.
10239   case NK_Type_Narrowing:
10240     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10241         << /*Constant*/ 0 << FromType << ToType;
10242     // TODO: It's not a constant expression, but what if the user intended it
10243     // to be? Can we produce notes to help them figure out why it isn't?
10244     return true;
10245   }
10246   llvm_unreachable("unhandled case in switch");
10247 }
10248 
10249 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10250                                                          ExprResult &LHS,
10251                                                          ExprResult &RHS,
10252                                                          SourceLocation Loc) {
10253   using CCT = ComparisonCategoryType;
10254 
10255   QualType LHSType = LHS.get()->getType();
10256   QualType RHSType = RHS.get()->getType();
10257   // Dig out the original argument type and expression before implicit casts
10258   // were applied. These are the types/expressions we need to check the
10259   // [expr.spaceship] requirements against.
10260   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10261   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10262   QualType LHSStrippedType = LHSStripped.get()->getType();
10263   QualType RHSStrippedType = RHSStripped.get()->getType();
10264 
10265   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10266   // other is not, the program is ill-formed.
10267   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10268     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10269     return QualType();
10270   }
10271 
10272   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10273                     RHSStrippedType->isEnumeralType();
10274   if (NumEnumArgs == 1) {
10275     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10276     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10277     if (OtherTy->hasFloatingRepresentation()) {
10278       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10279       return QualType();
10280     }
10281   }
10282   if (NumEnumArgs == 2) {
10283     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10284     // type E, the operator yields the result of converting the operands
10285     // to the underlying type of E and applying <=> to the converted operands.
10286     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10287       S.InvalidOperands(Loc, LHS, RHS);
10288       return QualType();
10289     }
10290     QualType IntType =
10291         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10292     assert(IntType->isArithmeticType());
10293 
10294     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10295     // promote the boolean type, and all other promotable integer types, to
10296     // avoid this.
10297     if (IntType->isPromotableIntegerType())
10298       IntType = S.Context.getPromotedIntegerType(IntType);
10299 
10300     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10301     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10302     LHSType = RHSType = IntType;
10303   }
10304 
10305   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10306   // usual arithmetic conversions are applied to the operands.
10307   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10308   if (LHS.isInvalid() || RHS.isInvalid())
10309     return QualType();
10310   if (Type.isNull())
10311     return S.InvalidOperands(Loc, LHS, RHS);
10312   assert(Type->isArithmeticType() || Type->isEnumeralType());
10313 
10314   bool HasNarrowing = checkThreeWayNarrowingConversion(
10315       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10316   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10317                                                    RHS.get()->getBeginLoc());
10318   if (HasNarrowing)
10319     return QualType();
10320 
10321   assert(!Type.isNull() && "composite type for <=> has not been set");
10322 
10323   auto TypeKind = [&]() {
10324     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10325       if (CT->getElementType()->hasFloatingRepresentation())
10326         return CCT::WeakEquality;
10327       return CCT::StrongEquality;
10328     }
10329     if (Type->isIntegralOrEnumerationType())
10330       return CCT::StrongOrdering;
10331     if (Type->hasFloatingRepresentation())
10332       return CCT::PartialOrdering;
10333     llvm_unreachable("other types are unimplemented");
10334   }();
10335 
10336   return S.CheckComparisonCategoryType(TypeKind, Loc);
10337 }
10338 
10339 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10340                                                  ExprResult &RHS,
10341                                                  SourceLocation Loc,
10342                                                  BinaryOperatorKind Opc) {
10343   if (Opc == BO_Cmp)
10344     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10345 
10346   // C99 6.5.8p3 / C99 6.5.9p4
10347   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10348   if (LHS.isInvalid() || RHS.isInvalid())
10349     return QualType();
10350   if (Type.isNull())
10351     return S.InvalidOperands(Loc, LHS, RHS);
10352   assert(Type->isArithmeticType() || Type->isEnumeralType());
10353 
10354   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10355 
10356   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10357     return S.InvalidOperands(Loc, LHS, RHS);
10358 
10359   // Check for comparisons of floating point operands using != and ==.
10360   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10361     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10362 
10363   // The result of comparisons is 'bool' in C++, 'int' in C.
10364   return S.Context.getLogicalOperationType();
10365 }
10366 
10367 // C99 6.5.8, C++ [expr.rel]
10368 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10369                                     SourceLocation Loc,
10370                                     BinaryOperatorKind Opc) {
10371   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10372   bool IsThreeWay = Opc == BO_Cmp;
10373   auto IsAnyPointerType = [](ExprResult E) {
10374     QualType Ty = E.get()->getType();
10375     return Ty->isPointerType() || Ty->isMemberPointerType();
10376   };
10377 
10378   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10379   // type, array-to-pointer, ..., conversions are performed on both operands to
10380   // bring them to their composite type.
10381   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10382   // any type-related checks.
10383   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10384     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10385     if (LHS.isInvalid())
10386       return QualType();
10387     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10388     if (RHS.isInvalid())
10389       return QualType();
10390   } else {
10391     LHS = DefaultLvalueConversion(LHS.get());
10392     if (LHS.isInvalid())
10393       return QualType();
10394     RHS = DefaultLvalueConversion(RHS.get());
10395     if (RHS.isInvalid())
10396       return QualType();
10397   }
10398 
10399   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10400 
10401   // Handle vector comparisons separately.
10402   if (LHS.get()->getType()->isVectorType() ||
10403       RHS.get()->getType()->isVectorType())
10404     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10405 
10406   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10407   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10408 
10409   QualType LHSType = LHS.get()->getType();
10410   QualType RHSType = RHS.get()->getType();
10411   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10412       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10413     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10414 
10415   const Expr::NullPointerConstantKind LHSNullKind =
10416       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10417   const Expr::NullPointerConstantKind RHSNullKind =
10418       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10419   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10420   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10421 
10422   auto computeResultTy = [&]() {
10423     if (Opc != BO_Cmp)
10424       return Context.getLogicalOperationType();
10425     assert(getLangOpts().CPlusPlus);
10426     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10427 
10428     QualType CompositeTy = LHS.get()->getType();
10429     assert(!CompositeTy->isReferenceType());
10430 
10431     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10432       return CheckComparisonCategoryType(Kind, Loc);
10433     };
10434 
10435     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10436     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10437     // result is of type std::strong_equality
10438     if (CompositeTy->isFunctionPointerType() ||
10439         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10440       // FIXME: consider making the function pointer case produce
10441       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10442       // and direction polls
10443       return buildResultTy(ComparisonCategoryType::StrongEquality);
10444 
10445     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10446     // pointer type, p <=> q is of type std::strong_ordering.
10447     if (CompositeTy->isPointerType()) {
10448       // P0946R0: Comparisons between a null pointer constant and an object
10449       // pointer result in std::strong_equality
10450       if (LHSIsNull != RHSIsNull)
10451         return buildResultTy(ComparisonCategoryType::StrongEquality);
10452       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10453     }
10454     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10455     // TODO: Extend support for operator<=> to ObjC types.
10456     return InvalidOperands(Loc, LHS, RHS);
10457   };
10458 
10459 
10460   if (!IsRelational && LHSIsNull != RHSIsNull) {
10461     bool IsEquality = Opc == BO_EQ;
10462     if (RHSIsNull)
10463       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10464                                    RHS.get()->getSourceRange());
10465     else
10466       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10467                                    LHS.get()->getSourceRange());
10468   }
10469 
10470   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10471       (RHSType->isIntegerType() && !RHSIsNull)) {
10472     // Skip normal pointer conversion checks in this case; we have better
10473     // diagnostics for this below.
10474   } else if (getLangOpts().CPlusPlus) {
10475     // Equality comparison of a function pointer to a void pointer is invalid,
10476     // but we allow it as an extension.
10477     // FIXME: If we really want to allow this, should it be part of composite
10478     // pointer type computation so it works in conditionals too?
10479     if (!IsRelational &&
10480         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10481          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10482       // This is a gcc extension compatibility comparison.
10483       // In a SFINAE context, we treat this as a hard error to maintain
10484       // conformance with the C++ standard.
10485       diagnoseFunctionPointerToVoidComparison(
10486           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10487 
10488       if (isSFINAEContext())
10489         return QualType();
10490 
10491       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10492       return computeResultTy();
10493     }
10494 
10495     // C++ [expr.eq]p2:
10496     //   If at least one operand is a pointer [...] bring them to their
10497     //   composite pointer type.
10498     // C++ [expr.spaceship]p6
10499     //  If at least one of the operands is of pointer type, [...] bring them
10500     //  to their composite pointer type.
10501     // C++ [expr.rel]p2:
10502     //   If both operands are pointers, [...] bring them to their composite
10503     //   pointer type.
10504     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10505             (IsRelational ? 2 : 1) &&
10506         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10507                                          RHSType->isObjCObjectPointerType()))) {
10508       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10509         return QualType();
10510       return computeResultTy();
10511     }
10512   } else if (LHSType->isPointerType() &&
10513              RHSType->isPointerType()) { // C99 6.5.8p2
10514     // All of the following pointer-related warnings are GCC extensions, except
10515     // when handling null pointer constants.
10516     QualType LCanPointeeTy =
10517       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10518     QualType RCanPointeeTy =
10519       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10520 
10521     // C99 6.5.9p2 and C99 6.5.8p2
10522     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10523                                    RCanPointeeTy.getUnqualifiedType())) {
10524       // Valid unless a relational comparison of function pointers
10525       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10526         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10527           << LHSType << RHSType << LHS.get()->getSourceRange()
10528           << RHS.get()->getSourceRange();
10529       }
10530     } else if (!IsRelational &&
10531                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10532       // Valid unless comparison between non-null pointer and function pointer
10533       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10534           && !LHSIsNull && !RHSIsNull)
10535         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10536                                                 /*isError*/false);
10537     } else {
10538       // Invalid
10539       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10540     }
10541     if (LCanPointeeTy != RCanPointeeTy) {
10542       // Treat NULL constant as a special case in OpenCL.
10543       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10544         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10545         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10546           Diag(Loc,
10547                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10548               << LHSType << RHSType << 0 /* comparison */
10549               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10550         }
10551       }
10552       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10553       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10554       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10555                                                : CK_BitCast;
10556       if (LHSIsNull && !RHSIsNull)
10557         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10558       else
10559         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10560     }
10561     return computeResultTy();
10562   }
10563 
10564   if (getLangOpts().CPlusPlus) {
10565     // C++ [expr.eq]p4:
10566     //   Two operands of type std::nullptr_t or one operand of type
10567     //   std::nullptr_t and the other a null pointer constant compare equal.
10568     if (!IsRelational && LHSIsNull && RHSIsNull) {
10569       if (LHSType->isNullPtrType()) {
10570         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10571         return computeResultTy();
10572       }
10573       if (RHSType->isNullPtrType()) {
10574         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10575         return computeResultTy();
10576       }
10577     }
10578 
10579     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10580     // These aren't covered by the composite pointer type rules.
10581     if (!IsRelational && RHSType->isNullPtrType() &&
10582         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10583       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10584       return computeResultTy();
10585     }
10586     if (!IsRelational && LHSType->isNullPtrType() &&
10587         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10588       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10589       return computeResultTy();
10590     }
10591 
10592     if (IsRelational &&
10593         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10594          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10595       // HACK: Relational comparison of nullptr_t against a pointer type is
10596       // invalid per DR583, but we allow it within std::less<> and friends,
10597       // since otherwise common uses of it break.
10598       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10599       // friends to have std::nullptr_t overload candidates.
10600       DeclContext *DC = CurContext;
10601       if (isa<FunctionDecl>(DC))
10602         DC = DC->getParent();
10603       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10604         if (CTSD->isInStdNamespace() &&
10605             llvm::StringSwitch<bool>(CTSD->getName())
10606                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10607                 .Default(false)) {
10608           if (RHSType->isNullPtrType())
10609             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10610           else
10611             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10612           return computeResultTy();
10613         }
10614       }
10615     }
10616 
10617     // C++ [expr.eq]p2:
10618     //   If at least one operand is a pointer to member, [...] bring them to
10619     //   their composite pointer type.
10620     if (!IsRelational &&
10621         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10622       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10623         return QualType();
10624       else
10625         return computeResultTy();
10626     }
10627   }
10628 
10629   // Handle block pointer types.
10630   if (!IsRelational && LHSType->isBlockPointerType() &&
10631       RHSType->isBlockPointerType()) {
10632     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10633     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10634 
10635     if (!LHSIsNull && !RHSIsNull &&
10636         !Context.typesAreCompatible(lpointee, rpointee)) {
10637       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10638         << LHSType << RHSType << LHS.get()->getSourceRange()
10639         << RHS.get()->getSourceRange();
10640     }
10641     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10642     return computeResultTy();
10643   }
10644 
10645   // Allow block pointers to be compared with null pointer constants.
10646   if (!IsRelational
10647       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10648           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10649     if (!LHSIsNull && !RHSIsNull) {
10650       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10651              ->getPointeeType()->isVoidType())
10652             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10653                 ->getPointeeType()->isVoidType())))
10654         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10655           << LHSType << RHSType << LHS.get()->getSourceRange()
10656           << RHS.get()->getSourceRange();
10657     }
10658     if (LHSIsNull && !RHSIsNull)
10659       LHS = ImpCastExprToType(LHS.get(), RHSType,
10660                               RHSType->isPointerType() ? CK_BitCast
10661                                 : CK_AnyPointerToBlockPointerCast);
10662     else
10663       RHS = ImpCastExprToType(RHS.get(), LHSType,
10664                               LHSType->isPointerType() ? CK_BitCast
10665                                 : CK_AnyPointerToBlockPointerCast);
10666     return computeResultTy();
10667   }
10668 
10669   if (LHSType->isObjCObjectPointerType() ||
10670       RHSType->isObjCObjectPointerType()) {
10671     const PointerType *LPT = LHSType->getAs<PointerType>();
10672     const PointerType *RPT = RHSType->getAs<PointerType>();
10673     if (LPT || RPT) {
10674       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10675       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10676 
10677       if (!LPtrToVoid && !RPtrToVoid &&
10678           !Context.typesAreCompatible(LHSType, RHSType)) {
10679         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10680                                           /*isError*/false);
10681       }
10682       if (LHSIsNull && !RHSIsNull) {
10683         Expr *E = LHS.get();
10684         if (getLangOpts().ObjCAutoRefCount)
10685           CheckObjCConversion(SourceRange(), RHSType, E,
10686                               CCK_ImplicitConversion);
10687         LHS = ImpCastExprToType(E, RHSType,
10688                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10689       }
10690       else {
10691         Expr *E = RHS.get();
10692         if (getLangOpts().ObjCAutoRefCount)
10693           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10694                               /*Diagnose=*/true,
10695                               /*DiagnoseCFAudited=*/false, Opc);
10696         RHS = ImpCastExprToType(E, LHSType,
10697                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10698       }
10699       return computeResultTy();
10700     }
10701     if (LHSType->isObjCObjectPointerType() &&
10702         RHSType->isObjCObjectPointerType()) {
10703       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10704         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10705                                           /*isError*/false);
10706       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10707         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10708 
10709       if (LHSIsNull && !RHSIsNull)
10710         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10711       else
10712         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10713       return computeResultTy();
10714     }
10715 
10716     if (!IsRelational && LHSType->isBlockPointerType() &&
10717         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10718       LHS = ImpCastExprToType(LHS.get(), RHSType,
10719                               CK_BlockPointerToObjCPointerCast);
10720       return computeResultTy();
10721     } else if (!IsRelational &&
10722                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10723                RHSType->isBlockPointerType()) {
10724       RHS = ImpCastExprToType(RHS.get(), LHSType,
10725                               CK_BlockPointerToObjCPointerCast);
10726       return computeResultTy();
10727     }
10728   }
10729   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10730       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10731     unsigned DiagID = 0;
10732     bool isError = false;
10733     if (LangOpts.DebuggerSupport) {
10734       // Under a debugger, allow the comparison of pointers to integers,
10735       // since users tend to want to compare addresses.
10736     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10737                (RHSIsNull && RHSType->isIntegerType())) {
10738       if (IsRelational) {
10739         isError = getLangOpts().CPlusPlus;
10740         DiagID =
10741           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10742                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10743       }
10744     } else if (getLangOpts().CPlusPlus) {
10745       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10746       isError = true;
10747     } else if (IsRelational)
10748       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10749     else
10750       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10751 
10752     if (DiagID) {
10753       Diag(Loc, DiagID)
10754         << LHSType << RHSType << LHS.get()->getSourceRange()
10755         << RHS.get()->getSourceRange();
10756       if (isError)
10757         return QualType();
10758     }
10759 
10760     if (LHSType->isIntegerType())
10761       LHS = ImpCastExprToType(LHS.get(), RHSType,
10762                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10763     else
10764       RHS = ImpCastExprToType(RHS.get(), LHSType,
10765                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10766     return computeResultTy();
10767   }
10768 
10769   // Handle block pointers.
10770   if (!IsRelational && RHSIsNull
10771       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10772     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10773     return computeResultTy();
10774   }
10775   if (!IsRelational && LHSIsNull
10776       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10777     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10778     return computeResultTy();
10779   }
10780 
10781   if (getLangOpts().OpenCLVersion >= 200) {
10782     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10783       return computeResultTy();
10784     }
10785 
10786     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10787       return computeResultTy();
10788     }
10789 
10790     if (LHSIsNull && RHSType->isQueueT()) {
10791       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10792       return computeResultTy();
10793     }
10794 
10795     if (LHSType->isQueueT() && RHSIsNull) {
10796       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10797       return computeResultTy();
10798     }
10799   }
10800 
10801   return InvalidOperands(Loc, LHS, RHS);
10802 }
10803 
10804 // Return a signed ext_vector_type that is of identical size and number of
10805 // elements. For floating point vectors, return an integer type of identical
10806 // size and number of elements. In the non ext_vector_type case, search from
10807 // the largest type to the smallest type to avoid cases where long long == long,
10808 // where long gets picked over long long.
10809 QualType Sema::GetSignedVectorType(QualType V) {
10810   const VectorType *VTy = V->getAs<VectorType>();
10811   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10812 
10813   if (isa<ExtVectorType>(VTy)) {
10814     if (TypeSize == Context.getTypeSize(Context.CharTy))
10815       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10816     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10817       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10818     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10819       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10820     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10821       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10822     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10823            "Unhandled vector element size in vector compare");
10824     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10825   }
10826 
10827   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10828     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10829                                  VectorType::GenericVector);
10830   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10831     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10832                                  VectorType::GenericVector);
10833   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10834     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10835                                  VectorType::GenericVector);
10836   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10837     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10838                                  VectorType::GenericVector);
10839   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10840          "Unhandled vector element size in vector compare");
10841   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10842                                VectorType::GenericVector);
10843 }
10844 
10845 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10846 /// operates on extended vector types.  Instead of producing an IntTy result,
10847 /// like a scalar comparison, a vector comparison produces a vector of integer
10848 /// types.
10849 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10850                                           SourceLocation Loc,
10851                                           BinaryOperatorKind Opc) {
10852   // Check to make sure we're operating on vectors of the same type and width,
10853   // Allowing one side to be a scalar of element type.
10854   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10855                               /*AllowBothBool*/true,
10856                               /*AllowBoolConversions*/getLangOpts().ZVector);
10857   if (vType.isNull())
10858     return vType;
10859 
10860   QualType LHSType = LHS.get()->getType();
10861 
10862   // If AltiVec, the comparison results in a numeric type, i.e.
10863   // bool for C++, int for C
10864   if (getLangOpts().AltiVec &&
10865       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10866     return Context.getLogicalOperationType();
10867 
10868   // For non-floating point types, check for self-comparisons of the form
10869   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10870   // often indicate logic errors in the program.
10871   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10872 
10873   // Check for comparisons of floating point operands using != and ==.
10874   if (BinaryOperator::isEqualityOp(Opc) &&
10875       LHSType->hasFloatingRepresentation()) {
10876     assert(RHS.get()->getType()->hasFloatingRepresentation());
10877     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10878   }
10879 
10880   // Return a signed type for the vector.
10881   return GetSignedVectorType(vType);
10882 }
10883 
10884 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10885                                           SourceLocation Loc) {
10886   // Ensure that either both operands are of the same vector type, or
10887   // one operand is of a vector type and the other is of its element type.
10888   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10889                                        /*AllowBothBool*/true,
10890                                        /*AllowBoolConversions*/false);
10891   if (vType.isNull())
10892     return InvalidOperands(Loc, LHS, RHS);
10893   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10894       vType->hasFloatingRepresentation())
10895     return InvalidOperands(Loc, LHS, RHS);
10896   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10897   //        usage of the logical operators && and || with vectors in C. This
10898   //        check could be notionally dropped.
10899   if (!getLangOpts().CPlusPlus &&
10900       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10901     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10902 
10903   return GetSignedVectorType(LHS.get()->getType());
10904 }
10905 
10906 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10907                                            SourceLocation Loc,
10908                                            BinaryOperatorKind Opc) {
10909   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10910 
10911   bool IsCompAssign =
10912       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10913 
10914   if (LHS.get()->getType()->isVectorType() ||
10915       RHS.get()->getType()->isVectorType()) {
10916     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10917         RHS.get()->getType()->hasIntegerRepresentation())
10918       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10919                         /*AllowBothBool*/true,
10920                         /*AllowBoolConversions*/getLangOpts().ZVector);
10921     return InvalidOperands(Loc, LHS, RHS);
10922   }
10923 
10924   if (Opc == BO_And)
10925     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10926 
10927   ExprResult LHSResult = LHS, RHSResult = RHS;
10928   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10929                                                  IsCompAssign);
10930   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10931     return QualType();
10932   LHS = LHSResult.get();
10933   RHS = RHSResult.get();
10934 
10935   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10936     return compType;
10937   return InvalidOperands(Loc, LHS, RHS);
10938 }
10939 
10940 // C99 6.5.[13,14]
10941 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10942                                            SourceLocation Loc,
10943                                            BinaryOperatorKind Opc) {
10944   // Check vector operands differently.
10945   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10946     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10947 
10948   // Diagnose cases where the user write a logical and/or but probably meant a
10949   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10950   // is a constant.
10951   if (LHS.get()->getType()->isIntegerType() &&
10952       !LHS.get()->getType()->isBooleanType() &&
10953       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10954       // Don't warn in macros or template instantiations.
10955       !Loc.isMacroID() && !inTemplateInstantiation()) {
10956     // If the RHS can be constant folded, and if it constant folds to something
10957     // that isn't 0 or 1 (which indicate a potential logical operation that
10958     // happened to fold to true/false) then warn.
10959     // Parens on the RHS are ignored.
10960     Expr::EvalResult EVResult;
10961     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10962       llvm::APSInt Result = EVResult.Val.getInt();
10963       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10964            !RHS.get()->getExprLoc().isMacroID()) ||
10965           (Result != 0 && Result != 1)) {
10966         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10967           << RHS.get()->getSourceRange()
10968           << (Opc == BO_LAnd ? "&&" : "||");
10969         // Suggest replacing the logical operator with the bitwise version
10970         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10971             << (Opc == BO_LAnd ? "&" : "|")
10972             << FixItHint::CreateReplacement(SourceRange(
10973                                                  Loc, getLocForEndOfToken(Loc)),
10974                                             Opc == BO_LAnd ? "&" : "|");
10975         if (Opc == BO_LAnd)
10976           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10977           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10978               << FixItHint::CreateRemoval(
10979                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10980                                  RHS.get()->getEndLoc()));
10981       }
10982     }
10983   }
10984 
10985   if (!Context.getLangOpts().CPlusPlus) {
10986     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10987     // not operate on the built-in scalar and vector float types.
10988     if (Context.getLangOpts().OpenCL &&
10989         Context.getLangOpts().OpenCLVersion < 120) {
10990       if (LHS.get()->getType()->isFloatingType() ||
10991           RHS.get()->getType()->isFloatingType())
10992         return InvalidOperands(Loc, LHS, RHS);
10993     }
10994 
10995     LHS = UsualUnaryConversions(LHS.get());
10996     if (LHS.isInvalid())
10997       return QualType();
10998 
10999     RHS = UsualUnaryConversions(RHS.get());
11000     if (RHS.isInvalid())
11001       return QualType();
11002 
11003     if (!LHS.get()->getType()->isScalarType() ||
11004         !RHS.get()->getType()->isScalarType())
11005       return InvalidOperands(Loc, LHS, RHS);
11006 
11007     return Context.IntTy;
11008   }
11009 
11010   // The following is safe because we only use this method for
11011   // non-overloadable operands.
11012 
11013   // C++ [expr.log.and]p1
11014   // C++ [expr.log.or]p1
11015   // The operands are both contextually converted to type bool.
11016   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11017   if (LHSRes.isInvalid())
11018     return InvalidOperands(Loc, LHS, RHS);
11019   LHS = LHSRes;
11020 
11021   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11022   if (RHSRes.isInvalid())
11023     return InvalidOperands(Loc, LHS, RHS);
11024   RHS = RHSRes;
11025 
11026   // C++ [expr.log.and]p2
11027   // C++ [expr.log.or]p2
11028   // The result is a bool.
11029   return Context.BoolTy;
11030 }
11031 
11032 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11033   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11034   if (!ME) return false;
11035   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11036   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11037       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11038   if (!Base) return false;
11039   return Base->getMethodDecl() != nullptr;
11040 }
11041 
11042 /// Is the given expression (which must be 'const') a reference to a
11043 /// variable which was originally non-const, but which has become
11044 /// 'const' due to being captured within a block?
11045 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11046 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11047   assert(E->isLValue() && E->getType().isConstQualified());
11048   E = E->IgnoreParens();
11049 
11050   // Must be a reference to a declaration from an enclosing scope.
11051   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11052   if (!DRE) return NCCK_None;
11053   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11054 
11055   // The declaration must be a variable which is not declared 'const'.
11056   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11057   if (!var) return NCCK_None;
11058   if (var->getType().isConstQualified()) return NCCK_None;
11059   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11060 
11061   // Decide whether the first capture was for a block or a lambda.
11062   DeclContext *DC = S.CurContext, *Prev = nullptr;
11063   // Decide whether the first capture was for a block or a lambda.
11064   while (DC) {
11065     // For init-capture, it is possible that the variable belongs to the
11066     // template pattern of the current context.
11067     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11068       if (var->isInitCapture() &&
11069           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11070         break;
11071     if (DC == var->getDeclContext())
11072       break;
11073     Prev = DC;
11074     DC = DC->getParent();
11075   }
11076   // Unless we have an init-capture, we've gone one step too far.
11077   if (!var->isInitCapture())
11078     DC = Prev;
11079   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11080 }
11081 
11082 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11083   Ty = Ty.getNonReferenceType();
11084   if (IsDereference && Ty->isPointerType())
11085     Ty = Ty->getPointeeType();
11086   return !Ty.isConstQualified();
11087 }
11088 
11089 // Update err_typecheck_assign_const and note_typecheck_assign_const
11090 // when this enum is changed.
11091 enum {
11092   ConstFunction,
11093   ConstVariable,
11094   ConstMember,
11095   ConstMethod,
11096   NestedConstMember,
11097   ConstUnknown,  // Keep as last element
11098 };
11099 
11100 /// Emit the "read-only variable not assignable" error and print notes to give
11101 /// more information about why the variable is not assignable, such as pointing
11102 /// to the declaration of a const variable, showing that a method is const, or
11103 /// that the function is returning a const reference.
11104 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11105                                     SourceLocation Loc) {
11106   SourceRange ExprRange = E->getSourceRange();
11107 
11108   // Only emit one error on the first const found.  All other consts will emit
11109   // a note to the error.
11110   bool DiagnosticEmitted = false;
11111 
11112   // Track if the current expression is the result of a dereference, and if the
11113   // next checked expression is the result of a dereference.
11114   bool IsDereference = false;
11115   bool NextIsDereference = false;
11116 
11117   // Loop to process MemberExpr chains.
11118   while (true) {
11119     IsDereference = NextIsDereference;
11120 
11121     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11122     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11123       NextIsDereference = ME->isArrow();
11124       const ValueDecl *VD = ME->getMemberDecl();
11125       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11126         // Mutable fields can be modified even if the class is const.
11127         if (Field->isMutable()) {
11128           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11129           break;
11130         }
11131 
11132         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11133           if (!DiagnosticEmitted) {
11134             S.Diag(Loc, diag::err_typecheck_assign_const)
11135                 << ExprRange << ConstMember << false /*static*/ << Field
11136                 << Field->getType();
11137             DiagnosticEmitted = true;
11138           }
11139           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11140               << ConstMember << false /*static*/ << Field << Field->getType()
11141               << Field->getSourceRange();
11142         }
11143         E = ME->getBase();
11144         continue;
11145       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11146         if (VDecl->getType().isConstQualified()) {
11147           if (!DiagnosticEmitted) {
11148             S.Diag(Loc, diag::err_typecheck_assign_const)
11149                 << ExprRange << ConstMember << true /*static*/ << VDecl
11150                 << VDecl->getType();
11151             DiagnosticEmitted = true;
11152           }
11153           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11154               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11155               << VDecl->getSourceRange();
11156         }
11157         // Static fields do not inherit constness from parents.
11158         break;
11159       }
11160       break; // End MemberExpr
11161     } else if (const ArraySubscriptExpr *ASE =
11162                    dyn_cast<ArraySubscriptExpr>(E)) {
11163       E = ASE->getBase()->IgnoreParenImpCasts();
11164       continue;
11165     } else if (const ExtVectorElementExpr *EVE =
11166                    dyn_cast<ExtVectorElementExpr>(E)) {
11167       E = EVE->getBase()->IgnoreParenImpCasts();
11168       continue;
11169     }
11170     break;
11171   }
11172 
11173   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11174     // Function calls
11175     const FunctionDecl *FD = CE->getDirectCallee();
11176     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11177       if (!DiagnosticEmitted) {
11178         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11179                                                       << ConstFunction << FD;
11180         DiagnosticEmitted = true;
11181       }
11182       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11183              diag::note_typecheck_assign_const)
11184           << ConstFunction << FD << FD->getReturnType()
11185           << FD->getReturnTypeSourceRange();
11186     }
11187   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11188     // Point to variable declaration.
11189     if (const ValueDecl *VD = DRE->getDecl()) {
11190       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11191         if (!DiagnosticEmitted) {
11192           S.Diag(Loc, diag::err_typecheck_assign_const)
11193               << ExprRange << ConstVariable << VD << VD->getType();
11194           DiagnosticEmitted = true;
11195         }
11196         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11197             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11198       }
11199     }
11200   } else if (isa<CXXThisExpr>(E)) {
11201     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11202       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11203         if (MD->isConst()) {
11204           if (!DiagnosticEmitted) {
11205             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11206                                                           << ConstMethod << MD;
11207             DiagnosticEmitted = true;
11208           }
11209           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11210               << ConstMethod << MD << MD->getSourceRange();
11211         }
11212       }
11213     }
11214   }
11215 
11216   if (DiagnosticEmitted)
11217     return;
11218 
11219   // Can't determine a more specific message, so display the generic error.
11220   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11221 }
11222 
11223 enum OriginalExprKind {
11224   OEK_Variable,
11225   OEK_Member,
11226   OEK_LValue
11227 };
11228 
11229 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11230                                          const RecordType *Ty,
11231                                          SourceLocation Loc, SourceRange Range,
11232                                          OriginalExprKind OEK,
11233                                          bool &DiagnosticEmitted) {
11234   std::vector<const RecordType *> RecordTypeList;
11235   RecordTypeList.push_back(Ty);
11236   unsigned NextToCheckIndex = 0;
11237   // We walk the record hierarchy breadth-first to ensure that we print
11238   // diagnostics in field nesting order.
11239   while (RecordTypeList.size() > NextToCheckIndex) {
11240     bool IsNested = NextToCheckIndex > 0;
11241     for (const FieldDecl *Field :
11242          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11243       // First, check every field for constness.
11244       QualType FieldTy = Field->getType();
11245       if (FieldTy.isConstQualified()) {
11246         if (!DiagnosticEmitted) {
11247           S.Diag(Loc, diag::err_typecheck_assign_const)
11248               << Range << NestedConstMember << OEK << VD
11249               << IsNested << Field;
11250           DiagnosticEmitted = true;
11251         }
11252         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11253             << NestedConstMember << IsNested << Field
11254             << FieldTy << Field->getSourceRange();
11255       }
11256 
11257       // Then we append it to the list to check next in order.
11258       FieldTy = FieldTy.getCanonicalType();
11259       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11260         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11261           RecordTypeList.push_back(FieldRecTy);
11262       }
11263     }
11264     ++NextToCheckIndex;
11265   }
11266 }
11267 
11268 /// Emit an error for the case where a record we are trying to assign to has a
11269 /// const-qualified field somewhere in its hierarchy.
11270 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11271                                          SourceLocation Loc) {
11272   QualType Ty = E->getType();
11273   assert(Ty->isRecordType() && "lvalue was not record?");
11274   SourceRange Range = E->getSourceRange();
11275   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11276   bool DiagEmitted = false;
11277 
11278   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11279     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11280             Range, OEK_Member, DiagEmitted);
11281   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11282     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11283             Range, OEK_Variable, DiagEmitted);
11284   else
11285     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11286             Range, OEK_LValue, DiagEmitted);
11287   if (!DiagEmitted)
11288     DiagnoseConstAssignment(S, E, Loc);
11289 }
11290 
11291 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11292 /// emit an error and return true.  If so, return false.
11293 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11294   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11295 
11296   S.CheckShadowingDeclModification(E, Loc);
11297 
11298   SourceLocation OrigLoc = Loc;
11299   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11300                                                               &Loc);
11301   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11302     IsLV = Expr::MLV_InvalidMessageExpression;
11303   if (IsLV == Expr::MLV_Valid)
11304     return false;
11305 
11306   unsigned DiagID = 0;
11307   bool NeedType = false;
11308   switch (IsLV) { // C99 6.5.16p2
11309   case Expr::MLV_ConstQualified:
11310     // Use a specialized diagnostic when we're assigning to an object
11311     // from an enclosing function or block.
11312     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11313       if (NCCK == NCCK_Block)
11314         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11315       else
11316         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11317       break;
11318     }
11319 
11320     // In ARC, use some specialized diagnostics for occasions where we
11321     // infer 'const'.  These are always pseudo-strong variables.
11322     if (S.getLangOpts().ObjCAutoRefCount) {
11323       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11324       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11325         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11326 
11327         // Use the normal diagnostic if it's pseudo-__strong but the
11328         // user actually wrote 'const'.
11329         if (var->isARCPseudoStrong() &&
11330             (!var->getTypeSourceInfo() ||
11331              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11332           // There are three pseudo-strong cases:
11333           //  - self
11334           ObjCMethodDecl *method = S.getCurMethodDecl();
11335           if (method && var == method->getSelfDecl()) {
11336             DiagID = method->isClassMethod()
11337               ? diag::err_typecheck_arc_assign_self_class_method
11338               : diag::err_typecheck_arc_assign_self;
11339 
11340           //  - Objective-C externally_retained attribute.
11341           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11342                      isa<ParmVarDecl>(var)) {
11343             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11344 
11345           //  - fast enumeration variables
11346           } else {
11347             DiagID = diag::err_typecheck_arr_assign_enumeration;
11348           }
11349 
11350           SourceRange Assign;
11351           if (Loc != OrigLoc)
11352             Assign = SourceRange(OrigLoc, OrigLoc);
11353           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11354           // We need to preserve the AST regardless, so migration tool
11355           // can do its job.
11356           return false;
11357         }
11358       }
11359     }
11360 
11361     // If none of the special cases above are triggered, then this is a
11362     // simple const assignment.
11363     if (DiagID == 0) {
11364       DiagnoseConstAssignment(S, E, Loc);
11365       return true;
11366     }
11367 
11368     break;
11369   case Expr::MLV_ConstAddrSpace:
11370     DiagnoseConstAssignment(S, E, Loc);
11371     return true;
11372   case Expr::MLV_ConstQualifiedField:
11373     DiagnoseRecursiveConstFields(S, E, Loc);
11374     return true;
11375   case Expr::MLV_ArrayType:
11376   case Expr::MLV_ArrayTemporary:
11377     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11378     NeedType = true;
11379     break;
11380   case Expr::MLV_NotObjectType:
11381     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11382     NeedType = true;
11383     break;
11384   case Expr::MLV_LValueCast:
11385     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11386     break;
11387   case Expr::MLV_Valid:
11388     llvm_unreachable("did not take early return for MLV_Valid");
11389   case Expr::MLV_InvalidExpression:
11390   case Expr::MLV_MemberFunction:
11391   case Expr::MLV_ClassTemporary:
11392     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11393     break;
11394   case Expr::MLV_IncompleteType:
11395   case Expr::MLV_IncompleteVoidType:
11396     return S.RequireCompleteType(Loc, E->getType(),
11397              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11398   case Expr::MLV_DuplicateVectorComponents:
11399     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11400     break;
11401   case Expr::MLV_NoSetterProperty:
11402     llvm_unreachable("readonly properties should be processed differently");
11403   case Expr::MLV_InvalidMessageExpression:
11404     DiagID = diag::err_readonly_message_assignment;
11405     break;
11406   case Expr::MLV_SubObjCPropertySetting:
11407     DiagID = diag::err_no_subobject_property_setting;
11408     break;
11409   }
11410 
11411   SourceRange Assign;
11412   if (Loc != OrigLoc)
11413     Assign = SourceRange(OrigLoc, OrigLoc);
11414   if (NeedType)
11415     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11416   else
11417     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11418   return true;
11419 }
11420 
11421 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11422                                          SourceLocation Loc,
11423                                          Sema &Sema) {
11424   if (Sema.inTemplateInstantiation())
11425     return;
11426   if (Sema.isUnevaluatedContext())
11427     return;
11428   if (Loc.isInvalid() || Loc.isMacroID())
11429     return;
11430   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11431     return;
11432 
11433   // C / C++ fields
11434   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11435   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11436   if (ML && MR) {
11437     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11438       return;
11439     const ValueDecl *LHSDecl =
11440         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11441     const ValueDecl *RHSDecl =
11442         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11443     if (LHSDecl != RHSDecl)
11444       return;
11445     if (LHSDecl->getType().isVolatileQualified())
11446       return;
11447     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11448       if (RefTy->getPointeeType().isVolatileQualified())
11449         return;
11450 
11451     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11452   }
11453 
11454   // Objective-C instance variables
11455   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11456   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11457   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11458     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11459     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11460     if (RL && RR && RL->getDecl() == RR->getDecl())
11461       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11462   }
11463 }
11464 
11465 // C99 6.5.16.1
11466 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11467                                        SourceLocation Loc,
11468                                        QualType CompoundType) {
11469   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11470 
11471   // Verify that LHS is a modifiable lvalue, and emit error if not.
11472   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11473     return QualType();
11474 
11475   QualType LHSType = LHSExpr->getType();
11476   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11477                                              CompoundType;
11478   // OpenCL v1.2 s6.1.1.1 p2:
11479   // The half data type can only be used to declare a pointer to a buffer that
11480   // contains half values
11481   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11482     LHSType->isHalfType()) {
11483     Diag(Loc, diag::err_opencl_half_load_store) << 1
11484         << LHSType.getUnqualifiedType();
11485     return QualType();
11486   }
11487 
11488   AssignConvertType ConvTy;
11489   if (CompoundType.isNull()) {
11490     Expr *RHSCheck = RHS.get();
11491 
11492     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11493 
11494     QualType LHSTy(LHSType);
11495     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11496     if (RHS.isInvalid())
11497       return QualType();
11498     // Special case of NSObject attributes on c-style pointer types.
11499     if (ConvTy == IncompatiblePointer &&
11500         ((Context.isObjCNSObjectType(LHSType) &&
11501           RHSType->isObjCObjectPointerType()) ||
11502          (Context.isObjCNSObjectType(RHSType) &&
11503           LHSType->isObjCObjectPointerType())))
11504       ConvTy = Compatible;
11505 
11506     if (ConvTy == Compatible &&
11507         LHSType->isObjCObjectType())
11508         Diag(Loc, diag::err_objc_object_assignment)
11509           << LHSType;
11510 
11511     // If the RHS is a unary plus or minus, check to see if they = and + are
11512     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11513     // instead of "x += 4".
11514     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11515       RHSCheck = ICE->getSubExpr();
11516     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11517       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11518           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11519           // Only if the two operators are exactly adjacent.
11520           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11521           // And there is a space or other character before the subexpr of the
11522           // unary +/-.  We don't want to warn on "x=-1".
11523           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11524           UO->getSubExpr()->getBeginLoc().isFileID()) {
11525         Diag(Loc, diag::warn_not_compound_assign)
11526           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11527           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11528       }
11529     }
11530 
11531     if (ConvTy == Compatible) {
11532       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11533         // Warn about retain cycles where a block captures the LHS, but
11534         // not if the LHS is a simple variable into which the block is
11535         // being stored...unless that variable can be captured by reference!
11536         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11537         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11538         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11539           checkRetainCycles(LHSExpr, RHS.get());
11540       }
11541 
11542       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11543           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11544         // It is safe to assign a weak reference into a strong variable.
11545         // Although this code can still have problems:
11546         //   id x = self.weakProp;
11547         //   id y = self.weakProp;
11548         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11549         // paths through the function. This should be revisited if
11550         // -Wrepeated-use-of-weak is made flow-sensitive.
11551         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11552         // variable, which will be valid for the current autorelease scope.
11553         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11554                              RHS.get()->getBeginLoc()))
11555           getCurFunction()->markSafeWeakUse(RHS.get());
11556 
11557       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11558         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11559       }
11560     }
11561   } else {
11562     // Compound assignment "x += y"
11563     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11564   }
11565 
11566   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11567                                RHS.get(), AA_Assigning))
11568     return QualType();
11569 
11570   CheckForNullPointerDereference(*this, LHSExpr);
11571 
11572   // C99 6.5.16p3: The type of an assignment expression is the type of the
11573   // left operand unless the left operand has qualified type, in which case
11574   // it is the unqualified version of the type of the left operand.
11575   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11576   // is converted to the type of the assignment expression (above).
11577   // C++ 5.17p1: the type of the assignment expression is that of its left
11578   // operand.
11579   return (getLangOpts().CPlusPlus
11580           ? LHSType : LHSType.getUnqualifiedType());
11581 }
11582 
11583 // Only ignore explicit casts to void.
11584 static bool IgnoreCommaOperand(const Expr *E) {
11585   E = E->IgnoreParens();
11586 
11587   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11588     if (CE->getCastKind() == CK_ToVoid) {
11589       return true;
11590     }
11591 
11592     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11593     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11594         CE->getSubExpr()->getType()->isDependentType()) {
11595       return true;
11596     }
11597   }
11598 
11599   return false;
11600 }
11601 
11602 // Look for instances where it is likely the comma operator is confused with
11603 // another operator.  There is a whitelist of acceptable expressions for the
11604 // left hand side of the comma operator, otherwise emit a warning.
11605 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11606   // No warnings in macros
11607   if (Loc.isMacroID())
11608     return;
11609 
11610   // Don't warn in template instantiations.
11611   if (inTemplateInstantiation())
11612     return;
11613 
11614   // Scope isn't fine-grained enough to whitelist the specific cases, so
11615   // instead, skip more than needed, then call back into here with the
11616   // CommaVisitor in SemaStmt.cpp.
11617   // The whitelisted locations are the initialization and increment portions
11618   // of a for loop.  The additional checks are on the condition of
11619   // if statements, do/while loops, and for loops.
11620   // Differences in scope flags for C89 mode requires the extra logic.
11621   const unsigned ForIncrementFlags =
11622       getLangOpts().C99 || getLangOpts().CPlusPlus
11623           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11624           : Scope::ContinueScope | Scope::BreakScope;
11625   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11626   const unsigned ScopeFlags = getCurScope()->getFlags();
11627   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11628       (ScopeFlags & ForInitFlags) == ForInitFlags)
11629     return;
11630 
11631   // If there are multiple comma operators used together, get the RHS of the
11632   // of the comma operator as the LHS.
11633   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11634     if (BO->getOpcode() != BO_Comma)
11635       break;
11636     LHS = BO->getRHS();
11637   }
11638 
11639   // Only allow some expressions on LHS to not warn.
11640   if (IgnoreCommaOperand(LHS))
11641     return;
11642 
11643   Diag(Loc, diag::warn_comma_operator);
11644   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11645       << LHS->getSourceRange()
11646       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11647                                     LangOpts.CPlusPlus ? "static_cast<void>("
11648                                                        : "(void)(")
11649       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11650                                     ")");
11651 }
11652 
11653 // C99 6.5.17
11654 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11655                                    SourceLocation Loc) {
11656   LHS = S.CheckPlaceholderExpr(LHS.get());
11657   RHS = S.CheckPlaceholderExpr(RHS.get());
11658   if (LHS.isInvalid() || RHS.isInvalid())
11659     return QualType();
11660 
11661   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11662   // operands, but not unary promotions.
11663   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11664 
11665   // So we treat the LHS as a ignored value, and in C++ we allow the
11666   // containing site to determine what should be done with the RHS.
11667   LHS = S.IgnoredValueConversions(LHS.get());
11668   if (LHS.isInvalid())
11669     return QualType();
11670 
11671   S.DiagnoseUnusedExprResult(LHS.get());
11672 
11673   if (!S.getLangOpts().CPlusPlus) {
11674     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11675     if (RHS.isInvalid())
11676       return QualType();
11677     if (!RHS.get()->getType()->isVoidType())
11678       S.RequireCompleteType(Loc, RHS.get()->getType(),
11679                             diag::err_incomplete_type);
11680   }
11681 
11682   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11683     S.DiagnoseCommaOperator(LHS.get(), Loc);
11684 
11685   return RHS.get()->getType();
11686 }
11687 
11688 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11689 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11690 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11691                                                ExprValueKind &VK,
11692                                                ExprObjectKind &OK,
11693                                                SourceLocation OpLoc,
11694                                                bool IsInc, bool IsPrefix) {
11695   if (Op->isTypeDependent())
11696     return S.Context.DependentTy;
11697 
11698   QualType ResType = Op->getType();
11699   // Atomic types can be used for increment / decrement where the non-atomic
11700   // versions can, so ignore the _Atomic() specifier for the purpose of
11701   // checking.
11702   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11703     ResType = ResAtomicType->getValueType();
11704 
11705   assert(!ResType.isNull() && "no type for increment/decrement expression");
11706 
11707   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11708     // Decrement of bool is not allowed.
11709     if (!IsInc) {
11710       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11711       return QualType();
11712     }
11713     // Increment of bool sets it to true, but is deprecated.
11714     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11715                                               : diag::warn_increment_bool)
11716       << Op->getSourceRange();
11717   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11718     // Error on enum increments and decrements in C++ mode
11719     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11720     return QualType();
11721   } else if (ResType->isRealType()) {
11722     // OK!
11723   } else if (ResType->isPointerType()) {
11724     // C99 6.5.2.4p2, 6.5.6p2
11725     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11726       return QualType();
11727   } else if (ResType->isObjCObjectPointerType()) {
11728     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11729     // Otherwise, we just need a complete type.
11730     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11731         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11732       return QualType();
11733   } else if (ResType->isAnyComplexType()) {
11734     // C99 does not support ++/-- on complex types, we allow as an extension.
11735     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11736       << ResType << Op->getSourceRange();
11737   } else if (ResType->isPlaceholderType()) {
11738     ExprResult PR = S.CheckPlaceholderExpr(Op);
11739     if (PR.isInvalid()) return QualType();
11740     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11741                                           IsInc, IsPrefix);
11742   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11743     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11744   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11745              (ResType->getAs<VectorType>()->getVectorKind() !=
11746               VectorType::AltiVecBool)) {
11747     // The z vector extensions allow ++ and -- for non-bool vectors.
11748   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11749             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11750     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11751   } else {
11752     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11753       << ResType << int(IsInc) << Op->getSourceRange();
11754     return QualType();
11755   }
11756   // At this point, we know we have a real, complex or pointer type.
11757   // Now make sure the operand is a modifiable lvalue.
11758   if (CheckForModifiableLvalue(Op, OpLoc, S))
11759     return QualType();
11760   // In C++, a prefix increment is the same type as the operand. Otherwise
11761   // (in C or with postfix), the increment is the unqualified type of the
11762   // operand.
11763   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11764     VK = VK_LValue;
11765     OK = Op->getObjectKind();
11766     return ResType;
11767   } else {
11768     VK = VK_RValue;
11769     return ResType.getUnqualifiedType();
11770   }
11771 }
11772 
11773 
11774 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11775 /// This routine allows us to typecheck complex/recursive expressions
11776 /// where the declaration is needed for type checking. We only need to
11777 /// handle cases when the expression references a function designator
11778 /// or is an lvalue. Here are some examples:
11779 ///  - &(x) => x
11780 ///  - &*****f => f for f a function designator.
11781 ///  - &s.xx => s
11782 ///  - &s.zz[1].yy -> s, if zz is an array
11783 ///  - *(x + 1) -> x, if x is an array
11784 ///  - &"123"[2] -> 0
11785 ///  - & __real__ x -> x
11786 static ValueDecl *getPrimaryDecl(Expr *E) {
11787   switch (E->getStmtClass()) {
11788   case Stmt::DeclRefExprClass:
11789     return cast<DeclRefExpr>(E)->getDecl();
11790   case Stmt::MemberExprClass:
11791     // If this is an arrow operator, the address is an offset from
11792     // the base's value, so the object the base refers to is
11793     // irrelevant.
11794     if (cast<MemberExpr>(E)->isArrow())
11795       return nullptr;
11796     // Otherwise, the expression refers to a part of the base
11797     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11798   case Stmt::ArraySubscriptExprClass: {
11799     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11800     // promotion of register arrays earlier.
11801     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11802     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11803       if (ICE->getSubExpr()->getType()->isArrayType())
11804         return getPrimaryDecl(ICE->getSubExpr());
11805     }
11806     return nullptr;
11807   }
11808   case Stmt::UnaryOperatorClass: {
11809     UnaryOperator *UO = cast<UnaryOperator>(E);
11810 
11811     switch(UO->getOpcode()) {
11812     case UO_Real:
11813     case UO_Imag:
11814     case UO_Extension:
11815       return getPrimaryDecl(UO->getSubExpr());
11816     default:
11817       return nullptr;
11818     }
11819   }
11820   case Stmt::ParenExprClass:
11821     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11822   case Stmt::ImplicitCastExprClass:
11823     // If the result of an implicit cast is an l-value, we care about
11824     // the sub-expression; otherwise, the result here doesn't matter.
11825     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11826   default:
11827     return nullptr;
11828   }
11829 }
11830 
11831 namespace {
11832   enum {
11833     AO_Bit_Field = 0,
11834     AO_Vector_Element = 1,
11835     AO_Property_Expansion = 2,
11836     AO_Register_Variable = 3,
11837     AO_No_Error = 4
11838   };
11839 }
11840 /// Diagnose invalid operand for address of operations.
11841 ///
11842 /// \param Type The type of operand which cannot have its address taken.
11843 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11844                                          Expr *E, unsigned Type) {
11845   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11846 }
11847 
11848 /// CheckAddressOfOperand - The operand of & must be either a function
11849 /// designator or an lvalue designating an object. If it is an lvalue, the
11850 /// object cannot be declared with storage class register or be a bit field.
11851 /// Note: The usual conversions are *not* applied to the operand of the &
11852 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11853 /// In C++, the operand might be an overloaded function name, in which case
11854 /// we allow the '&' but retain the overloaded-function type.
11855 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11856   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11857     if (PTy->getKind() == BuiltinType::Overload) {
11858       Expr *E = OrigOp.get()->IgnoreParens();
11859       if (!isa<OverloadExpr>(E)) {
11860         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11861         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11862           << OrigOp.get()->getSourceRange();
11863         return QualType();
11864       }
11865 
11866       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11867       if (isa<UnresolvedMemberExpr>(Ovl))
11868         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11869           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11870             << OrigOp.get()->getSourceRange();
11871           return QualType();
11872         }
11873 
11874       return Context.OverloadTy;
11875     }
11876 
11877     if (PTy->getKind() == BuiltinType::UnknownAny)
11878       return Context.UnknownAnyTy;
11879 
11880     if (PTy->getKind() == BuiltinType::BoundMember) {
11881       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11882         << OrigOp.get()->getSourceRange();
11883       return QualType();
11884     }
11885 
11886     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11887     if (OrigOp.isInvalid()) return QualType();
11888   }
11889 
11890   if (OrigOp.get()->isTypeDependent())
11891     return Context.DependentTy;
11892 
11893   assert(!OrigOp.get()->getType()->isPlaceholderType());
11894 
11895   // Make sure to ignore parentheses in subsequent checks
11896   Expr *op = OrigOp.get()->IgnoreParens();
11897 
11898   // In OpenCL captures for blocks called as lambda functions
11899   // are located in the private address space. Blocks used in
11900   // enqueue_kernel can be located in a different address space
11901   // depending on a vendor implementation. Thus preventing
11902   // taking an address of the capture to avoid invalid AS casts.
11903   if (LangOpts.OpenCL) {
11904     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11905     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11906       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11907       return QualType();
11908     }
11909   }
11910 
11911   if (getLangOpts().C99) {
11912     // Implement C99-only parts of addressof rules.
11913     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11914       if (uOp->getOpcode() == UO_Deref)
11915         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11916         // (assuming the deref expression is valid).
11917         return uOp->getSubExpr()->getType();
11918     }
11919     // Technically, there should be a check for array subscript
11920     // expressions here, but the result of one is always an lvalue anyway.
11921   }
11922   ValueDecl *dcl = getPrimaryDecl(op);
11923 
11924   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11925     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11926                                            op->getBeginLoc()))
11927       return QualType();
11928 
11929   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11930   unsigned AddressOfError = AO_No_Error;
11931 
11932   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11933     bool sfinae = (bool)isSFINAEContext();
11934     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11935                                   : diag::ext_typecheck_addrof_temporary)
11936       << op->getType() << op->getSourceRange();
11937     if (sfinae)
11938       return QualType();
11939     // Materialize the temporary as an lvalue so that we can take its address.
11940     OrigOp = op =
11941         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11942   } else if (isa<ObjCSelectorExpr>(op)) {
11943     return Context.getPointerType(op->getType());
11944   } else if (lval == Expr::LV_MemberFunction) {
11945     // If it's an instance method, make a member pointer.
11946     // The expression must have exactly the form &A::foo.
11947 
11948     // If the underlying expression isn't a decl ref, give up.
11949     if (!isa<DeclRefExpr>(op)) {
11950       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11951         << OrigOp.get()->getSourceRange();
11952       return QualType();
11953     }
11954     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11955     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11956 
11957     // The id-expression was parenthesized.
11958     if (OrigOp.get() != DRE) {
11959       Diag(OpLoc, diag::err_parens_pointer_member_function)
11960         << OrigOp.get()->getSourceRange();
11961 
11962     // The method was named without a qualifier.
11963     } else if (!DRE->getQualifier()) {
11964       if (MD->getParent()->getName().empty())
11965         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11966           << op->getSourceRange();
11967       else {
11968         SmallString<32> Str;
11969         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11970         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11971           << op->getSourceRange()
11972           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11973       }
11974     }
11975 
11976     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11977     if (isa<CXXDestructorDecl>(MD))
11978       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11979 
11980     QualType MPTy = Context.getMemberPointerType(
11981         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11982     // Under the MS ABI, lock down the inheritance model now.
11983     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11984       (void)isCompleteType(OpLoc, MPTy);
11985     return MPTy;
11986   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11987     // C99 6.5.3.2p1
11988     // The operand must be either an l-value or a function designator
11989     if (!op->getType()->isFunctionType()) {
11990       // Use a special diagnostic for loads from property references.
11991       if (isa<PseudoObjectExpr>(op)) {
11992         AddressOfError = AO_Property_Expansion;
11993       } else {
11994         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11995           << op->getType() << op->getSourceRange();
11996         return QualType();
11997       }
11998     }
11999   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12000     // The operand cannot be a bit-field
12001     AddressOfError = AO_Bit_Field;
12002   } else if (op->getObjectKind() == OK_VectorComponent) {
12003     // The operand cannot be an element of a vector
12004     AddressOfError = AO_Vector_Element;
12005   } else if (dcl) { // C99 6.5.3.2p1
12006     // We have an lvalue with a decl. Make sure the decl is not declared
12007     // with the register storage-class specifier.
12008     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12009       // in C++ it is not error to take address of a register
12010       // variable (c++03 7.1.1P3)
12011       if (vd->getStorageClass() == SC_Register &&
12012           !getLangOpts().CPlusPlus) {
12013         AddressOfError = AO_Register_Variable;
12014       }
12015     } else if (isa<MSPropertyDecl>(dcl)) {
12016       AddressOfError = AO_Property_Expansion;
12017     } else if (isa<FunctionTemplateDecl>(dcl)) {
12018       return Context.OverloadTy;
12019     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12020       // Okay: we can take the address of a field.
12021       // Could be a pointer to member, though, if there is an explicit
12022       // scope qualifier for the class.
12023       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12024         DeclContext *Ctx = dcl->getDeclContext();
12025         if (Ctx && Ctx->isRecord()) {
12026           if (dcl->getType()->isReferenceType()) {
12027             Diag(OpLoc,
12028                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12029               << dcl->getDeclName() << dcl->getType();
12030             return QualType();
12031           }
12032 
12033           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12034             Ctx = Ctx->getParent();
12035 
12036           QualType MPTy = Context.getMemberPointerType(
12037               op->getType(),
12038               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12039           // Under the MS ABI, lock down the inheritance model now.
12040           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12041             (void)isCompleteType(OpLoc, MPTy);
12042           return MPTy;
12043         }
12044       }
12045     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12046                !isa<BindingDecl>(dcl))
12047       llvm_unreachable("Unknown/unexpected decl type");
12048   }
12049 
12050   if (AddressOfError != AO_No_Error) {
12051     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12052     return QualType();
12053   }
12054 
12055   if (lval == Expr::LV_IncompleteVoidType) {
12056     // Taking the address of a void variable is technically illegal, but we
12057     // allow it in cases which are otherwise valid.
12058     // Example: "extern void x; void* y = &x;".
12059     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12060   }
12061 
12062   // If the operand has type "type", the result has type "pointer to type".
12063   if (op->getType()->isObjCObjectType())
12064     return Context.getObjCObjectPointerType(op->getType());
12065 
12066   CheckAddressOfPackedMember(op);
12067 
12068   return Context.getPointerType(op->getType());
12069 }
12070 
12071 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12072   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12073   if (!DRE)
12074     return;
12075   const Decl *D = DRE->getDecl();
12076   if (!D)
12077     return;
12078   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12079   if (!Param)
12080     return;
12081   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12082     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12083       return;
12084   if (FunctionScopeInfo *FD = S.getCurFunction())
12085     if (!FD->ModifiedNonNullParams.count(Param))
12086       FD->ModifiedNonNullParams.insert(Param);
12087 }
12088 
12089 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12090 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12091                                         SourceLocation OpLoc) {
12092   if (Op->isTypeDependent())
12093     return S.Context.DependentTy;
12094 
12095   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12096   if (ConvResult.isInvalid())
12097     return QualType();
12098   Op = ConvResult.get();
12099   QualType OpTy = Op->getType();
12100   QualType Result;
12101 
12102   if (isa<CXXReinterpretCastExpr>(Op)) {
12103     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12104     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12105                                      Op->getSourceRange());
12106   }
12107 
12108   if (const PointerType *PT = OpTy->getAs<PointerType>())
12109   {
12110     Result = PT->getPointeeType();
12111   }
12112   else if (const ObjCObjectPointerType *OPT =
12113              OpTy->getAs<ObjCObjectPointerType>())
12114     Result = OPT->getPointeeType();
12115   else {
12116     ExprResult PR = S.CheckPlaceholderExpr(Op);
12117     if (PR.isInvalid()) return QualType();
12118     if (PR.get() != Op)
12119       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12120   }
12121 
12122   if (Result.isNull()) {
12123     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12124       << OpTy << Op->getSourceRange();
12125     return QualType();
12126   }
12127 
12128   // Note that per both C89 and C99, indirection is always legal, even if Result
12129   // is an incomplete type or void.  It would be possible to warn about
12130   // dereferencing a void pointer, but it's completely well-defined, and such a
12131   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12132   // for pointers to 'void' but is fine for any other pointer type:
12133   //
12134   // C++ [expr.unary.op]p1:
12135   //   [...] the expression to which [the unary * operator] is applied shall
12136   //   be a pointer to an object type, or a pointer to a function type
12137   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12138     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12139       << OpTy << Op->getSourceRange();
12140 
12141   // Dereferences are usually l-values...
12142   VK = VK_LValue;
12143 
12144   // ...except that certain expressions are never l-values in C.
12145   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12146     VK = VK_RValue;
12147 
12148   return Result;
12149 }
12150 
12151 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12152   BinaryOperatorKind Opc;
12153   switch (Kind) {
12154   default: llvm_unreachable("Unknown binop!");
12155   case tok::periodstar:           Opc = BO_PtrMemD; break;
12156   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12157   case tok::star:                 Opc = BO_Mul; break;
12158   case tok::slash:                Opc = BO_Div; break;
12159   case tok::percent:              Opc = BO_Rem; break;
12160   case tok::plus:                 Opc = BO_Add; break;
12161   case tok::minus:                Opc = BO_Sub; break;
12162   case tok::lessless:             Opc = BO_Shl; break;
12163   case tok::greatergreater:       Opc = BO_Shr; break;
12164   case tok::lessequal:            Opc = BO_LE; break;
12165   case tok::less:                 Opc = BO_LT; break;
12166   case tok::greaterequal:         Opc = BO_GE; break;
12167   case tok::greater:              Opc = BO_GT; break;
12168   case tok::exclaimequal:         Opc = BO_NE; break;
12169   case tok::equalequal:           Opc = BO_EQ; break;
12170   case tok::spaceship:            Opc = BO_Cmp; break;
12171   case tok::amp:                  Opc = BO_And; break;
12172   case tok::caret:                Opc = BO_Xor; break;
12173   case tok::pipe:                 Opc = BO_Or; break;
12174   case tok::ampamp:               Opc = BO_LAnd; break;
12175   case tok::pipepipe:             Opc = BO_LOr; break;
12176   case tok::equal:                Opc = BO_Assign; break;
12177   case tok::starequal:            Opc = BO_MulAssign; break;
12178   case tok::slashequal:           Opc = BO_DivAssign; break;
12179   case tok::percentequal:         Opc = BO_RemAssign; break;
12180   case tok::plusequal:            Opc = BO_AddAssign; break;
12181   case tok::minusequal:           Opc = BO_SubAssign; break;
12182   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12183   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12184   case tok::ampequal:             Opc = BO_AndAssign; break;
12185   case tok::caretequal:           Opc = BO_XorAssign; break;
12186   case tok::pipeequal:            Opc = BO_OrAssign; break;
12187   case tok::comma:                Opc = BO_Comma; break;
12188   }
12189   return Opc;
12190 }
12191 
12192 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12193   tok::TokenKind Kind) {
12194   UnaryOperatorKind Opc;
12195   switch (Kind) {
12196   default: llvm_unreachable("Unknown unary op!");
12197   case tok::plusplus:     Opc = UO_PreInc; break;
12198   case tok::minusminus:   Opc = UO_PreDec; break;
12199   case tok::amp:          Opc = UO_AddrOf; break;
12200   case tok::star:         Opc = UO_Deref; break;
12201   case tok::plus:         Opc = UO_Plus; break;
12202   case tok::minus:        Opc = UO_Minus; break;
12203   case tok::tilde:        Opc = UO_Not; break;
12204   case tok::exclaim:      Opc = UO_LNot; break;
12205   case tok::kw___real:    Opc = UO_Real; break;
12206   case tok::kw___imag:    Opc = UO_Imag; break;
12207   case tok::kw___extension__: Opc = UO_Extension; break;
12208   }
12209   return Opc;
12210 }
12211 
12212 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12213 /// This warning suppressed in the event of macro expansions.
12214 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12215                                    SourceLocation OpLoc, bool IsBuiltin) {
12216   if (S.inTemplateInstantiation())
12217     return;
12218   if (S.isUnevaluatedContext())
12219     return;
12220   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12221     return;
12222   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12223   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12224   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12225   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12226   if (!LHSDeclRef || !RHSDeclRef ||
12227       LHSDeclRef->getLocation().isMacroID() ||
12228       RHSDeclRef->getLocation().isMacroID())
12229     return;
12230   const ValueDecl *LHSDecl =
12231     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12232   const ValueDecl *RHSDecl =
12233     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12234   if (LHSDecl != RHSDecl)
12235     return;
12236   if (LHSDecl->getType().isVolatileQualified())
12237     return;
12238   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12239     if (RefTy->getPointeeType().isVolatileQualified())
12240       return;
12241 
12242   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12243                           : diag::warn_self_assignment_overloaded)
12244       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12245       << RHSExpr->getSourceRange();
12246 }
12247 
12248 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12249 /// is usually indicative of introspection within the Objective-C pointer.
12250 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12251                                           SourceLocation OpLoc) {
12252   if (!S.getLangOpts().ObjC)
12253     return;
12254 
12255   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12256   const Expr *LHS = L.get();
12257   const Expr *RHS = R.get();
12258 
12259   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12260     ObjCPointerExpr = LHS;
12261     OtherExpr = RHS;
12262   }
12263   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12264     ObjCPointerExpr = RHS;
12265     OtherExpr = LHS;
12266   }
12267 
12268   // This warning is deliberately made very specific to reduce false
12269   // positives with logic that uses '&' for hashing.  This logic mainly
12270   // looks for code trying to introspect into tagged pointers, which
12271   // code should generally never do.
12272   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12273     unsigned Diag = diag::warn_objc_pointer_masking;
12274     // Determine if we are introspecting the result of performSelectorXXX.
12275     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12276     // Special case messages to -performSelector and friends, which
12277     // can return non-pointer values boxed in a pointer value.
12278     // Some clients may wish to silence warnings in this subcase.
12279     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12280       Selector S = ME->getSelector();
12281       StringRef SelArg0 = S.getNameForSlot(0);
12282       if (SelArg0.startswith("performSelector"))
12283         Diag = diag::warn_objc_pointer_masking_performSelector;
12284     }
12285 
12286     S.Diag(OpLoc, Diag)
12287       << ObjCPointerExpr->getSourceRange();
12288   }
12289 }
12290 
12291 static NamedDecl *getDeclFromExpr(Expr *E) {
12292   if (!E)
12293     return nullptr;
12294   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12295     return DRE->getDecl();
12296   if (auto *ME = dyn_cast<MemberExpr>(E))
12297     return ME->getMemberDecl();
12298   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12299     return IRE->getDecl();
12300   return nullptr;
12301 }
12302 
12303 // This helper function promotes a binary operator's operands (which are of a
12304 // half vector type) to a vector of floats and then truncates the result to
12305 // a vector of either half or short.
12306 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12307                                       BinaryOperatorKind Opc, QualType ResultTy,
12308                                       ExprValueKind VK, ExprObjectKind OK,
12309                                       bool IsCompAssign, SourceLocation OpLoc,
12310                                       FPOptions FPFeatures) {
12311   auto &Context = S.getASTContext();
12312   assert((isVector(ResultTy, Context.HalfTy) ||
12313           isVector(ResultTy, Context.ShortTy)) &&
12314          "Result must be a vector of half or short");
12315   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12316          isVector(RHS.get()->getType(), Context.HalfTy) &&
12317          "both operands expected to be a half vector");
12318 
12319   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12320   QualType BinOpResTy = RHS.get()->getType();
12321 
12322   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12323   // change BinOpResTy to a vector of ints.
12324   if (isVector(ResultTy, Context.ShortTy))
12325     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12326 
12327   if (IsCompAssign)
12328     return new (Context) CompoundAssignOperator(
12329         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12330         OpLoc, FPFeatures);
12331 
12332   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12333   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12334                                           VK, OK, OpLoc, FPFeatures);
12335   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12336 }
12337 
12338 static std::pair<ExprResult, ExprResult>
12339 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12340                            Expr *RHSExpr) {
12341   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12342   if (!S.getLangOpts().CPlusPlus) {
12343     // C cannot handle TypoExpr nodes on either side of a binop because it
12344     // doesn't handle dependent types properly, so make sure any TypoExprs have
12345     // been dealt with before checking the operands.
12346     LHS = S.CorrectDelayedTyposInExpr(LHS);
12347     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12348       if (Opc != BO_Assign)
12349         return ExprResult(E);
12350       // Avoid correcting the RHS to the same Expr as the LHS.
12351       Decl *D = getDeclFromExpr(E);
12352       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12353     });
12354   }
12355   return std::make_pair(LHS, RHS);
12356 }
12357 
12358 /// Returns true if conversion between vectors of halfs and vectors of floats
12359 /// is needed.
12360 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12361                                      QualType SrcType) {
12362   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12363          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12364          isVector(SrcType, Ctx.HalfTy);
12365 }
12366 
12367 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12368 /// operator @p Opc at location @c TokLoc. This routine only supports
12369 /// built-in operations; ActOnBinOp handles overloaded operators.
12370 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12371                                     BinaryOperatorKind Opc,
12372                                     Expr *LHSExpr, Expr *RHSExpr) {
12373   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12374     // The syntax only allows initializer lists on the RHS of assignment,
12375     // so we don't need to worry about accepting invalid code for
12376     // non-assignment operators.
12377     // C++11 5.17p9:
12378     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12379     //   of x = {} is x = T().
12380     InitializationKind Kind = InitializationKind::CreateDirectList(
12381         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12382     InitializedEntity Entity =
12383         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12384     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12385     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12386     if (Init.isInvalid())
12387       return Init;
12388     RHSExpr = Init.get();
12389   }
12390 
12391   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12392   QualType ResultTy;     // Result type of the binary operator.
12393   // The following two variables are used for compound assignment operators
12394   QualType CompLHSTy;    // Type of LHS after promotions for computation
12395   QualType CompResultTy; // Type of computation result
12396   ExprValueKind VK = VK_RValue;
12397   ExprObjectKind OK = OK_Ordinary;
12398   bool ConvertHalfVec = false;
12399 
12400   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12401   if (!LHS.isUsable() || !RHS.isUsable())
12402     return ExprError();
12403 
12404   if (getLangOpts().OpenCL) {
12405     QualType LHSTy = LHSExpr->getType();
12406     QualType RHSTy = RHSExpr->getType();
12407     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12408     // the ATOMIC_VAR_INIT macro.
12409     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12410       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12411       if (BO_Assign == Opc)
12412         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12413       else
12414         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12415       return ExprError();
12416     }
12417 
12418     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12419     // only with a builtin functions and therefore should be disallowed here.
12420     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12421         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12422         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12423         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12424       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12425       return ExprError();
12426     }
12427   }
12428 
12429   // Diagnose operations on the unsupported types for OpenMP device compilation.
12430   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12431     if (Opc != BO_Assign && Opc != BO_Comma) {
12432       checkOpenMPDeviceExpr(LHSExpr);
12433       checkOpenMPDeviceExpr(RHSExpr);
12434     }
12435   }
12436 
12437   switch (Opc) {
12438   case BO_Assign:
12439     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12440     if (getLangOpts().CPlusPlus &&
12441         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12442       VK = LHS.get()->getValueKind();
12443       OK = LHS.get()->getObjectKind();
12444     }
12445     if (!ResultTy.isNull()) {
12446       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12447       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12448 
12449       // Avoid copying a block to the heap if the block is assigned to a local
12450       // auto variable that is declared in the same scope as the block. This
12451       // optimization is unsafe if the local variable is declared in an outer
12452       // scope. For example:
12453       //
12454       // BlockTy b;
12455       // {
12456       //   b = ^{...};
12457       // }
12458       // // It is unsafe to invoke the block here if it wasn't copied to the
12459       // // heap.
12460       // b();
12461 
12462       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12463         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12464           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12465             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12466               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12467     }
12468     RecordModifiableNonNullParam(*this, LHS.get());
12469     break;
12470   case BO_PtrMemD:
12471   case BO_PtrMemI:
12472     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12473                                             Opc == BO_PtrMemI);
12474     break;
12475   case BO_Mul:
12476   case BO_Div:
12477     ConvertHalfVec = true;
12478     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12479                                            Opc == BO_Div);
12480     break;
12481   case BO_Rem:
12482     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12483     break;
12484   case BO_Add:
12485     ConvertHalfVec = true;
12486     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12487     break;
12488   case BO_Sub:
12489     ConvertHalfVec = true;
12490     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12491     break;
12492   case BO_Shl:
12493   case BO_Shr:
12494     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12495     break;
12496   case BO_LE:
12497   case BO_LT:
12498   case BO_GE:
12499   case BO_GT:
12500     ConvertHalfVec = true;
12501     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12502     break;
12503   case BO_EQ:
12504   case BO_NE:
12505     ConvertHalfVec = true;
12506     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12507     break;
12508   case BO_Cmp:
12509     ConvertHalfVec = true;
12510     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12511     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12512     break;
12513   case BO_And:
12514     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12515     LLVM_FALLTHROUGH;
12516   case BO_Xor:
12517   case BO_Or:
12518     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12519     break;
12520   case BO_LAnd:
12521   case BO_LOr:
12522     ConvertHalfVec = true;
12523     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12524     break;
12525   case BO_MulAssign:
12526   case BO_DivAssign:
12527     ConvertHalfVec = true;
12528     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12529                                                Opc == BO_DivAssign);
12530     CompLHSTy = CompResultTy;
12531     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12532       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12533     break;
12534   case BO_RemAssign:
12535     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12536     CompLHSTy = CompResultTy;
12537     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12538       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12539     break;
12540   case BO_AddAssign:
12541     ConvertHalfVec = true;
12542     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12543     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12544       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12545     break;
12546   case BO_SubAssign:
12547     ConvertHalfVec = true;
12548     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12549     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12550       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12551     break;
12552   case BO_ShlAssign:
12553   case BO_ShrAssign:
12554     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12555     CompLHSTy = CompResultTy;
12556     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12557       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12558     break;
12559   case BO_AndAssign:
12560   case BO_OrAssign: // fallthrough
12561     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12562     LLVM_FALLTHROUGH;
12563   case BO_XorAssign:
12564     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12565     CompLHSTy = CompResultTy;
12566     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12567       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12568     break;
12569   case BO_Comma:
12570     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12571     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12572       VK = RHS.get()->getValueKind();
12573       OK = RHS.get()->getObjectKind();
12574     }
12575     break;
12576   }
12577   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12578     return ExprError();
12579 
12580   // Some of the binary operations require promoting operands of half vector to
12581   // float vectors and truncating the result back to half vector. For now, we do
12582   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12583   // arm64).
12584   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12585          isVector(LHS.get()->getType(), Context.HalfTy) &&
12586          "both sides are half vectors or neither sides are");
12587   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12588                                             LHS.get()->getType());
12589 
12590   // Check for array bounds violations for both sides of the BinaryOperator
12591   CheckArrayAccess(LHS.get());
12592   CheckArrayAccess(RHS.get());
12593 
12594   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12595     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12596                                                  &Context.Idents.get("object_setClass"),
12597                                                  SourceLocation(), LookupOrdinaryName);
12598     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12599       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12600       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12601           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12602                                         "object_setClass(")
12603           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12604                                           ",")
12605           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12606     }
12607     else
12608       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12609   }
12610   else if (const ObjCIvarRefExpr *OIRE =
12611            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12612     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12613 
12614   // Opc is not a compound assignment if CompResultTy is null.
12615   if (CompResultTy.isNull()) {
12616     if (ConvertHalfVec)
12617       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12618                                  OpLoc, FPFeatures);
12619     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12620                                         OK, OpLoc, FPFeatures);
12621   }
12622 
12623   // Handle compound assignments.
12624   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12625       OK_ObjCProperty) {
12626     VK = VK_LValue;
12627     OK = LHS.get()->getObjectKind();
12628   }
12629 
12630   if (ConvertHalfVec)
12631     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12632                                OpLoc, FPFeatures);
12633 
12634   return new (Context) CompoundAssignOperator(
12635       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12636       OpLoc, FPFeatures);
12637 }
12638 
12639 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12640 /// operators are mixed in a way that suggests that the programmer forgot that
12641 /// comparison operators have higher precedence. The most typical example of
12642 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12643 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12644                                       SourceLocation OpLoc, Expr *LHSExpr,
12645                                       Expr *RHSExpr) {
12646   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12647   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12648 
12649   // Check that one of the sides is a comparison operator and the other isn't.
12650   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12651   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12652   if (isLeftComp == isRightComp)
12653     return;
12654 
12655   // Bitwise operations are sometimes used as eager logical ops.
12656   // Don't diagnose this.
12657   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12658   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12659   if (isLeftBitwise || isRightBitwise)
12660     return;
12661 
12662   SourceRange DiagRange = isLeftComp
12663                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12664                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12665   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12666   SourceRange ParensRange =
12667       isLeftComp
12668           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12669           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12670 
12671   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12672     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12673   SuggestParentheses(Self, OpLoc,
12674     Self.PDiag(diag::note_precedence_silence) << OpStr,
12675     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12676   SuggestParentheses(Self, OpLoc,
12677     Self.PDiag(diag::note_precedence_bitwise_first)
12678       << BinaryOperator::getOpcodeStr(Opc),
12679     ParensRange);
12680 }
12681 
12682 /// It accepts a '&&' expr that is inside a '||' one.
12683 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12684 /// in parentheses.
12685 static void
12686 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12687                                        BinaryOperator *Bop) {
12688   assert(Bop->getOpcode() == BO_LAnd);
12689   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12690       << Bop->getSourceRange() << OpLoc;
12691   SuggestParentheses(Self, Bop->getOperatorLoc(),
12692     Self.PDiag(diag::note_precedence_silence)
12693       << Bop->getOpcodeStr(),
12694     Bop->getSourceRange());
12695 }
12696 
12697 /// Returns true if the given expression can be evaluated as a constant
12698 /// 'true'.
12699 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12700   bool Res;
12701   return !E->isValueDependent() &&
12702          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12703 }
12704 
12705 /// Returns true if the given expression can be evaluated as a constant
12706 /// 'false'.
12707 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12708   bool Res;
12709   return !E->isValueDependent() &&
12710          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12711 }
12712 
12713 /// Look for '&&' in the left hand of a '||' expr.
12714 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12715                                              Expr *LHSExpr, Expr *RHSExpr) {
12716   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12717     if (Bop->getOpcode() == BO_LAnd) {
12718       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12719       if (EvaluatesAsFalse(S, RHSExpr))
12720         return;
12721       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12722       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12723         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12724     } else if (Bop->getOpcode() == BO_LOr) {
12725       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12726         // If it's "a || b && 1 || c" we didn't warn earlier for
12727         // "a || b && 1", but warn now.
12728         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12729           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12730       }
12731     }
12732   }
12733 }
12734 
12735 /// Look for '&&' in the right hand of a '||' expr.
12736 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12737                                              Expr *LHSExpr, Expr *RHSExpr) {
12738   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12739     if (Bop->getOpcode() == BO_LAnd) {
12740       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12741       if (EvaluatesAsFalse(S, LHSExpr))
12742         return;
12743       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12744       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12745         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12746     }
12747   }
12748 }
12749 
12750 /// Look for bitwise op in the left or right hand of a bitwise op with
12751 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12752 /// the '&' expression in parentheses.
12753 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12754                                          SourceLocation OpLoc, Expr *SubExpr) {
12755   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12756     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12757       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12758         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12759         << Bop->getSourceRange() << OpLoc;
12760       SuggestParentheses(S, Bop->getOperatorLoc(),
12761         S.PDiag(diag::note_precedence_silence)
12762           << Bop->getOpcodeStr(),
12763         Bop->getSourceRange());
12764     }
12765   }
12766 }
12767 
12768 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12769                                     Expr *SubExpr, StringRef Shift) {
12770   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12771     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12772       StringRef Op = Bop->getOpcodeStr();
12773       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12774           << Bop->getSourceRange() << OpLoc << Shift << Op;
12775       SuggestParentheses(S, Bop->getOperatorLoc(),
12776           S.PDiag(diag::note_precedence_silence) << Op,
12777           Bop->getSourceRange());
12778     }
12779   }
12780 }
12781 
12782 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12783                                  Expr *LHSExpr, Expr *RHSExpr) {
12784   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12785   if (!OCE)
12786     return;
12787 
12788   FunctionDecl *FD = OCE->getDirectCallee();
12789   if (!FD || !FD->isOverloadedOperator())
12790     return;
12791 
12792   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12793   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12794     return;
12795 
12796   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12797       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12798       << (Kind == OO_LessLess);
12799   SuggestParentheses(S, OCE->getOperatorLoc(),
12800                      S.PDiag(diag::note_precedence_silence)
12801                          << (Kind == OO_LessLess ? "<<" : ">>"),
12802                      OCE->getSourceRange());
12803   SuggestParentheses(
12804       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12805       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12806 }
12807 
12808 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12809 /// precedence.
12810 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12811                                     SourceLocation OpLoc, Expr *LHSExpr,
12812                                     Expr *RHSExpr){
12813   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12814   if (BinaryOperator::isBitwiseOp(Opc))
12815     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12816 
12817   // Diagnose "arg1 & arg2 | arg3"
12818   if ((Opc == BO_Or || Opc == BO_Xor) &&
12819       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12820     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12821     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12822   }
12823 
12824   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12825   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12826   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12827     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12828     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12829   }
12830 
12831   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12832       || Opc == BO_Shr) {
12833     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12834     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12835     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12836   }
12837 
12838   // Warn on overloaded shift operators and comparisons, such as:
12839   // cout << 5 == 4;
12840   if (BinaryOperator::isComparisonOp(Opc))
12841     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12842 }
12843 
12844 // Binary Operators.  'Tok' is the token for the operator.
12845 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12846                             tok::TokenKind Kind,
12847                             Expr *LHSExpr, Expr *RHSExpr) {
12848   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12849   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12850   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12851 
12852   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12853   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12854 
12855   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12856 }
12857 
12858 /// Build an overloaded binary operator expression in the given scope.
12859 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12860                                        BinaryOperatorKind Opc,
12861                                        Expr *LHS, Expr *RHS) {
12862   switch (Opc) {
12863   case BO_Assign:
12864   case BO_DivAssign:
12865   case BO_RemAssign:
12866   case BO_SubAssign:
12867   case BO_AndAssign:
12868   case BO_OrAssign:
12869   case BO_XorAssign:
12870     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12871     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12872     break;
12873   default:
12874     break;
12875   }
12876 
12877   // Find all of the overloaded operators visible from this
12878   // point. We perform both an operator-name lookup from the local
12879   // scope and an argument-dependent lookup based on the types of
12880   // the arguments.
12881   UnresolvedSet<16> Functions;
12882   OverloadedOperatorKind OverOp
12883     = BinaryOperator::getOverloadedOperator(Opc);
12884   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12885     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12886                                    RHS->getType(), Functions);
12887 
12888   // Build the (potentially-overloaded, potentially-dependent)
12889   // binary operation.
12890   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12891 }
12892 
12893 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12894                             BinaryOperatorKind Opc,
12895                             Expr *LHSExpr, Expr *RHSExpr) {
12896   ExprResult LHS, RHS;
12897   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12898   if (!LHS.isUsable() || !RHS.isUsable())
12899     return ExprError();
12900   LHSExpr = LHS.get();
12901   RHSExpr = RHS.get();
12902 
12903   // We want to end up calling one of checkPseudoObjectAssignment
12904   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12905   // both expressions are overloadable or either is type-dependent),
12906   // or CreateBuiltinBinOp (in any other case).  We also want to get
12907   // any placeholder types out of the way.
12908 
12909   // Handle pseudo-objects in the LHS.
12910   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12911     // Assignments with a pseudo-object l-value need special analysis.
12912     if (pty->getKind() == BuiltinType::PseudoObject &&
12913         BinaryOperator::isAssignmentOp(Opc))
12914       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12915 
12916     // Don't resolve overloads if the other type is overloadable.
12917     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12918       // We can't actually test that if we still have a placeholder,
12919       // though.  Fortunately, none of the exceptions we see in that
12920       // code below are valid when the LHS is an overload set.  Note
12921       // that an overload set can be dependently-typed, but it never
12922       // instantiates to having an overloadable type.
12923       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12924       if (resolvedRHS.isInvalid()) return ExprError();
12925       RHSExpr = resolvedRHS.get();
12926 
12927       if (RHSExpr->isTypeDependent() ||
12928           RHSExpr->getType()->isOverloadableType())
12929         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12930     }
12931 
12932     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12933     // template, diagnose the missing 'template' keyword instead of diagnosing
12934     // an invalid use of a bound member function.
12935     //
12936     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12937     // to C++1z [over.over]/1.4, but we already checked for that case above.
12938     if (Opc == BO_LT && inTemplateInstantiation() &&
12939         (pty->getKind() == BuiltinType::BoundMember ||
12940          pty->getKind() == BuiltinType::Overload)) {
12941       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12942       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12943           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12944             return isa<FunctionTemplateDecl>(ND);
12945           })) {
12946         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12947                                 : OE->getNameLoc(),
12948              diag::err_template_kw_missing)
12949           << OE->getName().getAsString() << "";
12950         return ExprError();
12951       }
12952     }
12953 
12954     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12955     if (LHS.isInvalid()) return ExprError();
12956     LHSExpr = LHS.get();
12957   }
12958 
12959   // Handle pseudo-objects in the RHS.
12960   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12961     // An overload in the RHS can potentially be resolved by the type
12962     // being assigned to.
12963     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12964       if (getLangOpts().CPlusPlus &&
12965           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12966            LHSExpr->getType()->isOverloadableType()))
12967         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12968 
12969       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12970     }
12971 
12972     // Don't resolve overloads if the other type is overloadable.
12973     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12974         LHSExpr->getType()->isOverloadableType())
12975       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12976 
12977     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12978     if (!resolvedRHS.isUsable()) return ExprError();
12979     RHSExpr = resolvedRHS.get();
12980   }
12981 
12982   if (getLangOpts().CPlusPlus) {
12983     // If either expression is type-dependent, always build an
12984     // overloaded op.
12985     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12986       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12987 
12988     // Otherwise, build an overloaded op if either expression has an
12989     // overloadable type.
12990     if (LHSExpr->getType()->isOverloadableType() ||
12991         RHSExpr->getType()->isOverloadableType())
12992       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12993   }
12994 
12995   // Build a built-in binary operation.
12996   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12997 }
12998 
12999 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13000   if (T.isNull() || T->isDependentType())
13001     return false;
13002 
13003   if (!T->isPromotableIntegerType())
13004     return true;
13005 
13006   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13007 }
13008 
13009 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13010                                       UnaryOperatorKind Opc,
13011                                       Expr *InputExpr) {
13012   ExprResult Input = InputExpr;
13013   ExprValueKind VK = VK_RValue;
13014   ExprObjectKind OK = OK_Ordinary;
13015   QualType resultType;
13016   bool CanOverflow = false;
13017 
13018   bool ConvertHalfVec = false;
13019   if (getLangOpts().OpenCL) {
13020     QualType Ty = InputExpr->getType();
13021     // The only legal unary operation for atomics is '&'.
13022     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13023     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13024     // only with a builtin functions and therefore should be disallowed here.
13025         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13026         || Ty->isBlockPointerType())) {
13027       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13028                        << InputExpr->getType()
13029                        << Input.get()->getSourceRange());
13030     }
13031   }
13032   // Diagnose operations on the unsupported types for OpenMP device compilation.
13033   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13034     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13035         UnaryOperator::isArithmeticOp(Opc))
13036       checkOpenMPDeviceExpr(InputExpr);
13037   }
13038 
13039   switch (Opc) {
13040   case UO_PreInc:
13041   case UO_PreDec:
13042   case UO_PostInc:
13043   case UO_PostDec:
13044     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13045                                                 OpLoc,
13046                                                 Opc == UO_PreInc ||
13047                                                 Opc == UO_PostInc,
13048                                                 Opc == UO_PreInc ||
13049                                                 Opc == UO_PreDec);
13050     CanOverflow = isOverflowingIntegerType(Context, resultType);
13051     break;
13052   case UO_AddrOf:
13053     resultType = CheckAddressOfOperand(Input, OpLoc);
13054     CheckAddressOfNoDeref(InputExpr);
13055     RecordModifiableNonNullParam(*this, InputExpr);
13056     break;
13057   case UO_Deref: {
13058     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13059     if (Input.isInvalid()) return ExprError();
13060     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13061     break;
13062   }
13063   case UO_Plus:
13064   case UO_Minus:
13065     CanOverflow = Opc == UO_Minus &&
13066                   isOverflowingIntegerType(Context, Input.get()->getType());
13067     Input = UsualUnaryConversions(Input.get());
13068     if (Input.isInvalid()) return ExprError();
13069     // Unary plus and minus require promoting an operand of half vector to a
13070     // float vector and truncating the result back to a half vector. For now, we
13071     // do this only when HalfArgsAndReturns is set (that is, when the target is
13072     // arm or arm64).
13073     ConvertHalfVec =
13074         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13075 
13076     // If the operand is a half vector, promote it to a float vector.
13077     if (ConvertHalfVec)
13078       Input = convertVector(Input.get(), Context.FloatTy, *this);
13079     resultType = Input.get()->getType();
13080     if (resultType->isDependentType())
13081       break;
13082     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13083       break;
13084     else if (resultType->isVectorType() &&
13085              // The z vector extensions don't allow + or - with bool vectors.
13086              (!Context.getLangOpts().ZVector ||
13087               resultType->getAs<VectorType>()->getVectorKind() !=
13088               VectorType::AltiVecBool))
13089       break;
13090     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13091              Opc == UO_Plus &&
13092              resultType->isPointerType())
13093       break;
13094 
13095     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13096       << resultType << Input.get()->getSourceRange());
13097 
13098   case UO_Not: // bitwise complement
13099     Input = UsualUnaryConversions(Input.get());
13100     if (Input.isInvalid())
13101       return ExprError();
13102     resultType = Input.get()->getType();
13103 
13104     if (resultType->isDependentType())
13105       break;
13106     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13107     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13108       // C99 does not support '~' for complex conjugation.
13109       Diag(OpLoc, diag::ext_integer_complement_complex)
13110           << resultType << Input.get()->getSourceRange();
13111     else if (resultType->hasIntegerRepresentation())
13112       break;
13113     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13114       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13115       // on vector float types.
13116       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13117       if (!T->isIntegerType())
13118         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13119                           << resultType << Input.get()->getSourceRange());
13120     } else {
13121       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13122                        << resultType << Input.get()->getSourceRange());
13123     }
13124     break;
13125 
13126   case UO_LNot: // logical negation
13127     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13128     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13129     if (Input.isInvalid()) return ExprError();
13130     resultType = Input.get()->getType();
13131 
13132     // Though we still have to promote half FP to float...
13133     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13134       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13135       resultType = Context.FloatTy;
13136     }
13137 
13138     if (resultType->isDependentType())
13139       break;
13140     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13141       // C99 6.5.3.3p1: ok, fallthrough;
13142       if (Context.getLangOpts().CPlusPlus) {
13143         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13144         // operand contextually converted to bool.
13145         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13146                                   ScalarTypeToBooleanCastKind(resultType));
13147       } else if (Context.getLangOpts().OpenCL &&
13148                  Context.getLangOpts().OpenCLVersion < 120) {
13149         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13150         // operate on scalar float types.
13151         if (!resultType->isIntegerType() && !resultType->isPointerType())
13152           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13153                            << resultType << Input.get()->getSourceRange());
13154       }
13155     } else if (resultType->isExtVectorType()) {
13156       if (Context.getLangOpts().OpenCL &&
13157           Context.getLangOpts().OpenCLVersion < 120) {
13158         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13159         // operate on vector float types.
13160         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13161         if (!T->isIntegerType())
13162           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13163                            << resultType << Input.get()->getSourceRange());
13164       }
13165       // Vector logical not returns the signed variant of the operand type.
13166       resultType = GetSignedVectorType(resultType);
13167       break;
13168     } else {
13169       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13170       //        type in C++. We should allow that here too.
13171       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13172         << resultType << Input.get()->getSourceRange());
13173     }
13174 
13175     // LNot always has type int. C99 6.5.3.3p5.
13176     // In C++, it's bool. C++ 5.3.1p8
13177     resultType = Context.getLogicalOperationType();
13178     break;
13179   case UO_Real:
13180   case UO_Imag:
13181     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13182     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13183     // complex l-values to ordinary l-values and all other values to r-values.
13184     if (Input.isInvalid()) return ExprError();
13185     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13186       if (Input.get()->getValueKind() != VK_RValue &&
13187           Input.get()->getObjectKind() == OK_Ordinary)
13188         VK = Input.get()->getValueKind();
13189     } else if (!getLangOpts().CPlusPlus) {
13190       // In C, a volatile scalar is read by __imag. In C++, it is not.
13191       Input = DefaultLvalueConversion(Input.get());
13192     }
13193     break;
13194   case UO_Extension:
13195     resultType = Input.get()->getType();
13196     VK = Input.get()->getValueKind();
13197     OK = Input.get()->getObjectKind();
13198     break;
13199   case UO_Coawait:
13200     // It's unnecessary to represent the pass-through operator co_await in the
13201     // AST; just return the input expression instead.
13202     assert(!Input.get()->getType()->isDependentType() &&
13203                    "the co_await expression must be non-dependant before "
13204                    "building operator co_await");
13205     return Input;
13206   }
13207   if (resultType.isNull() || Input.isInvalid())
13208     return ExprError();
13209 
13210   // Check for array bounds violations in the operand of the UnaryOperator,
13211   // except for the '*' and '&' operators that have to be handled specially
13212   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13213   // that are explicitly defined as valid by the standard).
13214   if (Opc != UO_AddrOf && Opc != UO_Deref)
13215     CheckArrayAccess(Input.get());
13216 
13217   auto *UO = new (Context)
13218       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13219 
13220   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13221       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13222     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13223 
13224   // Convert the result back to a half vector.
13225   if (ConvertHalfVec)
13226     return convertVector(UO, Context.HalfTy, *this);
13227   return UO;
13228 }
13229 
13230 /// Determine whether the given expression is a qualified member
13231 /// access expression, of a form that could be turned into a pointer to member
13232 /// with the address-of operator.
13233 bool Sema::isQualifiedMemberAccess(Expr *E) {
13234   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13235     if (!DRE->getQualifier())
13236       return false;
13237 
13238     ValueDecl *VD = DRE->getDecl();
13239     if (!VD->isCXXClassMember())
13240       return false;
13241 
13242     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13243       return true;
13244     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13245       return Method->isInstance();
13246 
13247     return false;
13248   }
13249 
13250   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13251     if (!ULE->getQualifier())
13252       return false;
13253 
13254     for (NamedDecl *D : ULE->decls()) {
13255       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13256         if (Method->isInstance())
13257           return true;
13258       } else {
13259         // Overload set does not contain methods.
13260         break;
13261       }
13262     }
13263 
13264     return false;
13265   }
13266 
13267   return false;
13268 }
13269 
13270 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13271                               UnaryOperatorKind Opc, Expr *Input) {
13272   // First things first: handle placeholders so that the
13273   // overloaded-operator check considers the right type.
13274   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13275     // Increment and decrement of pseudo-object references.
13276     if (pty->getKind() == BuiltinType::PseudoObject &&
13277         UnaryOperator::isIncrementDecrementOp(Opc))
13278       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13279 
13280     // extension is always a builtin operator.
13281     if (Opc == UO_Extension)
13282       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13283 
13284     // & gets special logic for several kinds of placeholder.
13285     // The builtin code knows what to do.
13286     if (Opc == UO_AddrOf &&
13287         (pty->getKind() == BuiltinType::Overload ||
13288          pty->getKind() == BuiltinType::UnknownAny ||
13289          pty->getKind() == BuiltinType::BoundMember))
13290       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13291 
13292     // Anything else needs to be handled now.
13293     ExprResult Result = CheckPlaceholderExpr(Input);
13294     if (Result.isInvalid()) return ExprError();
13295     Input = Result.get();
13296   }
13297 
13298   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13299       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13300       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13301     // Find all of the overloaded operators visible from this
13302     // point. We perform both an operator-name lookup from the local
13303     // scope and an argument-dependent lookup based on the types of
13304     // the arguments.
13305     UnresolvedSet<16> Functions;
13306     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13307     if (S && OverOp != OO_None)
13308       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13309                                    Functions);
13310 
13311     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13312   }
13313 
13314   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13315 }
13316 
13317 // Unary Operators.  'Tok' is the token for the operator.
13318 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13319                               tok::TokenKind Op, Expr *Input) {
13320   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13321 }
13322 
13323 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13324 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13325                                 LabelDecl *TheDecl) {
13326   TheDecl->markUsed(Context);
13327   // Create the AST node.  The address of a label always has type 'void*'.
13328   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13329                                      Context.getPointerType(Context.VoidTy));
13330 }
13331 
13332 void Sema::ActOnStartStmtExpr() {
13333   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13334 }
13335 
13336 void Sema::ActOnStmtExprError() {
13337   // Note that function is also called by TreeTransform when leaving a
13338   // StmtExpr scope without rebuilding anything.
13339 
13340   DiscardCleanupsInEvaluationContext();
13341   PopExpressionEvaluationContext();
13342 }
13343 
13344 ExprResult
13345 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13346                     SourceLocation RPLoc) { // "({..})"
13347   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13348   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13349 
13350   if (hasAnyUnrecoverableErrorsInThisFunction())
13351     DiscardCleanupsInEvaluationContext();
13352   assert(!Cleanup.exprNeedsCleanups() &&
13353          "cleanups within StmtExpr not correctly bound!");
13354   PopExpressionEvaluationContext();
13355 
13356   // FIXME: there are a variety of strange constraints to enforce here, for
13357   // example, it is not possible to goto into a stmt expression apparently.
13358   // More semantic analysis is needed.
13359 
13360   // If there are sub-stmts in the compound stmt, take the type of the last one
13361   // as the type of the stmtexpr.
13362   QualType Ty = Context.VoidTy;
13363   bool StmtExprMayBindToTemp = false;
13364   if (!Compound->body_empty()) {
13365     if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
13366       if (const Expr *Value = LastStmt->getExprStmt()) {
13367         StmtExprMayBindToTemp = true;
13368         Ty = Value->getType();
13369       }
13370     }
13371   }
13372 
13373   // FIXME: Check that expression type is complete/non-abstract; statement
13374   // expressions are not lvalues.
13375   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13376   if (StmtExprMayBindToTemp)
13377     return MaybeBindToTemporary(ResStmtExpr);
13378   return ResStmtExpr;
13379 }
13380 
13381 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13382   if (ER.isInvalid())
13383     return ExprError();
13384 
13385   // Do function/array conversion on the last expression, but not
13386   // lvalue-to-rvalue.  However, initialize an unqualified type.
13387   ER = DefaultFunctionArrayConversion(ER.get());
13388   if (ER.isInvalid())
13389     return ExprError();
13390   Expr *E = ER.get();
13391 
13392   if (E->isTypeDependent())
13393     return E;
13394 
13395   // In ARC, if the final expression ends in a consume, splice
13396   // the consume out and bind it later.  In the alternate case
13397   // (when dealing with a retainable type), the result
13398   // initialization will create a produce.  In both cases the
13399   // result will be +1, and we'll need to balance that out with
13400   // a bind.
13401   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13402   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13403     return Cast->getSubExpr();
13404 
13405   // FIXME: Provide a better location for the initialization.
13406   return PerformCopyInitialization(
13407       InitializedEntity::InitializeStmtExprResult(
13408           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13409       SourceLocation(), E);
13410 }
13411 
13412 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13413                                       TypeSourceInfo *TInfo,
13414                                       ArrayRef<OffsetOfComponent> Components,
13415                                       SourceLocation RParenLoc) {
13416   QualType ArgTy = TInfo->getType();
13417   bool Dependent = ArgTy->isDependentType();
13418   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13419 
13420   // We must have at least one component that refers to the type, and the first
13421   // one is known to be a field designator.  Verify that the ArgTy represents
13422   // a struct/union/class.
13423   if (!Dependent && !ArgTy->isRecordType())
13424     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13425                        << ArgTy << TypeRange);
13426 
13427   // Type must be complete per C99 7.17p3 because a declaring a variable
13428   // with an incomplete type would be ill-formed.
13429   if (!Dependent
13430       && RequireCompleteType(BuiltinLoc, ArgTy,
13431                              diag::err_offsetof_incomplete_type, TypeRange))
13432     return ExprError();
13433 
13434   bool DidWarnAboutNonPOD = false;
13435   QualType CurrentType = ArgTy;
13436   SmallVector<OffsetOfNode, 4> Comps;
13437   SmallVector<Expr*, 4> Exprs;
13438   for (const OffsetOfComponent &OC : Components) {
13439     if (OC.isBrackets) {
13440       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13441       if (!CurrentType->isDependentType()) {
13442         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13443         if(!AT)
13444           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13445                            << CurrentType);
13446         CurrentType = AT->getElementType();
13447       } else
13448         CurrentType = Context.DependentTy;
13449 
13450       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13451       if (IdxRval.isInvalid())
13452         return ExprError();
13453       Expr *Idx = IdxRval.get();
13454 
13455       // The expression must be an integral expression.
13456       // FIXME: An integral constant expression?
13457       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13458           !Idx->getType()->isIntegerType())
13459         return ExprError(
13460             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13461             << Idx->getSourceRange());
13462 
13463       // Record this array index.
13464       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13465       Exprs.push_back(Idx);
13466       continue;
13467     }
13468 
13469     // Offset of a field.
13470     if (CurrentType->isDependentType()) {
13471       // We have the offset of a field, but we can't look into the dependent
13472       // type. Just record the identifier of the field.
13473       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13474       CurrentType = Context.DependentTy;
13475       continue;
13476     }
13477 
13478     // We need to have a complete type to look into.
13479     if (RequireCompleteType(OC.LocStart, CurrentType,
13480                             diag::err_offsetof_incomplete_type))
13481       return ExprError();
13482 
13483     // Look for the designated field.
13484     const RecordType *RC = CurrentType->getAs<RecordType>();
13485     if (!RC)
13486       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13487                        << CurrentType);
13488     RecordDecl *RD = RC->getDecl();
13489 
13490     // C++ [lib.support.types]p5:
13491     //   The macro offsetof accepts a restricted set of type arguments in this
13492     //   International Standard. type shall be a POD structure or a POD union
13493     //   (clause 9).
13494     // C++11 [support.types]p4:
13495     //   If type is not a standard-layout class (Clause 9), the results are
13496     //   undefined.
13497     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13498       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13499       unsigned DiagID =
13500         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13501                             : diag::ext_offsetof_non_pod_type;
13502 
13503       if (!IsSafe && !DidWarnAboutNonPOD &&
13504           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13505                               PDiag(DiagID)
13506                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13507                               << CurrentType))
13508         DidWarnAboutNonPOD = true;
13509     }
13510 
13511     // Look for the field.
13512     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13513     LookupQualifiedName(R, RD);
13514     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13515     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13516     if (!MemberDecl) {
13517       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13518         MemberDecl = IndirectMemberDecl->getAnonField();
13519     }
13520 
13521     if (!MemberDecl)
13522       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13523                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13524                                                               OC.LocEnd));
13525 
13526     // C99 7.17p3:
13527     //   (If the specified member is a bit-field, the behavior is undefined.)
13528     //
13529     // We diagnose this as an error.
13530     if (MemberDecl->isBitField()) {
13531       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13532         << MemberDecl->getDeclName()
13533         << SourceRange(BuiltinLoc, RParenLoc);
13534       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13535       return ExprError();
13536     }
13537 
13538     RecordDecl *Parent = MemberDecl->getParent();
13539     if (IndirectMemberDecl)
13540       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13541 
13542     // If the member was found in a base class, introduce OffsetOfNodes for
13543     // the base class indirections.
13544     CXXBasePaths Paths;
13545     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13546                       Paths)) {
13547       if (Paths.getDetectedVirtual()) {
13548         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13549           << MemberDecl->getDeclName()
13550           << SourceRange(BuiltinLoc, RParenLoc);
13551         return ExprError();
13552       }
13553 
13554       CXXBasePath &Path = Paths.front();
13555       for (const CXXBasePathElement &B : Path)
13556         Comps.push_back(OffsetOfNode(B.Base));
13557     }
13558 
13559     if (IndirectMemberDecl) {
13560       for (auto *FI : IndirectMemberDecl->chain()) {
13561         assert(isa<FieldDecl>(FI));
13562         Comps.push_back(OffsetOfNode(OC.LocStart,
13563                                      cast<FieldDecl>(FI), OC.LocEnd));
13564       }
13565     } else
13566       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13567 
13568     CurrentType = MemberDecl->getType().getNonReferenceType();
13569   }
13570 
13571   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13572                               Comps, Exprs, RParenLoc);
13573 }
13574 
13575 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13576                                       SourceLocation BuiltinLoc,
13577                                       SourceLocation TypeLoc,
13578                                       ParsedType ParsedArgTy,
13579                                       ArrayRef<OffsetOfComponent> Components,
13580                                       SourceLocation RParenLoc) {
13581 
13582   TypeSourceInfo *ArgTInfo;
13583   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13584   if (ArgTy.isNull())
13585     return ExprError();
13586 
13587   if (!ArgTInfo)
13588     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13589 
13590   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13591 }
13592 
13593 
13594 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13595                                  Expr *CondExpr,
13596                                  Expr *LHSExpr, Expr *RHSExpr,
13597                                  SourceLocation RPLoc) {
13598   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13599 
13600   ExprValueKind VK = VK_RValue;
13601   ExprObjectKind OK = OK_Ordinary;
13602   QualType resType;
13603   bool ValueDependent = false;
13604   bool CondIsTrue = false;
13605   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13606     resType = Context.DependentTy;
13607     ValueDependent = true;
13608   } else {
13609     // The conditional expression is required to be a constant expression.
13610     llvm::APSInt condEval(32);
13611     ExprResult CondICE
13612       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13613           diag::err_typecheck_choose_expr_requires_constant, false);
13614     if (CondICE.isInvalid())
13615       return ExprError();
13616     CondExpr = CondICE.get();
13617     CondIsTrue = condEval.getZExtValue();
13618 
13619     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13620     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13621 
13622     resType = ActiveExpr->getType();
13623     ValueDependent = ActiveExpr->isValueDependent();
13624     VK = ActiveExpr->getValueKind();
13625     OK = ActiveExpr->getObjectKind();
13626   }
13627 
13628   return new (Context)
13629       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13630                  CondIsTrue, resType->isDependentType(), ValueDependent);
13631 }
13632 
13633 //===----------------------------------------------------------------------===//
13634 // Clang Extensions.
13635 //===----------------------------------------------------------------------===//
13636 
13637 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13638 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13639   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13640 
13641   if (LangOpts.CPlusPlus) {
13642     Decl *ManglingContextDecl;
13643     if (MangleNumberingContext *MCtx =
13644             getCurrentMangleNumberContext(Block->getDeclContext(),
13645                                           ManglingContextDecl)) {
13646       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13647       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13648     }
13649   }
13650 
13651   PushBlockScope(CurScope, Block);
13652   CurContext->addDecl(Block);
13653   if (CurScope)
13654     PushDeclContext(CurScope, Block);
13655   else
13656     CurContext = Block;
13657 
13658   getCurBlock()->HasImplicitReturnType = true;
13659 
13660   // Enter a new evaluation context to insulate the block from any
13661   // cleanups from the enclosing full-expression.
13662   PushExpressionEvaluationContext(
13663       ExpressionEvaluationContext::PotentiallyEvaluated);
13664 }
13665 
13666 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13667                                Scope *CurScope) {
13668   assert(ParamInfo.getIdentifier() == nullptr &&
13669          "block-id should have no identifier!");
13670   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13671   BlockScopeInfo *CurBlock = getCurBlock();
13672 
13673   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13674   QualType T = Sig->getType();
13675 
13676   // FIXME: We should allow unexpanded parameter packs here, but that would,
13677   // in turn, make the block expression contain unexpanded parameter packs.
13678   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13679     // Drop the parameters.
13680     FunctionProtoType::ExtProtoInfo EPI;
13681     EPI.HasTrailingReturn = false;
13682     EPI.TypeQuals.addConst();
13683     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13684     Sig = Context.getTrivialTypeSourceInfo(T);
13685   }
13686 
13687   // GetTypeForDeclarator always produces a function type for a block
13688   // literal signature.  Furthermore, it is always a FunctionProtoType
13689   // unless the function was written with a typedef.
13690   assert(T->isFunctionType() &&
13691          "GetTypeForDeclarator made a non-function block signature");
13692 
13693   // Look for an explicit signature in that function type.
13694   FunctionProtoTypeLoc ExplicitSignature;
13695 
13696   if ((ExplicitSignature =
13697            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13698 
13699     // Check whether that explicit signature was synthesized by
13700     // GetTypeForDeclarator.  If so, don't save that as part of the
13701     // written signature.
13702     if (ExplicitSignature.getLocalRangeBegin() ==
13703         ExplicitSignature.getLocalRangeEnd()) {
13704       // This would be much cheaper if we stored TypeLocs instead of
13705       // TypeSourceInfos.
13706       TypeLoc Result = ExplicitSignature.getReturnLoc();
13707       unsigned Size = Result.getFullDataSize();
13708       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13709       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13710 
13711       ExplicitSignature = FunctionProtoTypeLoc();
13712     }
13713   }
13714 
13715   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13716   CurBlock->FunctionType = T;
13717 
13718   const FunctionType *Fn = T->getAs<FunctionType>();
13719   QualType RetTy = Fn->getReturnType();
13720   bool isVariadic =
13721     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13722 
13723   CurBlock->TheDecl->setIsVariadic(isVariadic);
13724 
13725   // Context.DependentTy is used as a placeholder for a missing block
13726   // return type.  TODO:  what should we do with declarators like:
13727   //   ^ * { ... }
13728   // If the answer is "apply template argument deduction"....
13729   if (RetTy != Context.DependentTy) {
13730     CurBlock->ReturnType = RetTy;
13731     CurBlock->TheDecl->setBlockMissingReturnType(false);
13732     CurBlock->HasImplicitReturnType = false;
13733   }
13734 
13735   // Push block parameters from the declarator if we had them.
13736   SmallVector<ParmVarDecl*, 8> Params;
13737   if (ExplicitSignature) {
13738     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13739       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13740       if (Param->getIdentifier() == nullptr &&
13741           !Param->isImplicit() &&
13742           !Param->isInvalidDecl() &&
13743           !getLangOpts().CPlusPlus)
13744         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13745       Params.push_back(Param);
13746     }
13747 
13748   // Fake up parameter variables if we have a typedef, like
13749   //   ^ fntype { ... }
13750   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13751     for (const auto &I : Fn->param_types()) {
13752       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13753           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13754       Params.push_back(Param);
13755     }
13756   }
13757 
13758   // Set the parameters on the block decl.
13759   if (!Params.empty()) {
13760     CurBlock->TheDecl->setParams(Params);
13761     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13762                              /*CheckParameterNames=*/false);
13763   }
13764 
13765   // Finally we can process decl attributes.
13766   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13767 
13768   // Put the parameter variables in scope.
13769   for (auto AI : CurBlock->TheDecl->parameters()) {
13770     AI->setOwningFunction(CurBlock->TheDecl);
13771 
13772     // If this has an identifier, add it to the scope stack.
13773     if (AI->getIdentifier()) {
13774       CheckShadow(CurBlock->TheScope, AI);
13775 
13776       PushOnScopeChains(AI, CurBlock->TheScope);
13777     }
13778   }
13779 }
13780 
13781 /// ActOnBlockError - If there is an error parsing a block, this callback
13782 /// is invoked to pop the information about the block from the action impl.
13783 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13784   // Leave the expression-evaluation context.
13785   DiscardCleanupsInEvaluationContext();
13786   PopExpressionEvaluationContext();
13787 
13788   // Pop off CurBlock, handle nested blocks.
13789   PopDeclContext();
13790   PopFunctionScopeInfo();
13791 }
13792 
13793 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13794 /// literal was successfully completed.  ^(int x){...}
13795 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13796                                     Stmt *Body, Scope *CurScope) {
13797   // If blocks are disabled, emit an error.
13798   if (!LangOpts.Blocks)
13799     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13800 
13801   // Leave the expression-evaluation context.
13802   if (hasAnyUnrecoverableErrorsInThisFunction())
13803     DiscardCleanupsInEvaluationContext();
13804   assert(!Cleanup.exprNeedsCleanups() &&
13805          "cleanups within block not correctly bound!");
13806   PopExpressionEvaluationContext();
13807 
13808   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13809   BlockDecl *BD = BSI->TheDecl;
13810 
13811   if (BSI->HasImplicitReturnType)
13812     deduceClosureReturnType(*BSI);
13813 
13814   PopDeclContext();
13815 
13816   QualType RetTy = Context.VoidTy;
13817   if (!BSI->ReturnType.isNull())
13818     RetTy = BSI->ReturnType;
13819 
13820   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13821   QualType BlockTy;
13822 
13823   // Set the captured variables on the block.
13824   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13825   SmallVector<BlockDecl::Capture, 4> Captures;
13826   for (Capture &Cap : BSI->Captures) {
13827     if (Cap.isThisCapture())
13828       continue;
13829     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13830                               Cap.isNested(), Cap.getInitExpr());
13831     Captures.push_back(NewCap);
13832   }
13833   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13834 
13835   // If the user wrote a function type in some form, try to use that.
13836   if (!BSI->FunctionType.isNull()) {
13837     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13838 
13839     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13840     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13841 
13842     // Turn protoless block types into nullary block types.
13843     if (isa<FunctionNoProtoType>(FTy)) {
13844       FunctionProtoType::ExtProtoInfo EPI;
13845       EPI.ExtInfo = Ext;
13846       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13847 
13848     // Otherwise, if we don't need to change anything about the function type,
13849     // preserve its sugar structure.
13850     } else if (FTy->getReturnType() == RetTy &&
13851                (!NoReturn || FTy->getNoReturnAttr())) {
13852       BlockTy = BSI->FunctionType;
13853 
13854     // Otherwise, make the minimal modifications to the function type.
13855     } else {
13856       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13857       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13858       EPI.TypeQuals = Qualifiers();
13859       EPI.ExtInfo = Ext;
13860       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13861     }
13862 
13863   // If we don't have a function type, just build one from nothing.
13864   } else {
13865     FunctionProtoType::ExtProtoInfo EPI;
13866     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13867     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13868   }
13869 
13870   DiagnoseUnusedParameters(BD->parameters());
13871   BlockTy = Context.getBlockPointerType(BlockTy);
13872 
13873   // If needed, diagnose invalid gotos and switches in the block.
13874   if (getCurFunction()->NeedsScopeChecking() &&
13875       !PP.isCodeCompletionEnabled())
13876     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13877 
13878   BD->setBody(cast<CompoundStmt>(Body));
13879 
13880   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13881     DiagnoseUnguardedAvailabilityViolations(BD);
13882 
13883   // Try to apply the named return value optimization. We have to check again
13884   // if we can do this, though, because blocks keep return statements around
13885   // to deduce an implicit return type.
13886   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13887       !BD->isDependentContext())
13888     computeNRVO(Body, BSI);
13889 
13890   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13891   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13892   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13893 
13894   // If the block isn't obviously global, i.e. it captures anything at
13895   // all, then we need to do a few things in the surrounding context:
13896   if (Result->getBlockDecl()->hasCaptures()) {
13897     // First, this expression has a new cleanup object.
13898     ExprCleanupObjects.push_back(Result->getBlockDecl());
13899     Cleanup.setExprNeedsCleanups(true);
13900 
13901     // It also gets a branch-protected scope if any of the captured
13902     // variables needs destruction.
13903     for (const auto &CI : Result->getBlockDecl()->captures()) {
13904       const VarDecl *var = CI.getVariable();
13905       if (var->getType().isDestructedType() != QualType::DK_none) {
13906         setFunctionHasBranchProtectedScope();
13907         break;
13908       }
13909     }
13910   }
13911 
13912   if (getCurFunction())
13913     getCurFunction()->addBlock(BD);
13914 
13915   return Result;
13916 }
13917 
13918 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13919                             SourceLocation RPLoc) {
13920   TypeSourceInfo *TInfo;
13921   GetTypeFromParser(Ty, &TInfo);
13922   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13923 }
13924 
13925 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13926                                 Expr *E, TypeSourceInfo *TInfo,
13927                                 SourceLocation RPLoc) {
13928   Expr *OrigExpr = E;
13929   bool IsMS = false;
13930 
13931   // CUDA device code does not support varargs.
13932   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13933     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13934       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13935       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13936         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13937     }
13938   }
13939 
13940   // NVPTX does not support va_arg expression.
13941   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
13942       Context.getTargetInfo().getTriple().isNVPTX())
13943     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
13944 
13945   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13946   // as Microsoft ABI on an actual Microsoft platform, where
13947   // __builtin_ms_va_list and __builtin_va_list are the same.)
13948   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13949       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13950     QualType MSVaListType = Context.getBuiltinMSVaListType();
13951     if (Context.hasSameType(MSVaListType, E->getType())) {
13952       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13953         return ExprError();
13954       IsMS = true;
13955     }
13956   }
13957 
13958   // Get the va_list type
13959   QualType VaListType = Context.getBuiltinVaListType();
13960   if (!IsMS) {
13961     if (VaListType->isArrayType()) {
13962       // Deal with implicit array decay; for example, on x86-64,
13963       // va_list is an array, but it's supposed to decay to
13964       // a pointer for va_arg.
13965       VaListType = Context.getArrayDecayedType(VaListType);
13966       // Make sure the input expression also decays appropriately.
13967       ExprResult Result = UsualUnaryConversions(E);
13968       if (Result.isInvalid())
13969         return ExprError();
13970       E = Result.get();
13971     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13972       // If va_list is a record type and we are compiling in C++ mode,
13973       // check the argument using reference binding.
13974       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13975           Context, Context.getLValueReferenceType(VaListType), false);
13976       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13977       if (Init.isInvalid())
13978         return ExprError();
13979       E = Init.getAs<Expr>();
13980     } else {
13981       // Otherwise, the va_list argument must be an l-value because
13982       // it is modified by va_arg.
13983       if (!E->isTypeDependent() &&
13984           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13985         return ExprError();
13986     }
13987   }
13988 
13989   if (!IsMS && !E->isTypeDependent() &&
13990       !Context.hasSameType(VaListType, E->getType()))
13991     return ExprError(
13992         Diag(E->getBeginLoc(),
13993              diag::err_first_argument_to_va_arg_not_of_type_va_list)
13994         << OrigExpr->getType() << E->getSourceRange());
13995 
13996   if (!TInfo->getType()->isDependentType()) {
13997     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13998                             diag::err_second_parameter_to_va_arg_incomplete,
13999                             TInfo->getTypeLoc()))
14000       return ExprError();
14001 
14002     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14003                                TInfo->getType(),
14004                                diag::err_second_parameter_to_va_arg_abstract,
14005                                TInfo->getTypeLoc()))
14006       return ExprError();
14007 
14008     if (!TInfo->getType().isPODType(Context)) {
14009       Diag(TInfo->getTypeLoc().getBeginLoc(),
14010            TInfo->getType()->isObjCLifetimeType()
14011              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14012              : diag::warn_second_parameter_to_va_arg_not_pod)
14013         << TInfo->getType()
14014         << TInfo->getTypeLoc().getSourceRange();
14015     }
14016 
14017     // Check for va_arg where arguments of the given type will be promoted
14018     // (i.e. this va_arg is guaranteed to have undefined behavior).
14019     QualType PromoteType;
14020     if (TInfo->getType()->isPromotableIntegerType()) {
14021       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14022       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14023         PromoteType = QualType();
14024     }
14025     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14026       PromoteType = Context.DoubleTy;
14027     if (!PromoteType.isNull())
14028       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14029                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14030                           << TInfo->getType()
14031                           << PromoteType
14032                           << TInfo->getTypeLoc().getSourceRange());
14033   }
14034 
14035   QualType T = TInfo->getType().getNonLValueExprType(Context);
14036   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14037 }
14038 
14039 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14040   // The type of __null will be int or long, depending on the size of
14041   // pointers on the target.
14042   QualType Ty;
14043   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14044   if (pw == Context.getTargetInfo().getIntWidth())
14045     Ty = Context.IntTy;
14046   else if (pw == Context.getTargetInfo().getLongWidth())
14047     Ty = Context.LongTy;
14048   else if (pw == Context.getTargetInfo().getLongLongWidth())
14049     Ty = Context.LongLongTy;
14050   else {
14051     llvm_unreachable("I don't know size of pointer!");
14052   }
14053 
14054   return new (Context) GNUNullExpr(Ty, TokenLoc);
14055 }
14056 
14057 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14058                                               bool Diagnose) {
14059   if (!getLangOpts().ObjC)
14060     return false;
14061 
14062   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14063   if (!PT)
14064     return false;
14065 
14066   if (!PT->isObjCIdType()) {
14067     // Check if the destination is the 'NSString' interface.
14068     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14069     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14070       return false;
14071   }
14072 
14073   // Ignore any parens, implicit casts (should only be
14074   // array-to-pointer decays), and not-so-opaque values.  The last is
14075   // important for making this trigger for property assignments.
14076   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14077   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14078     if (OV->getSourceExpr())
14079       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14080 
14081   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14082   if (!SL || !SL->isAscii())
14083     return false;
14084   if (Diagnose) {
14085     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14086         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14087     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14088   }
14089   return true;
14090 }
14091 
14092 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14093                                               const Expr *SrcExpr) {
14094   if (!DstType->isFunctionPointerType() ||
14095       !SrcExpr->getType()->isFunctionType())
14096     return false;
14097 
14098   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14099   if (!DRE)
14100     return false;
14101 
14102   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14103   if (!FD)
14104     return false;
14105 
14106   return !S.checkAddressOfFunctionIsAvailable(FD,
14107                                               /*Complain=*/true,
14108                                               SrcExpr->getBeginLoc());
14109 }
14110 
14111 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14112                                     SourceLocation Loc,
14113                                     QualType DstType, QualType SrcType,
14114                                     Expr *SrcExpr, AssignmentAction Action,
14115                                     bool *Complained) {
14116   if (Complained)
14117     *Complained = false;
14118 
14119   // Decode the result (notice that AST's are still created for extensions).
14120   bool CheckInferredResultType = false;
14121   bool isInvalid = false;
14122   unsigned DiagKind = 0;
14123   FixItHint Hint;
14124   ConversionFixItGenerator ConvHints;
14125   bool MayHaveConvFixit = false;
14126   bool MayHaveFunctionDiff = false;
14127   const ObjCInterfaceDecl *IFace = nullptr;
14128   const ObjCProtocolDecl *PDecl = nullptr;
14129 
14130   switch (ConvTy) {
14131   case Compatible:
14132       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14133       return false;
14134 
14135   case PointerToInt:
14136     DiagKind = diag::ext_typecheck_convert_pointer_int;
14137     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14138     MayHaveConvFixit = true;
14139     break;
14140   case IntToPointer:
14141     DiagKind = diag::ext_typecheck_convert_int_pointer;
14142     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14143     MayHaveConvFixit = true;
14144     break;
14145   case IncompatiblePointer:
14146     if (Action == AA_Passing_CFAudited)
14147       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14148     else if (SrcType->isFunctionPointerType() &&
14149              DstType->isFunctionPointerType())
14150       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14151     else
14152       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14153 
14154     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14155       SrcType->isObjCObjectPointerType();
14156     if (Hint.isNull() && !CheckInferredResultType) {
14157       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14158     }
14159     else if (CheckInferredResultType) {
14160       SrcType = SrcType.getUnqualifiedType();
14161       DstType = DstType.getUnqualifiedType();
14162     }
14163     MayHaveConvFixit = true;
14164     break;
14165   case IncompatiblePointerSign:
14166     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14167     break;
14168   case FunctionVoidPointer:
14169     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14170     break;
14171   case IncompatiblePointerDiscardsQualifiers: {
14172     // Perform array-to-pointer decay if necessary.
14173     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14174 
14175     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14176     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14177     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14178       DiagKind = diag::err_typecheck_incompatible_address_space;
14179       break;
14180 
14181     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14182       DiagKind = diag::err_typecheck_incompatible_ownership;
14183       break;
14184     }
14185 
14186     llvm_unreachable("unknown error case for discarding qualifiers!");
14187     // fallthrough
14188   }
14189   case CompatiblePointerDiscardsQualifiers:
14190     // If the qualifiers lost were because we were applying the
14191     // (deprecated) C++ conversion from a string literal to a char*
14192     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14193     // Ideally, this check would be performed in
14194     // checkPointerTypesForAssignment. However, that would require a
14195     // bit of refactoring (so that the second argument is an
14196     // expression, rather than a type), which should be done as part
14197     // of a larger effort to fix checkPointerTypesForAssignment for
14198     // C++ semantics.
14199     if (getLangOpts().CPlusPlus &&
14200         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14201       return false;
14202     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14203     break;
14204   case IncompatibleNestedPointerQualifiers:
14205     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14206     break;
14207   case IntToBlockPointer:
14208     DiagKind = diag::err_int_to_block_pointer;
14209     break;
14210   case IncompatibleBlockPointer:
14211     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14212     break;
14213   case IncompatibleObjCQualifiedId: {
14214     if (SrcType->isObjCQualifiedIdType()) {
14215       const ObjCObjectPointerType *srcOPT =
14216                 SrcType->getAs<ObjCObjectPointerType>();
14217       for (auto *srcProto : srcOPT->quals()) {
14218         PDecl = srcProto;
14219         break;
14220       }
14221       if (const ObjCInterfaceType *IFaceT =
14222             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14223         IFace = IFaceT->getDecl();
14224     }
14225     else if (DstType->isObjCQualifiedIdType()) {
14226       const ObjCObjectPointerType *dstOPT =
14227         DstType->getAs<ObjCObjectPointerType>();
14228       for (auto *dstProto : dstOPT->quals()) {
14229         PDecl = dstProto;
14230         break;
14231       }
14232       if (const ObjCInterfaceType *IFaceT =
14233             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14234         IFace = IFaceT->getDecl();
14235     }
14236     DiagKind = diag::warn_incompatible_qualified_id;
14237     break;
14238   }
14239   case IncompatibleVectors:
14240     DiagKind = diag::warn_incompatible_vectors;
14241     break;
14242   case IncompatibleObjCWeakRef:
14243     DiagKind = diag::err_arc_weak_unavailable_assign;
14244     break;
14245   case Incompatible:
14246     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14247       if (Complained)
14248         *Complained = true;
14249       return true;
14250     }
14251 
14252     DiagKind = diag::err_typecheck_convert_incompatible;
14253     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14254     MayHaveConvFixit = true;
14255     isInvalid = true;
14256     MayHaveFunctionDiff = true;
14257     break;
14258   }
14259 
14260   QualType FirstType, SecondType;
14261   switch (Action) {
14262   case AA_Assigning:
14263   case AA_Initializing:
14264     // The destination type comes first.
14265     FirstType = DstType;
14266     SecondType = SrcType;
14267     break;
14268 
14269   case AA_Returning:
14270   case AA_Passing:
14271   case AA_Passing_CFAudited:
14272   case AA_Converting:
14273   case AA_Sending:
14274   case AA_Casting:
14275     // The source type comes first.
14276     FirstType = SrcType;
14277     SecondType = DstType;
14278     break;
14279   }
14280 
14281   PartialDiagnostic FDiag = PDiag(DiagKind);
14282   if (Action == AA_Passing_CFAudited)
14283     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14284   else
14285     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14286 
14287   // If we can fix the conversion, suggest the FixIts.
14288   assert(ConvHints.isNull() || Hint.isNull());
14289   if (!ConvHints.isNull()) {
14290     for (FixItHint &H : ConvHints.Hints)
14291       FDiag << H;
14292   } else {
14293     FDiag << Hint;
14294   }
14295   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14296 
14297   if (MayHaveFunctionDiff)
14298     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14299 
14300   Diag(Loc, FDiag);
14301   if (DiagKind == diag::warn_incompatible_qualified_id &&
14302       PDecl && IFace && !IFace->hasDefinition())
14303       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14304         << IFace << PDecl;
14305 
14306   if (SecondType == Context.OverloadTy)
14307     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14308                               FirstType, /*TakingAddress=*/true);
14309 
14310   if (CheckInferredResultType)
14311     EmitRelatedResultTypeNote(SrcExpr);
14312 
14313   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14314     EmitRelatedResultTypeNoteForReturn(DstType);
14315 
14316   if (Complained)
14317     *Complained = true;
14318   return isInvalid;
14319 }
14320 
14321 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14322                                                  llvm::APSInt *Result) {
14323   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14324   public:
14325     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14326       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14327     }
14328   } Diagnoser;
14329 
14330   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14331 }
14332 
14333 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14334                                                  llvm::APSInt *Result,
14335                                                  unsigned DiagID,
14336                                                  bool AllowFold) {
14337   class IDDiagnoser : public VerifyICEDiagnoser {
14338     unsigned DiagID;
14339 
14340   public:
14341     IDDiagnoser(unsigned DiagID)
14342       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14343 
14344     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14345       S.Diag(Loc, DiagID) << SR;
14346     }
14347   } Diagnoser(DiagID);
14348 
14349   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14350 }
14351 
14352 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14353                                             SourceRange SR) {
14354   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14355 }
14356 
14357 ExprResult
14358 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14359                                       VerifyICEDiagnoser &Diagnoser,
14360                                       bool AllowFold) {
14361   SourceLocation DiagLoc = E->getBeginLoc();
14362 
14363   if (getLangOpts().CPlusPlus11) {
14364     // C++11 [expr.const]p5:
14365     //   If an expression of literal class type is used in a context where an
14366     //   integral constant expression is required, then that class type shall
14367     //   have a single non-explicit conversion function to an integral or
14368     //   unscoped enumeration type
14369     ExprResult Converted;
14370     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14371     public:
14372       CXX11ConvertDiagnoser(bool Silent)
14373           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14374                                 Silent, true) {}
14375 
14376       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14377                                            QualType T) override {
14378         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14379       }
14380 
14381       SemaDiagnosticBuilder diagnoseIncomplete(
14382           Sema &S, SourceLocation Loc, QualType T) override {
14383         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14384       }
14385 
14386       SemaDiagnosticBuilder diagnoseExplicitConv(
14387           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14388         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14389       }
14390 
14391       SemaDiagnosticBuilder noteExplicitConv(
14392           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14393         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14394                  << ConvTy->isEnumeralType() << ConvTy;
14395       }
14396 
14397       SemaDiagnosticBuilder diagnoseAmbiguous(
14398           Sema &S, SourceLocation Loc, QualType T) override {
14399         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14400       }
14401 
14402       SemaDiagnosticBuilder noteAmbiguous(
14403           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14404         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14405                  << ConvTy->isEnumeralType() << ConvTy;
14406       }
14407 
14408       SemaDiagnosticBuilder diagnoseConversion(
14409           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14410         llvm_unreachable("conversion functions are permitted");
14411       }
14412     } ConvertDiagnoser(Diagnoser.Suppress);
14413 
14414     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14415                                                     ConvertDiagnoser);
14416     if (Converted.isInvalid())
14417       return Converted;
14418     E = Converted.get();
14419     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14420       return ExprError();
14421   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14422     // An ICE must be of integral or unscoped enumeration type.
14423     if (!Diagnoser.Suppress)
14424       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14425     return ExprError();
14426   }
14427 
14428   if (!isa<ConstantExpr>(E))
14429     E = ConstantExpr::Create(Context, E);
14430 
14431   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14432   // in the non-ICE case.
14433   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14434     if (Result)
14435       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14436     return E;
14437   }
14438 
14439   Expr::EvalResult EvalResult;
14440   SmallVector<PartialDiagnosticAt, 8> Notes;
14441   EvalResult.Diag = &Notes;
14442 
14443   // Try to evaluate the expression, and produce diagnostics explaining why it's
14444   // not a constant expression as a side-effect.
14445   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14446                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14447 
14448   // In C++11, we can rely on diagnostics being produced for any expression
14449   // which is not a constant expression. If no diagnostics were produced, then
14450   // this is a constant expression.
14451   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14452     if (Result)
14453       *Result = EvalResult.Val.getInt();
14454     return E;
14455   }
14456 
14457   // If our only note is the usual "invalid subexpression" note, just point
14458   // the caret at its location rather than producing an essentially
14459   // redundant note.
14460   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14461         diag::note_invalid_subexpr_in_const_expr) {
14462     DiagLoc = Notes[0].first;
14463     Notes.clear();
14464   }
14465 
14466   if (!Folded || !AllowFold) {
14467     if (!Diagnoser.Suppress) {
14468       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14469       for (const PartialDiagnosticAt &Note : Notes)
14470         Diag(Note.first, Note.second);
14471     }
14472 
14473     return ExprError();
14474   }
14475 
14476   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14477   for (const PartialDiagnosticAt &Note : Notes)
14478     Diag(Note.first, Note.second);
14479 
14480   if (Result)
14481     *Result = EvalResult.Val.getInt();
14482   return E;
14483 }
14484 
14485 namespace {
14486   // Handle the case where we conclude a expression which we speculatively
14487   // considered to be unevaluated is actually evaluated.
14488   class TransformToPE : public TreeTransform<TransformToPE> {
14489     typedef TreeTransform<TransformToPE> BaseTransform;
14490 
14491   public:
14492     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14493 
14494     // Make sure we redo semantic analysis
14495     bool AlwaysRebuild() { return true; }
14496 
14497     // We need to special-case DeclRefExprs referring to FieldDecls which
14498     // are not part of a member pointer formation; normal TreeTransforming
14499     // doesn't catch this case because of the way we represent them in the AST.
14500     // FIXME: This is a bit ugly; is it really the best way to handle this
14501     // case?
14502     //
14503     // Error on DeclRefExprs referring to FieldDecls.
14504     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14505       if (isa<FieldDecl>(E->getDecl()) &&
14506           !SemaRef.isUnevaluatedContext())
14507         return SemaRef.Diag(E->getLocation(),
14508                             diag::err_invalid_non_static_member_use)
14509             << E->getDecl() << E->getSourceRange();
14510 
14511       return BaseTransform::TransformDeclRefExpr(E);
14512     }
14513 
14514     // Exception: filter out member pointer formation
14515     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14516       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14517         return E;
14518 
14519       return BaseTransform::TransformUnaryOperator(E);
14520     }
14521 
14522     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14523       // Lambdas never need to be transformed.
14524       return E;
14525     }
14526   };
14527 }
14528 
14529 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14530   assert(isUnevaluatedContext() &&
14531          "Should only transform unevaluated expressions");
14532   ExprEvalContexts.back().Context =
14533       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14534   if (isUnevaluatedContext())
14535     return E;
14536   return TransformToPE(*this).TransformExpr(E);
14537 }
14538 
14539 void
14540 Sema::PushExpressionEvaluationContext(
14541     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14542     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14543   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14544                                 LambdaContextDecl, ExprContext);
14545   Cleanup.reset();
14546   if (!MaybeODRUseExprs.empty())
14547     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14548 }
14549 
14550 void
14551 Sema::PushExpressionEvaluationContext(
14552     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14553     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14554   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14555   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14556 }
14557 
14558 namespace {
14559 
14560 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14561   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14562   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14563     if (E->getOpcode() == UO_Deref)
14564       return CheckPossibleDeref(S, E->getSubExpr());
14565   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14566     return CheckPossibleDeref(S, E->getBase());
14567   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14568     return CheckPossibleDeref(S, E->getBase());
14569   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14570     QualType Inner;
14571     QualType Ty = E->getType();
14572     if (const auto *Ptr = Ty->getAs<PointerType>())
14573       Inner = Ptr->getPointeeType();
14574     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14575       Inner = Arr->getElementType();
14576     else
14577       return nullptr;
14578 
14579     if (Inner->hasAttr(attr::NoDeref))
14580       return E;
14581   }
14582   return nullptr;
14583 }
14584 
14585 } // namespace
14586 
14587 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14588   for (const Expr *E : Rec.PossibleDerefs) {
14589     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14590     if (DeclRef) {
14591       const ValueDecl *Decl = DeclRef->getDecl();
14592       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14593           << Decl->getName() << E->getSourceRange();
14594       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14595     } else {
14596       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14597           << E->getSourceRange();
14598     }
14599   }
14600   Rec.PossibleDerefs.clear();
14601 }
14602 
14603 void Sema::PopExpressionEvaluationContext() {
14604   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14605   unsigned NumTypos = Rec.NumTypos;
14606 
14607   if (!Rec.Lambdas.empty()) {
14608     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14609     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14610         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14611       unsigned D;
14612       if (Rec.isUnevaluated()) {
14613         // C++11 [expr.prim.lambda]p2:
14614         //   A lambda-expression shall not appear in an unevaluated operand
14615         //   (Clause 5).
14616         D = diag::err_lambda_unevaluated_operand;
14617       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14618         // C++1y [expr.const]p2:
14619         //   A conditional-expression e is a core constant expression unless the
14620         //   evaluation of e, following the rules of the abstract machine, would
14621         //   evaluate [...] a lambda-expression.
14622         D = diag::err_lambda_in_constant_expression;
14623       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14624         // C++17 [expr.prim.lamda]p2:
14625         // A lambda-expression shall not appear [...] in a template-argument.
14626         D = diag::err_lambda_in_invalid_context;
14627       } else
14628         llvm_unreachable("Couldn't infer lambda error message.");
14629 
14630       for (const auto *L : Rec.Lambdas)
14631         Diag(L->getBeginLoc(), D);
14632     } else {
14633       // Mark the capture expressions odr-used. This was deferred
14634       // during lambda expression creation.
14635       for (auto *Lambda : Rec.Lambdas) {
14636         for (auto *C : Lambda->capture_inits())
14637           MarkDeclarationsReferencedInExpr(C);
14638       }
14639     }
14640   }
14641 
14642   WarnOnPendingNoDerefs(Rec);
14643 
14644   // When are coming out of an unevaluated context, clear out any
14645   // temporaries that we may have created as part of the evaluation of
14646   // the expression in that context: they aren't relevant because they
14647   // will never be constructed.
14648   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14649     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14650                              ExprCleanupObjects.end());
14651     Cleanup = Rec.ParentCleanup;
14652     CleanupVarDeclMarking();
14653     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14654   // Otherwise, merge the contexts together.
14655   } else {
14656     Cleanup.mergeFrom(Rec.ParentCleanup);
14657     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14658                             Rec.SavedMaybeODRUseExprs.end());
14659   }
14660 
14661   // Pop the current expression evaluation context off the stack.
14662   ExprEvalContexts.pop_back();
14663 
14664   // The global expression evaluation context record is never popped.
14665   ExprEvalContexts.back().NumTypos += NumTypos;
14666 }
14667 
14668 void Sema::DiscardCleanupsInEvaluationContext() {
14669   ExprCleanupObjects.erase(
14670          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14671          ExprCleanupObjects.end());
14672   Cleanup.reset();
14673   MaybeODRUseExprs.clear();
14674 }
14675 
14676 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14677   ExprResult Result = CheckPlaceholderExpr(E);
14678   if (Result.isInvalid())
14679     return ExprError();
14680   E = Result.get();
14681   if (!E->getType()->isVariablyModifiedType())
14682     return E;
14683   return TransformToPotentiallyEvaluated(E);
14684 }
14685 
14686 /// Are we within a context in which some evaluation could be performed (be it
14687 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14688 /// captured by C++'s idea of an "unevaluated context".
14689 static bool isEvaluatableContext(Sema &SemaRef) {
14690   switch (SemaRef.ExprEvalContexts.back().Context) {
14691     case Sema::ExpressionEvaluationContext::Unevaluated:
14692     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14693       // Expressions in this context are never evaluated.
14694       return false;
14695 
14696     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14697     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14698     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14699     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14700       // Expressions in this context could be evaluated.
14701       return true;
14702 
14703     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14704       // Referenced declarations will only be used if the construct in the
14705       // containing expression is used, at which point we'll be given another
14706       // turn to mark them.
14707       return false;
14708   }
14709   llvm_unreachable("Invalid context");
14710 }
14711 
14712 /// Are we within a context in which references to resolved functions or to
14713 /// variables result in odr-use?
14714 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14715   // An expression in a template is not really an expression until it's been
14716   // instantiated, so it doesn't trigger odr-use.
14717   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14718     return false;
14719 
14720   switch (SemaRef.ExprEvalContexts.back().Context) {
14721     case Sema::ExpressionEvaluationContext::Unevaluated:
14722     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14723     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14724     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14725       return false;
14726 
14727     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14728     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14729       return true;
14730 
14731     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14732       return false;
14733   }
14734   llvm_unreachable("Invalid context");
14735 }
14736 
14737 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14738   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14739   return Func->isConstexpr() &&
14740          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14741 }
14742 
14743 /// Mark a function referenced, and check whether it is odr-used
14744 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14745 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14746                                   bool MightBeOdrUse) {
14747   assert(Func && "No function?");
14748 
14749   Func->setReferenced();
14750 
14751   // C++11 [basic.def.odr]p3:
14752   //   A function whose name appears as a potentially-evaluated expression is
14753   //   odr-used if it is the unique lookup result or the selected member of a
14754   //   set of overloaded functions [...].
14755   //
14756   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14757   // can just check that here.
14758   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14759 
14760   // Determine whether we require a function definition to exist, per
14761   // C++11 [temp.inst]p3:
14762   //   Unless a function template specialization has been explicitly
14763   //   instantiated or explicitly specialized, the function template
14764   //   specialization is implicitly instantiated when the specialization is
14765   //   referenced in a context that requires a function definition to exist.
14766   //
14767   // That is either when this is an odr-use, or when a usage of a constexpr
14768   // function occurs within an evaluatable context.
14769   bool NeedDefinition =
14770       OdrUse || (isEvaluatableContext(*this) &&
14771                  isImplicitlyDefinableConstexprFunction(Func));
14772 
14773   // C++14 [temp.expl.spec]p6:
14774   //   If a template [...] is explicitly specialized then that specialization
14775   //   shall be declared before the first use of that specialization that would
14776   //   cause an implicit instantiation to take place, in every translation unit
14777   //   in which such a use occurs
14778   if (NeedDefinition &&
14779       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14780        Func->getMemberSpecializationInfo()))
14781     checkSpecializationVisibility(Loc, Func);
14782 
14783   // C++14 [except.spec]p17:
14784   //   An exception-specification is considered to be needed when:
14785   //   - the function is odr-used or, if it appears in an unevaluated operand,
14786   //     would be odr-used if the expression were potentially-evaluated;
14787   //
14788   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14789   // function is a pure virtual function we're calling, and in that case the
14790   // function was selected by overload resolution and we need to resolve its
14791   // exception specification for a different reason.
14792   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14793   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14794     ResolveExceptionSpec(Loc, FPT);
14795 
14796   if (getLangOpts().CUDA)
14797     CheckCUDACall(Loc, Func);
14798 
14799   // If we don't need to mark the function as used, and we don't need to
14800   // try to provide a definition, there's nothing more to do.
14801   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14802       (!NeedDefinition || Func->getBody()))
14803     return;
14804 
14805   // Note that this declaration has been used.
14806   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14807     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14808     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14809       if (Constructor->isDefaultConstructor()) {
14810         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14811           return;
14812         DefineImplicitDefaultConstructor(Loc, Constructor);
14813       } else if (Constructor->isCopyConstructor()) {
14814         DefineImplicitCopyConstructor(Loc, Constructor);
14815       } else if (Constructor->isMoveConstructor()) {
14816         DefineImplicitMoveConstructor(Loc, Constructor);
14817       }
14818     } else if (Constructor->getInheritedConstructor()) {
14819       DefineInheritingConstructor(Loc, Constructor);
14820     }
14821   } else if (CXXDestructorDecl *Destructor =
14822                  dyn_cast<CXXDestructorDecl>(Func)) {
14823     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14824     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14825       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14826         return;
14827       DefineImplicitDestructor(Loc, Destructor);
14828     }
14829     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14830       MarkVTableUsed(Loc, Destructor->getParent());
14831   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14832     if (MethodDecl->isOverloadedOperator() &&
14833         MethodDecl->getOverloadedOperator() == OO_Equal) {
14834       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14835       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14836         if (MethodDecl->isCopyAssignmentOperator())
14837           DefineImplicitCopyAssignment(Loc, MethodDecl);
14838         else if (MethodDecl->isMoveAssignmentOperator())
14839           DefineImplicitMoveAssignment(Loc, MethodDecl);
14840       }
14841     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14842                MethodDecl->getParent()->isLambda()) {
14843       CXXConversionDecl *Conversion =
14844           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14845       if (Conversion->isLambdaToBlockPointerConversion())
14846         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14847       else
14848         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14849     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14850       MarkVTableUsed(Loc, MethodDecl->getParent());
14851   }
14852 
14853   // Recursive functions should be marked when used from another function.
14854   // FIXME: Is this really right?
14855   if (CurContext == Func) return;
14856 
14857   // Implicit instantiation of function templates and member functions of
14858   // class templates.
14859   if (Func->isImplicitlyInstantiable()) {
14860     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14861     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14862     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14863     if (FirstInstantiation) {
14864       PointOfInstantiation = Loc;
14865       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14866     } else if (TSK != TSK_ImplicitInstantiation) {
14867       // Use the point of use as the point of instantiation, instead of the
14868       // point of explicit instantiation (which we track as the actual point of
14869       // instantiation). This gives better backtraces in diagnostics.
14870       PointOfInstantiation = Loc;
14871     }
14872 
14873     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14874         Func->isConstexpr()) {
14875       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14876           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14877           CodeSynthesisContexts.size())
14878         PendingLocalImplicitInstantiations.push_back(
14879             std::make_pair(Func, PointOfInstantiation));
14880       else if (Func->isConstexpr())
14881         // Do not defer instantiations of constexpr functions, to avoid the
14882         // expression evaluator needing to call back into Sema if it sees a
14883         // call to such a function.
14884         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14885       else {
14886         Func->setInstantiationIsPending(true);
14887         PendingInstantiations.push_back(std::make_pair(Func,
14888                                                        PointOfInstantiation));
14889         // Notify the consumer that a function was implicitly instantiated.
14890         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14891       }
14892     }
14893   } else {
14894     // Walk redefinitions, as some of them may be instantiable.
14895     for (auto i : Func->redecls()) {
14896       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14897         MarkFunctionReferenced(Loc, i, OdrUse);
14898     }
14899   }
14900 
14901   if (!OdrUse) return;
14902 
14903   // Keep track of used but undefined functions.
14904   if (!Func->isDefined()) {
14905     if (mightHaveNonExternalLinkage(Func))
14906       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14907     else if (Func->getMostRecentDecl()->isInlined() &&
14908              !LangOpts.GNUInline &&
14909              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14910       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14911     else if (isExternalWithNoLinkageType(Func))
14912       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14913   }
14914 
14915   Func->markUsed(Context);
14916 
14917   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
14918     checkOpenMPDeviceFunction(Loc, Func);
14919 }
14920 
14921 static void
14922 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14923                                    ValueDecl *var, DeclContext *DC) {
14924   DeclContext *VarDC = var->getDeclContext();
14925 
14926   //  If the parameter still belongs to the translation unit, then
14927   //  we're actually just using one parameter in the declaration of
14928   //  the next.
14929   if (isa<ParmVarDecl>(var) &&
14930       isa<TranslationUnitDecl>(VarDC))
14931     return;
14932 
14933   // For C code, don't diagnose about capture if we're not actually in code
14934   // right now; it's impossible to write a non-constant expression outside of
14935   // function context, so we'll get other (more useful) diagnostics later.
14936   //
14937   // For C++, things get a bit more nasty... it would be nice to suppress this
14938   // diagnostic for certain cases like using a local variable in an array bound
14939   // for a member of a local class, but the correct predicate is not obvious.
14940   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14941     return;
14942 
14943   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14944   unsigned ContextKind = 3; // unknown
14945   if (isa<CXXMethodDecl>(VarDC) &&
14946       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14947     ContextKind = 2;
14948   } else if (isa<FunctionDecl>(VarDC)) {
14949     ContextKind = 0;
14950   } else if (isa<BlockDecl>(VarDC)) {
14951     ContextKind = 1;
14952   }
14953 
14954   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14955     << var << ValueKind << ContextKind << VarDC;
14956   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14957       << var;
14958 
14959   // FIXME: Add additional diagnostic info about class etc. which prevents
14960   // capture.
14961 }
14962 
14963 
14964 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14965                                       bool &SubCapturesAreNested,
14966                                       QualType &CaptureType,
14967                                       QualType &DeclRefType) {
14968    // Check whether we've already captured it.
14969   if (CSI->CaptureMap.count(Var)) {
14970     // If we found a capture, any subcaptures are nested.
14971     SubCapturesAreNested = true;
14972 
14973     // Retrieve the capture type for this variable.
14974     CaptureType = CSI->getCapture(Var).getCaptureType();
14975 
14976     // Compute the type of an expression that refers to this variable.
14977     DeclRefType = CaptureType.getNonReferenceType();
14978 
14979     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14980     // are mutable in the sense that user can change their value - they are
14981     // private instances of the captured declarations.
14982     const Capture &Cap = CSI->getCapture(Var);
14983     if (Cap.isCopyCapture() &&
14984         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14985         !(isa<CapturedRegionScopeInfo>(CSI) &&
14986           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14987       DeclRefType.addConst();
14988     return true;
14989   }
14990   return false;
14991 }
14992 
14993 // Only block literals, captured statements, and lambda expressions can
14994 // capture; other scopes don't work.
14995 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14996                                  SourceLocation Loc,
14997                                  const bool Diagnose, Sema &S) {
14998   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14999     return getLambdaAwareParentOfDeclContext(DC);
15000   else if (Var->hasLocalStorage()) {
15001     if (Diagnose)
15002        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15003   }
15004   return nullptr;
15005 }
15006 
15007 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15008 // certain types of variables (unnamed, variably modified types etc.)
15009 // so check for eligibility.
15010 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15011                                  SourceLocation Loc,
15012                                  const bool Diagnose, Sema &S) {
15013 
15014   bool IsBlock = isa<BlockScopeInfo>(CSI);
15015   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15016 
15017   // Lambdas are not allowed to capture unnamed variables
15018   // (e.g. anonymous unions).
15019   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15020   // assuming that's the intent.
15021   if (IsLambda && !Var->getDeclName()) {
15022     if (Diagnose) {
15023       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15024       S.Diag(Var->getLocation(), diag::note_declared_at);
15025     }
15026     return false;
15027   }
15028 
15029   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15030   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15031     if (Diagnose) {
15032       S.Diag(Loc, diag::err_ref_vm_type);
15033       S.Diag(Var->getLocation(), diag::note_previous_decl)
15034         << Var->getDeclName();
15035     }
15036     return false;
15037   }
15038   // Prohibit structs with flexible array members too.
15039   // We cannot capture what is in the tail end of the struct.
15040   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15041     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15042       if (Diagnose) {
15043         if (IsBlock)
15044           S.Diag(Loc, diag::err_ref_flexarray_type);
15045         else
15046           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15047             << Var->getDeclName();
15048         S.Diag(Var->getLocation(), diag::note_previous_decl)
15049           << Var->getDeclName();
15050       }
15051       return false;
15052     }
15053   }
15054   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15055   // Lambdas and captured statements are not allowed to capture __block
15056   // variables; they don't support the expected semantics.
15057   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15058     if (Diagnose) {
15059       S.Diag(Loc, diag::err_capture_block_variable)
15060         << Var->getDeclName() << !IsLambda;
15061       S.Diag(Var->getLocation(), diag::note_previous_decl)
15062         << Var->getDeclName();
15063     }
15064     return false;
15065   }
15066   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15067   if (S.getLangOpts().OpenCL && IsBlock &&
15068       Var->getType()->isBlockPointerType()) {
15069     if (Diagnose)
15070       S.Diag(Loc, diag::err_opencl_block_ref_block);
15071     return false;
15072   }
15073 
15074   return true;
15075 }
15076 
15077 // Returns true if the capture by block was successful.
15078 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15079                                  SourceLocation Loc,
15080                                  const bool BuildAndDiagnose,
15081                                  QualType &CaptureType,
15082                                  QualType &DeclRefType,
15083                                  const bool Nested,
15084                                  Sema &S) {
15085   Expr *CopyExpr = nullptr;
15086   bool ByRef = false;
15087 
15088   // Blocks are not allowed to capture arrays, excepting OpenCL.
15089   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15090   // (decayed to pointers).
15091   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15092     if (BuildAndDiagnose) {
15093       S.Diag(Loc, diag::err_ref_array_type);
15094       S.Diag(Var->getLocation(), diag::note_previous_decl)
15095       << Var->getDeclName();
15096     }
15097     return false;
15098   }
15099 
15100   // Forbid the block-capture of autoreleasing variables.
15101   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15102     if (BuildAndDiagnose) {
15103       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15104         << /*block*/ 0;
15105       S.Diag(Var->getLocation(), diag::note_previous_decl)
15106         << Var->getDeclName();
15107     }
15108     return false;
15109   }
15110 
15111   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15112   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15113     // This function finds out whether there is an AttributedType of kind
15114     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15115     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15116     // rather than being added implicitly by the compiler.
15117     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15118       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15119         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15120           return true;
15121 
15122         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15123         Ty = AttrTy->getModifiedType();
15124       }
15125 
15126       return false;
15127     };
15128 
15129     QualType PointeeTy = PT->getPointeeType();
15130 
15131     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
15132         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15133         !IsObjCOwnershipAttributedType(PointeeTy)) {
15134       if (BuildAndDiagnose) {
15135         SourceLocation VarLoc = Var->getLocation();
15136         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15137         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15138       }
15139     }
15140   }
15141 
15142   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15143   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15144       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15145     // Block capture by reference does not change the capture or
15146     // declaration reference types.
15147     ByRef = true;
15148   } else {
15149     // Block capture by copy introduces 'const'.
15150     CaptureType = CaptureType.getNonReferenceType().withConst();
15151     DeclRefType = CaptureType;
15152 
15153     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15154       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15155         // The capture logic needs the destructor, so make sure we mark it.
15156         // Usually this is unnecessary because most local variables have
15157         // their destructors marked at declaration time, but parameters are
15158         // an exception because it's technically only the call site that
15159         // actually requires the destructor.
15160         if (isa<ParmVarDecl>(Var))
15161           S.FinalizeVarWithDestructor(Var, Record);
15162 
15163         // Enter a new evaluation context to insulate the copy
15164         // full-expression.
15165         EnterExpressionEvaluationContext scope(
15166             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
15167 
15168         // According to the blocks spec, the capture of a variable from
15169         // the stack requires a const copy constructor.  This is not true
15170         // of the copy/move done to move a __block variable to the heap.
15171         Expr *DeclRef = new (S.Context) DeclRefExpr(
15172             S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15173 
15174         ExprResult Result
15175           = S.PerformCopyInitialization(
15176               InitializedEntity::InitializeBlock(Var->getLocation(),
15177                                                   CaptureType, false),
15178               Loc, DeclRef);
15179 
15180         // Build a full-expression copy expression if initialization
15181         // succeeded and used a non-trivial constructor.  Recover from
15182         // errors by pretending that the copy isn't necessary.
15183         if (!Result.isInvalid() &&
15184             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15185                 ->isTrivial()) {
15186           Result = S.MaybeCreateExprWithCleanups(Result);
15187           CopyExpr = Result.get();
15188         }
15189       }
15190     }
15191   }
15192 
15193   // Actually capture the variable.
15194   if (BuildAndDiagnose)
15195     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15196                     SourceLocation(), CaptureType, CopyExpr);
15197 
15198   return true;
15199 
15200 }
15201 
15202 
15203 /// Capture the given variable in the captured region.
15204 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15205                                     VarDecl *Var,
15206                                     SourceLocation Loc,
15207                                     const bool BuildAndDiagnose,
15208                                     QualType &CaptureType,
15209                                     QualType &DeclRefType,
15210                                     const bool RefersToCapturedVariable,
15211                                     Sema &S) {
15212   // By default, capture variables by reference.
15213   bool ByRef = true;
15214   // Using an LValue reference type is consistent with Lambdas (see below).
15215   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15216     if (S.isOpenMPCapturedDecl(Var)) {
15217       bool HasConst = DeclRefType.isConstQualified();
15218       DeclRefType = DeclRefType.getUnqualifiedType();
15219       // Don't lose diagnostics about assignments to const.
15220       if (HasConst)
15221         DeclRefType.addConst();
15222     }
15223     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15224   }
15225 
15226   if (ByRef)
15227     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15228   else
15229     CaptureType = DeclRefType;
15230 
15231   Expr *CopyExpr = nullptr;
15232   if (BuildAndDiagnose) {
15233     // The current implementation assumes that all variables are captured
15234     // by references. Since there is no capture by copy, no expression
15235     // evaluation will be needed.
15236     RecordDecl *RD = RSI->TheRecordDecl;
15237 
15238     FieldDecl *Field
15239       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15240                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15241                           nullptr, false, ICIS_NoInit);
15242     Field->setImplicit(true);
15243     Field->setAccess(AS_private);
15244     RD->addDecl(Field);
15245     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15246       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15247 
15248     CopyExpr = new (S.Context) DeclRefExpr(
15249         S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15250     Var->setReferenced(true);
15251     Var->markUsed(S.Context);
15252   }
15253 
15254   // Actually capture the variable.
15255   if (BuildAndDiagnose)
15256     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15257                     SourceLocation(), CaptureType, CopyExpr);
15258 
15259 
15260   return true;
15261 }
15262 
15263 /// Create a field within the lambda class for the variable
15264 /// being captured.
15265 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
15266                                     QualType FieldType, QualType DeclRefType,
15267                                     SourceLocation Loc,
15268                                     bool RefersToCapturedVariable) {
15269   CXXRecordDecl *Lambda = LSI->Lambda;
15270 
15271   // Build the non-static data member.
15272   FieldDecl *Field
15273     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15274                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15275                         nullptr, false, ICIS_NoInit);
15276   // If the variable being captured has an invalid type, mark the lambda class
15277   // as invalid as well.
15278   if (!FieldType->isDependentType()) {
15279     if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15280       Lambda->setInvalidDecl();
15281       Field->setInvalidDecl();
15282     } else {
15283       NamedDecl *Def;
15284       FieldType->isIncompleteType(&Def);
15285       if (Def && Def->isInvalidDecl()) {
15286         Lambda->setInvalidDecl();
15287         Field->setInvalidDecl();
15288       }
15289     }
15290   }
15291   Field->setImplicit(true);
15292   Field->setAccess(AS_private);
15293   Lambda->addDecl(Field);
15294 }
15295 
15296 /// Capture the given variable in the lambda.
15297 static bool captureInLambda(LambdaScopeInfo *LSI,
15298                             VarDecl *Var,
15299                             SourceLocation Loc,
15300                             const bool BuildAndDiagnose,
15301                             QualType &CaptureType,
15302                             QualType &DeclRefType,
15303                             const bool RefersToCapturedVariable,
15304                             const Sema::TryCaptureKind Kind,
15305                             SourceLocation EllipsisLoc,
15306                             const bool IsTopScope,
15307                             Sema &S) {
15308 
15309   // Determine whether we are capturing by reference or by value.
15310   bool ByRef = false;
15311   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15312     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15313   } else {
15314     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15315   }
15316 
15317   // Compute the type of the field that will capture this variable.
15318   if (ByRef) {
15319     // C++11 [expr.prim.lambda]p15:
15320     //   An entity is captured by reference if it is implicitly or
15321     //   explicitly captured but not captured by copy. It is
15322     //   unspecified whether additional unnamed non-static data
15323     //   members are declared in the closure type for entities
15324     //   captured by reference.
15325     //
15326     // FIXME: It is not clear whether we want to build an lvalue reference
15327     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15328     // to do the former, while EDG does the latter. Core issue 1249 will
15329     // clarify, but for now we follow GCC because it's a more permissive and
15330     // easily defensible position.
15331     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15332   } else {
15333     // C++11 [expr.prim.lambda]p14:
15334     //   For each entity captured by copy, an unnamed non-static
15335     //   data member is declared in the closure type. The
15336     //   declaration order of these members is unspecified. The type
15337     //   of such a data member is the type of the corresponding
15338     //   captured entity if the entity is not a reference to an
15339     //   object, or the referenced type otherwise. [Note: If the
15340     //   captured entity is a reference to a function, the
15341     //   corresponding data member is also a reference to a
15342     //   function. - end note ]
15343     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15344       if (!RefType->getPointeeType()->isFunctionType())
15345         CaptureType = RefType->getPointeeType();
15346     }
15347 
15348     // Forbid the lambda copy-capture of autoreleasing variables.
15349     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15350       if (BuildAndDiagnose) {
15351         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15352         S.Diag(Var->getLocation(), diag::note_previous_decl)
15353           << Var->getDeclName();
15354       }
15355       return false;
15356     }
15357 
15358     // Make sure that by-copy captures are of a complete and non-abstract type.
15359     if (BuildAndDiagnose) {
15360       if (!CaptureType->isDependentType() &&
15361           S.RequireCompleteType(Loc, CaptureType,
15362                                 diag::err_capture_of_incomplete_type,
15363                                 Var->getDeclName()))
15364         return false;
15365 
15366       if (S.RequireNonAbstractType(Loc, CaptureType,
15367                                    diag::err_capture_of_abstract_type))
15368         return false;
15369     }
15370   }
15371 
15372   // Capture this variable in the lambda.
15373   if (BuildAndDiagnose)
15374     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15375                             RefersToCapturedVariable);
15376 
15377   // Compute the type of a reference to this captured variable.
15378   if (ByRef)
15379     DeclRefType = CaptureType.getNonReferenceType();
15380   else {
15381     // C++ [expr.prim.lambda]p5:
15382     //   The closure type for a lambda-expression has a public inline
15383     //   function call operator [...]. This function call operator is
15384     //   declared const (9.3.1) if and only if the lambda-expression's
15385     //   parameter-declaration-clause is not followed by mutable.
15386     DeclRefType = CaptureType.getNonReferenceType();
15387     if (!LSI->Mutable && !CaptureType->isReferenceType())
15388       DeclRefType.addConst();
15389   }
15390 
15391   // Add the capture.
15392   if (BuildAndDiagnose)
15393     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15394                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15395 
15396   return true;
15397 }
15398 
15399 bool Sema::tryCaptureVariable(
15400     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15401     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15402     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15403   // An init-capture is notionally from the context surrounding its
15404   // declaration, but its parent DC is the lambda class.
15405   DeclContext *VarDC = Var->getDeclContext();
15406   if (Var->isInitCapture())
15407     VarDC = VarDC->getParent();
15408 
15409   DeclContext *DC = CurContext;
15410   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15411       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15412   // We need to sync up the Declaration Context with the
15413   // FunctionScopeIndexToStopAt
15414   if (FunctionScopeIndexToStopAt) {
15415     unsigned FSIndex = FunctionScopes.size() - 1;
15416     while (FSIndex != MaxFunctionScopesIndex) {
15417       DC = getLambdaAwareParentOfDeclContext(DC);
15418       --FSIndex;
15419     }
15420   }
15421 
15422 
15423   // If the variable is declared in the current context, there is no need to
15424   // capture it.
15425   if (VarDC == DC) return true;
15426 
15427   // Capture global variables if it is required to use private copy of this
15428   // variable.
15429   bool IsGlobal = !Var->hasLocalStorage();
15430   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15431     return true;
15432   Var = Var->getCanonicalDecl();
15433 
15434   // Walk up the stack to determine whether we can capture the variable,
15435   // performing the "simple" checks that don't depend on type. We stop when
15436   // we've either hit the declared scope of the variable or find an existing
15437   // capture of that variable.  We start from the innermost capturing-entity
15438   // (the DC) and ensure that all intervening capturing-entities
15439   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15440   // declcontext can either capture the variable or have already captured
15441   // the variable.
15442   CaptureType = Var->getType();
15443   DeclRefType = CaptureType.getNonReferenceType();
15444   bool Nested = false;
15445   bool Explicit = (Kind != TryCapture_Implicit);
15446   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15447   do {
15448     // Only block literals, captured statements, and lambda expressions can
15449     // capture; other scopes don't work.
15450     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15451                                                               ExprLoc,
15452                                                               BuildAndDiagnose,
15453                                                               *this);
15454     // We need to check for the parent *first* because, if we *have*
15455     // private-captured a global variable, we need to recursively capture it in
15456     // intermediate blocks, lambdas, etc.
15457     if (!ParentDC) {
15458       if (IsGlobal) {
15459         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15460         break;
15461       }
15462       return true;
15463     }
15464 
15465     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15466     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15467 
15468 
15469     // Check whether we've already captured it.
15470     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15471                                              DeclRefType)) {
15472       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15473       break;
15474     }
15475     // If we are instantiating a generic lambda call operator body,
15476     // we do not want to capture new variables.  What was captured
15477     // during either a lambdas transformation or initial parsing
15478     // should be used.
15479     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15480       if (BuildAndDiagnose) {
15481         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15482         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15483           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15484           Diag(Var->getLocation(), diag::note_previous_decl)
15485              << Var->getDeclName();
15486           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15487         } else
15488           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15489       }
15490       return true;
15491     }
15492     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15493     // certain types of variables (unnamed, variably modified types etc.)
15494     // so check for eligibility.
15495     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15496        return true;
15497 
15498     // Try to capture variable-length arrays types.
15499     if (Var->getType()->isVariablyModifiedType()) {
15500       // We're going to walk down into the type and look for VLA
15501       // expressions.
15502       QualType QTy = Var->getType();
15503       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15504         QTy = PVD->getOriginalType();
15505       captureVariablyModifiedType(Context, QTy, CSI);
15506     }
15507 
15508     if (getLangOpts().OpenMP) {
15509       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15510         // OpenMP private variables should not be captured in outer scope, so
15511         // just break here. Similarly, global variables that are captured in a
15512         // target region should not be captured outside the scope of the region.
15513         if (RSI->CapRegionKind == CR_OpenMP) {
15514           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15515           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15516                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15517           // When we detect target captures we are looking from inside the
15518           // target region, therefore we need to propagate the capture from the
15519           // enclosing region. Therefore, the capture is not initially nested.
15520           if (IsTargetCap)
15521             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15522 
15523           if (IsTargetCap || IsOpenMPPrivateDecl) {
15524             Nested = !IsTargetCap;
15525             DeclRefType = DeclRefType.getUnqualifiedType();
15526             CaptureType = Context.getLValueReferenceType(DeclRefType);
15527             break;
15528           }
15529         }
15530       }
15531     }
15532     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15533       // No capture-default, and this is not an explicit capture
15534       // so cannot capture this variable.
15535       if (BuildAndDiagnose) {
15536         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15537         Diag(Var->getLocation(), diag::note_previous_decl)
15538           << Var->getDeclName();
15539         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15540           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15541                diag::note_lambda_decl);
15542         // FIXME: If we error out because an outer lambda can not implicitly
15543         // capture a variable that an inner lambda explicitly captures, we
15544         // should have the inner lambda do the explicit capture - because
15545         // it makes for cleaner diagnostics later.  This would purely be done
15546         // so that the diagnostic does not misleadingly claim that a variable
15547         // can not be captured by a lambda implicitly even though it is captured
15548         // explicitly.  Suggestion:
15549         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15550         //    at the function head
15551         //  - cache the StartingDeclContext - this must be a lambda
15552         //  - captureInLambda in the innermost lambda the variable.
15553       }
15554       return true;
15555     }
15556 
15557     FunctionScopesIndex--;
15558     DC = ParentDC;
15559     Explicit = false;
15560   } while (!VarDC->Equals(DC));
15561 
15562   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15563   // computing the type of the capture at each step, checking type-specific
15564   // requirements, and adding captures if requested.
15565   // If the variable had already been captured previously, we start capturing
15566   // at the lambda nested within that one.
15567   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15568        ++I) {
15569     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15570 
15571     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15572       if (!captureInBlock(BSI, Var, ExprLoc,
15573                           BuildAndDiagnose, CaptureType,
15574                           DeclRefType, Nested, *this))
15575         return true;
15576       Nested = true;
15577     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15578       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15579                                    BuildAndDiagnose, CaptureType,
15580                                    DeclRefType, Nested, *this))
15581         return true;
15582       Nested = true;
15583     } else {
15584       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15585       if (!captureInLambda(LSI, Var, ExprLoc,
15586                            BuildAndDiagnose, CaptureType,
15587                            DeclRefType, Nested, Kind, EllipsisLoc,
15588                             /*IsTopScope*/I == N - 1, *this))
15589         return true;
15590       Nested = true;
15591     }
15592   }
15593   return false;
15594 }
15595 
15596 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15597                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15598   QualType CaptureType;
15599   QualType DeclRefType;
15600   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15601                             /*BuildAndDiagnose=*/true, CaptureType,
15602                             DeclRefType, nullptr);
15603 }
15604 
15605 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15606   QualType CaptureType;
15607   QualType DeclRefType;
15608   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15609                              /*BuildAndDiagnose=*/false, CaptureType,
15610                              DeclRefType, nullptr);
15611 }
15612 
15613 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15614   QualType CaptureType;
15615   QualType DeclRefType;
15616 
15617   // Determine whether we can capture this variable.
15618   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15619                          /*BuildAndDiagnose=*/false, CaptureType,
15620                          DeclRefType, nullptr))
15621     return QualType();
15622 
15623   return DeclRefType;
15624 }
15625 
15626 
15627 
15628 // If either the type of the variable or the initializer is dependent,
15629 // return false. Otherwise, determine whether the variable is a constant
15630 // expression. Use this if you need to know if a variable that might or
15631 // might not be dependent is truly a constant expression.
15632 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15633     ASTContext &Context) {
15634 
15635   if (Var->getType()->isDependentType())
15636     return false;
15637   const VarDecl *DefVD = nullptr;
15638   Var->getAnyInitializer(DefVD);
15639   if (!DefVD)
15640     return false;
15641   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15642   Expr *Init = cast<Expr>(Eval->Value);
15643   if (Init->isValueDependent())
15644     return false;
15645   return IsVariableAConstantExpression(Var, Context);
15646 }
15647 
15648 
15649 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15650   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15651   // an object that satisfies the requirements for appearing in a
15652   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15653   // is immediately applied."  This function handles the lvalue-to-rvalue
15654   // conversion part.
15655   MaybeODRUseExprs.erase(E->IgnoreParens());
15656 
15657   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15658   // to a variable that is a constant expression, and if so, identify it as
15659   // a reference to a variable that does not involve an odr-use of that
15660   // variable.
15661   if (LambdaScopeInfo *LSI = getCurLambda()) {
15662     Expr *SansParensExpr = E->IgnoreParens();
15663     VarDecl *Var = nullptr;
15664     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15665       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15666     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15667       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15668 
15669     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15670       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15671   }
15672 }
15673 
15674 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15675   Res = CorrectDelayedTyposInExpr(Res);
15676 
15677   if (!Res.isUsable())
15678     return Res;
15679 
15680   // If a constant-expression is a reference to a variable where we delay
15681   // deciding whether it is an odr-use, just assume we will apply the
15682   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15683   // (a non-type template argument), we have special handling anyway.
15684   UpdateMarkingForLValueToRValue(Res.get());
15685   return Res;
15686 }
15687 
15688 void Sema::CleanupVarDeclMarking() {
15689   for (Expr *E : MaybeODRUseExprs) {
15690     VarDecl *Var;
15691     SourceLocation Loc;
15692     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15693       Var = cast<VarDecl>(DRE->getDecl());
15694       Loc = DRE->getLocation();
15695     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15696       Var = cast<VarDecl>(ME->getMemberDecl());
15697       Loc = ME->getMemberLoc();
15698     } else {
15699       llvm_unreachable("Unexpected expression");
15700     }
15701 
15702     MarkVarDeclODRUsed(Var, Loc, *this,
15703                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15704   }
15705 
15706   MaybeODRUseExprs.clear();
15707 }
15708 
15709 
15710 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15711                                     VarDecl *Var, Expr *E) {
15712   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15713          "Invalid Expr argument to DoMarkVarDeclReferenced");
15714   Var->setReferenced();
15715 
15716   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15717 
15718   bool OdrUseContext = isOdrUseContext(SemaRef);
15719   bool UsableInConstantExpr =
15720       Var->isUsableInConstantExpressions(SemaRef.Context);
15721   bool NeedDefinition =
15722       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15723 
15724   VarTemplateSpecializationDecl *VarSpec =
15725       dyn_cast<VarTemplateSpecializationDecl>(Var);
15726   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15727          "Can't instantiate a partial template specialization.");
15728 
15729   // If this might be a member specialization of a static data member, check
15730   // the specialization is visible. We already did the checks for variable
15731   // template specializations when we created them.
15732   if (NeedDefinition && TSK != TSK_Undeclared &&
15733       !isa<VarTemplateSpecializationDecl>(Var))
15734     SemaRef.checkSpecializationVisibility(Loc, Var);
15735 
15736   // Perform implicit instantiation of static data members, static data member
15737   // templates of class templates, and variable template specializations. Delay
15738   // instantiations of variable templates, except for those that could be used
15739   // in a constant expression.
15740   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15741     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15742     // instantiation declaration if a variable is usable in a constant
15743     // expression (among other cases).
15744     bool TryInstantiating =
15745         TSK == TSK_ImplicitInstantiation ||
15746         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15747 
15748     if (TryInstantiating) {
15749       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15750       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15751       if (FirstInstantiation) {
15752         PointOfInstantiation = Loc;
15753         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15754       }
15755 
15756       bool InstantiationDependent = false;
15757       bool IsNonDependent =
15758           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15759                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15760                   : true;
15761 
15762       // Do not instantiate specializations that are still type-dependent.
15763       if (IsNonDependent) {
15764         if (UsableInConstantExpr) {
15765           // Do not defer instantiations of variables that could be used in a
15766           // constant expression.
15767           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15768         } else if (FirstInstantiation ||
15769                    isa<VarTemplateSpecializationDecl>(Var)) {
15770           // FIXME: For a specialization of a variable template, we don't
15771           // distinguish between "declaration and type implicitly instantiated"
15772           // and "implicit instantiation of definition requested", so we have
15773           // no direct way to avoid enqueueing the pending instantiation
15774           // multiple times.
15775           SemaRef.PendingInstantiations
15776               .push_back(std::make_pair(Var, PointOfInstantiation));
15777         }
15778       }
15779     }
15780   }
15781 
15782   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15783   // the requirements for appearing in a constant expression (5.19) and, if
15784   // it is an object, the lvalue-to-rvalue conversion (4.1)
15785   // is immediately applied."  We check the first part here, and
15786   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15787   // Note that we use the C++11 definition everywhere because nothing in
15788   // C++03 depends on whether we get the C++03 version correct. The second
15789   // part does not apply to references, since they are not objects.
15790   if (OdrUseContext && E &&
15791       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15792     // A reference initialized by a constant expression can never be
15793     // odr-used, so simply ignore it.
15794     if (!Var->getType()->isReferenceType() ||
15795         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15796       SemaRef.MaybeODRUseExprs.insert(E);
15797   } else if (OdrUseContext) {
15798     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15799                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15800   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15801     // If this is a dependent context, we don't need to mark variables as
15802     // odr-used, but we may still need to track them for lambda capture.
15803     // FIXME: Do we also need to do this inside dependent typeid expressions
15804     // (which are modeled as unevaluated at this point)?
15805     const bool RefersToEnclosingScope =
15806         (SemaRef.CurContext != Var->getDeclContext() &&
15807          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15808     if (RefersToEnclosingScope) {
15809       LambdaScopeInfo *const LSI =
15810           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15811       if (LSI && (!LSI->CallOperator ||
15812                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15813         // If a variable could potentially be odr-used, defer marking it so
15814         // until we finish analyzing the full expression for any
15815         // lvalue-to-rvalue
15816         // or discarded value conversions that would obviate odr-use.
15817         // Add it to the list of potential captures that will be analyzed
15818         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15819         // unless the variable is a reference that was initialized by a constant
15820         // expression (this will never need to be captured or odr-used).
15821         assert(E && "Capture variable should be used in an expression.");
15822         if (!Var->getType()->isReferenceType() ||
15823             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15824           LSI->addPotentialCapture(E->IgnoreParens());
15825       }
15826     }
15827   }
15828 }
15829 
15830 /// Mark a variable referenced, and check whether it is odr-used
15831 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15832 /// used directly for normal expressions referring to VarDecl.
15833 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15834   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15835 }
15836 
15837 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15838                                Decl *D, Expr *E, bool MightBeOdrUse) {
15839   if (SemaRef.isInOpenMPDeclareTargetContext())
15840     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15841 
15842   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15843     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15844     return;
15845   }
15846 
15847   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15848 
15849   // If this is a call to a method via a cast, also mark the method in the
15850   // derived class used in case codegen can devirtualize the call.
15851   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15852   if (!ME)
15853     return;
15854   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15855   if (!MD)
15856     return;
15857   // Only attempt to devirtualize if this is truly a virtual call.
15858   bool IsVirtualCall = MD->isVirtual() &&
15859                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15860   if (!IsVirtualCall)
15861     return;
15862 
15863   // If it's possible to devirtualize the call, mark the called function
15864   // referenced.
15865   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15866       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15867   if (DM)
15868     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15869 }
15870 
15871 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15872 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15873   // TODO: update this with DR# once a defect report is filed.
15874   // C++11 defect. The address of a pure member should not be an ODR use, even
15875   // if it's a qualified reference.
15876   bool OdrUse = true;
15877   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15878     if (Method->isVirtual() &&
15879         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15880       OdrUse = false;
15881   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15882 }
15883 
15884 /// Perform reference-marking and odr-use handling for a MemberExpr.
15885 void Sema::MarkMemberReferenced(MemberExpr *E) {
15886   // C++11 [basic.def.odr]p2:
15887   //   A non-overloaded function whose name appears as a potentially-evaluated
15888   //   expression or a member of a set of candidate functions, if selected by
15889   //   overload resolution when referred to from a potentially-evaluated
15890   //   expression, is odr-used, unless it is a pure virtual function and its
15891   //   name is not explicitly qualified.
15892   bool MightBeOdrUse = true;
15893   if (E->performsVirtualDispatch(getLangOpts())) {
15894     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15895       if (Method->isPure())
15896         MightBeOdrUse = false;
15897   }
15898   SourceLocation Loc =
15899       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15900   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15901 }
15902 
15903 /// Perform marking for a reference to an arbitrary declaration.  It
15904 /// marks the declaration referenced, and performs odr-use checking for
15905 /// functions and variables. This method should not be used when building a
15906 /// normal expression which refers to a variable.
15907 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15908                                  bool MightBeOdrUse) {
15909   if (MightBeOdrUse) {
15910     if (auto *VD = dyn_cast<VarDecl>(D)) {
15911       MarkVariableReferenced(Loc, VD);
15912       return;
15913     }
15914   }
15915   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15916     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15917     return;
15918   }
15919   D->setReferenced();
15920 }
15921 
15922 namespace {
15923   // Mark all of the declarations used by a type as referenced.
15924   // FIXME: Not fully implemented yet! We need to have a better understanding
15925   // of when we're entering a context we should not recurse into.
15926   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15927   // TreeTransforms rebuilding the type in a new context. Rather than
15928   // duplicating the TreeTransform logic, we should consider reusing it here.
15929   // Currently that causes problems when rebuilding LambdaExprs.
15930   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15931     Sema &S;
15932     SourceLocation Loc;
15933 
15934   public:
15935     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15936 
15937     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15938 
15939     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15940   };
15941 }
15942 
15943 bool MarkReferencedDecls::TraverseTemplateArgument(
15944     const TemplateArgument &Arg) {
15945   {
15946     // A non-type template argument is a constant-evaluated context.
15947     EnterExpressionEvaluationContext Evaluated(
15948         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15949     if (Arg.getKind() == TemplateArgument::Declaration) {
15950       if (Decl *D = Arg.getAsDecl())
15951         S.MarkAnyDeclReferenced(Loc, D, true);
15952     } else if (Arg.getKind() == TemplateArgument::Expression) {
15953       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15954     }
15955   }
15956 
15957   return Inherited::TraverseTemplateArgument(Arg);
15958 }
15959 
15960 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15961   MarkReferencedDecls Marker(*this, Loc);
15962   Marker.TraverseType(T);
15963 }
15964 
15965 namespace {
15966   /// Helper class that marks all of the declarations referenced by
15967   /// potentially-evaluated subexpressions as "referenced".
15968   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15969     Sema &S;
15970     bool SkipLocalVariables;
15971 
15972   public:
15973     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15974 
15975     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15976       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15977 
15978     void VisitDeclRefExpr(DeclRefExpr *E) {
15979       // If we were asked not to visit local variables, don't.
15980       if (SkipLocalVariables) {
15981         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15982           if (VD->hasLocalStorage())
15983             return;
15984       }
15985 
15986       S.MarkDeclRefReferenced(E);
15987     }
15988 
15989     void VisitMemberExpr(MemberExpr *E) {
15990       S.MarkMemberReferenced(E);
15991       Inherited::VisitMemberExpr(E);
15992     }
15993 
15994     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15995       S.MarkFunctionReferenced(
15996           E->getBeginLoc(),
15997           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15998       Visit(E->getSubExpr());
15999     }
16000 
16001     void VisitCXXNewExpr(CXXNewExpr *E) {
16002       if (E->getOperatorNew())
16003         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16004       if (E->getOperatorDelete())
16005         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16006       Inherited::VisitCXXNewExpr(E);
16007     }
16008 
16009     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16010       if (E->getOperatorDelete())
16011         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16012       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16013       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16014         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16015         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16016       }
16017 
16018       Inherited::VisitCXXDeleteExpr(E);
16019     }
16020 
16021     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16022       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16023       Inherited::VisitCXXConstructExpr(E);
16024     }
16025 
16026     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16027       Visit(E->getExpr());
16028     }
16029 
16030     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
16031       Inherited::VisitImplicitCastExpr(E);
16032 
16033       if (E->getCastKind() == CK_LValueToRValue)
16034         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
16035     }
16036   };
16037 }
16038 
16039 /// Mark any declarations that appear within this expression or any
16040 /// potentially-evaluated subexpressions as "referenced".
16041 ///
16042 /// \param SkipLocalVariables If true, don't mark local variables as
16043 /// 'referenced'.
16044 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16045                                             bool SkipLocalVariables) {
16046   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16047 }
16048 
16049 /// Emit a diagnostic that describes an effect on the run-time behavior
16050 /// of the program being compiled.
16051 ///
16052 /// This routine emits the given diagnostic when the code currently being
16053 /// type-checked is "potentially evaluated", meaning that there is a
16054 /// possibility that the code will actually be executable. Code in sizeof()
16055 /// expressions, code used only during overload resolution, etc., are not
16056 /// potentially evaluated. This routine will suppress such diagnostics or,
16057 /// in the absolutely nutty case of potentially potentially evaluated
16058 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16059 /// later.
16060 ///
16061 /// This routine should be used for all diagnostics that describe the run-time
16062 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16063 /// Failure to do so will likely result in spurious diagnostics or failures
16064 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16065 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16066                                const PartialDiagnostic &PD) {
16067   switch (ExprEvalContexts.back().Context) {
16068   case ExpressionEvaluationContext::Unevaluated:
16069   case ExpressionEvaluationContext::UnevaluatedList:
16070   case ExpressionEvaluationContext::UnevaluatedAbstract:
16071   case ExpressionEvaluationContext::DiscardedStatement:
16072     // The argument will never be evaluated, so don't complain.
16073     break;
16074 
16075   case ExpressionEvaluationContext::ConstantEvaluated:
16076     // Relevant diagnostics should be produced by constant evaluation.
16077     break;
16078 
16079   case ExpressionEvaluationContext::PotentiallyEvaluated:
16080   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16081     if (Statement && getCurFunctionOrMethodDecl()) {
16082       FunctionScopes.back()->PossiblyUnreachableDiags.
16083         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
16084       return true;
16085     }
16086 
16087     // The initializer of a constexpr variable or of the first declaration of a
16088     // static data member is not syntactically a constant evaluated constant,
16089     // but nonetheless is always required to be a constant expression, so we
16090     // can skip diagnosing.
16091     // FIXME: Using the mangling context here is a hack.
16092     if (auto *VD = dyn_cast_or_null<VarDecl>(
16093             ExprEvalContexts.back().ManglingContextDecl)) {
16094       if (VD->isConstexpr() ||
16095           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16096         break;
16097       // FIXME: For any other kind of variable, we should build a CFG for its
16098       // initializer and check whether the context in question is reachable.
16099     }
16100 
16101     Diag(Loc, PD);
16102     return true;
16103   }
16104 
16105   return false;
16106 }
16107 
16108 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16109                                CallExpr *CE, FunctionDecl *FD) {
16110   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16111     return false;
16112 
16113   // If we're inside a decltype's expression, don't check for a valid return
16114   // type or construct temporaries until we know whether this is the last call.
16115   if (ExprEvalContexts.back().ExprContext ==
16116       ExpressionEvaluationContextRecord::EK_Decltype) {
16117     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16118     return false;
16119   }
16120 
16121   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16122     FunctionDecl *FD;
16123     CallExpr *CE;
16124 
16125   public:
16126     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16127       : FD(FD), CE(CE) { }
16128 
16129     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16130       if (!FD) {
16131         S.Diag(Loc, diag::err_call_incomplete_return)
16132           << T << CE->getSourceRange();
16133         return;
16134       }
16135 
16136       S.Diag(Loc, diag::err_call_function_incomplete_return)
16137         << CE->getSourceRange() << FD->getDeclName() << T;
16138       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16139           << FD->getDeclName();
16140     }
16141   } Diagnoser(FD, CE);
16142 
16143   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16144     return true;
16145 
16146   return false;
16147 }
16148 
16149 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16150 // will prevent this condition from triggering, which is what we want.
16151 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16152   SourceLocation Loc;
16153 
16154   unsigned diagnostic = diag::warn_condition_is_assignment;
16155   bool IsOrAssign = false;
16156 
16157   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16158     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16159       return;
16160 
16161     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16162 
16163     // Greylist some idioms by putting them into a warning subcategory.
16164     if (ObjCMessageExpr *ME
16165           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16166       Selector Sel = ME->getSelector();
16167 
16168       // self = [<foo> init...]
16169       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16170         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16171 
16172       // <foo> = [<bar> nextObject]
16173       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16174         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16175     }
16176 
16177     Loc = Op->getOperatorLoc();
16178   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16179     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16180       return;
16181 
16182     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16183     Loc = Op->getOperatorLoc();
16184   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16185     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16186   else {
16187     // Not an assignment.
16188     return;
16189   }
16190 
16191   Diag(Loc, diagnostic) << E->getSourceRange();
16192 
16193   SourceLocation Open = E->getBeginLoc();
16194   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16195   Diag(Loc, diag::note_condition_assign_silence)
16196         << FixItHint::CreateInsertion(Open, "(")
16197         << FixItHint::CreateInsertion(Close, ")");
16198 
16199   if (IsOrAssign)
16200     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16201       << FixItHint::CreateReplacement(Loc, "!=");
16202   else
16203     Diag(Loc, diag::note_condition_assign_to_comparison)
16204       << FixItHint::CreateReplacement(Loc, "==");
16205 }
16206 
16207 /// Redundant parentheses over an equality comparison can indicate
16208 /// that the user intended an assignment used as condition.
16209 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16210   // Don't warn if the parens came from a macro.
16211   SourceLocation parenLoc = ParenE->getBeginLoc();
16212   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16213     return;
16214   // Don't warn for dependent expressions.
16215   if (ParenE->isTypeDependent())
16216     return;
16217 
16218   Expr *E = ParenE->IgnoreParens();
16219 
16220   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16221     if (opE->getOpcode() == BO_EQ &&
16222         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16223                                                            == Expr::MLV_Valid) {
16224       SourceLocation Loc = opE->getOperatorLoc();
16225 
16226       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16227       SourceRange ParenERange = ParenE->getSourceRange();
16228       Diag(Loc, diag::note_equality_comparison_silence)
16229         << FixItHint::CreateRemoval(ParenERange.getBegin())
16230         << FixItHint::CreateRemoval(ParenERange.getEnd());
16231       Diag(Loc, diag::note_equality_comparison_to_assign)
16232         << FixItHint::CreateReplacement(Loc, "=");
16233     }
16234 }
16235 
16236 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16237                                        bool IsConstexpr) {
16238   DiagnoseAssignmentAsCondition(E);
16239   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16240     DiagnoseEqualityWithExtraParens(parenE);
16241 
16242   ExprResult result = CheckPlaceholderExpr(E);
16243   if (result.isInvalid()) return ExprError();
16244   E = result.get();
16245 
16246   if (!E->isTypeDependent()) {
16247     if (getLangOpts().CPlusPlus)
16248       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16249 
16250     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16251     if (ERes.isInvalid())
16252       return ExprError();
16253     E = ERes.get();
16254 
16255     QualType T = E->getType();
16256     if (!T->isScalarType()) { // C99 6.8.4.1p1
16257       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16258         << T << E->getSourceRange();
16259       return ExprError();
16260     }
16261     CheckBoolLikeConversion(E, Loc);
16262   }
16263 
16264   return E;
16265 }
16266 
16267 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16268                                            Expr *SubExpr, ConditionKind CK) {
16269   // Empty conditions are valid in for-statements.
16270   if (!SubExpr)
16271     return ConditionResult();
16272 
16273   ExprResult Cond;
16274   switch (CK) {
16275   case ConditionKind::Boolean:
16276     Cond = CheckBooleanCondition(Loc, SubExpr);
16277     break;
16278 
16279   case ConditionKind::ConstexprIf:
16280     Cond = CheckBooleanCondition(Loc, SubExpr, true);
16281     break;
16282 
16283   case ConditionKind::Switch:
16284     Cond = CheckSwitchCondition(Loc, SubExpr);
16285     break;
16286   }
16287   if (Cond.isInvalid())
16288     return ConditionError();
16289 
16290   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16291   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16292   if (!FullExpr.get())
16293     return ConditionError();
16294 
16295   return ConditionResult(*this, nullptr, FullExpr,
16296                          CK == ConditionKind::ConstexprIf);
16297 }
16298 
16299 namespace {
16300   /// A visitor for rebuilding a call to an __unknown_any expression
16301   /// to have an appropriate type.
16302   struct RebuildUnknownAnyFunction
16303     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16304 
16305     Sema &S;
16306 
16307     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16308 
16309     ExprResult VisitStmt(Stmt *S) {
16310       llvm_unreachable("unexpected statement!");
16311     }
16312 
16313     ExprResult VisitExpr(Expr *E) {
16314       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16315         << E->getSourceRange();
16316       return ExprError();
16317     }
16318 
16319     /// Rebuild an expression which simply semantically wraps another
16320     /// expression which it shares the type and value kind of.
16321     template <class T> ExprResult rebuildSugarExpr(T *E) {
16322       ExprResult SubResult = Visit(E->getSubExpr());
16323       if (SubResult.isInvalid()) return ExprError();
16324 
16325       Expr *SubExpr = SubResult.get();
16326       E->setSubExpr(SubExpr);
16327       E->setType(SubExpr->getType());
16328       E->setValueKind(SubExpr->getValueKind());
16329       assert(E->getObjectKind() == OK_Ordinary);
16330       return E;
16331     }
16332 
16333     ExprResult VisitParenExpr(ParenExpr *E) {
16334       return rebuildSugarExpr(E);
16335     }
16336 
16337     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16338       return rebuildSugarExpr(E);
16339     }
16340 
16341     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16342       ExprResult SubResult = Visit(E->getSubExpr());
16343       if (SubResult.isInvalid()) return ExprError();
16344 
16345       Expr *SubExpr = SubResult.get();
16346       E->setSubExpr(SubExpr);
16347       E->setType(S.Context.getPointerType(SubExpr->getType()));
16348       assert(E->getValueKind() == VK_RValue);
16349       assert(E->getObjectKind() == OK_Ordinary);
16350       return E;
16351     }
16352 
16353     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16354       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16355 
16356       E->setType(VD->getType());
16357 
16358       assert(E->getValueKind() == VK_RValue);
16359       if (S.getLangOpts().CPlusPlus &&
16360           !(isa<CXXMethodDecl>(VD) &&
16361             cast<CXXMethodDecl>(VD)->isInstance()))
16362         E->setValueKind(VK_LValue);
16363 
16364       return E;
16365     }
16366 
16367     ExprResult VisitMemberExpr(MemberExpr *E) {
16368       return resolveDecl(E, E->getMemberDecl());
16369     }
16370 
16371     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16372       return resolveDecl(E, E->getDecl());
16373     }
16374   };
16375 }
16376 
16377 /// Given a function expression of unknown-any type, try to rebuild it
16378 /// to have a function type.
16379 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16380   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16381   if (Result.isInvalid()) return ExprError();
16382   return S.DefaultFunctionArrayConversion(Result.get());
16383 }
16384 
16385 namespace {
16386   /// A visitor for rebuilding an expression of type __unknown_anytype
16387   /// into one which resolves the type directly on the referring
16388   /// expression.  Strict preservation of the original source
16389   /// structure is not a goal.
16390   struct RebuildUnknownAnyExpr
16391     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16392 
16393     Sema &S;
16394 
16395     /// The current destination type.
16396     QualType DestType;
16397 
16398     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16399       : S(S), DestType(CastType) {}
16400 
16401     ExprResult VisitStmt(Stmt *S) {
16402       llvm_unreachable("unexpected statement!");
16403     }
16404 
16405     ExprResult VisitExpr(Expr *E) {
16406       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16407         << E->getSourceRange();
16408       return ExprError();
16409     }
16410 
16411     ExprResult VisitCallExpr(CallExpr *E);
16412     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16413 
16414     /// Rebuild an expression which simply semantically wraps another
16415     /// expression which it shares the type and value kind of.
16416     template <class T> ExprResult rebuildSugarExpr(T *E) {
16417       ExprResult SubResult = Visit(E->getSubExpr());
16418       if (SubResult.isInvalid()) return ExprError();
16419       Expr *SubExpr = SubResult.get();
16420       E->setSubExpr(SubExpr);
16421       E->setType(SubExpr->getType());
16422       E->setValueKind(SubExpr->getValueKind());
16423       assert(E->getObjectKind() == OK_Ordinary);
16424       return E;
16425     }
16426 
16427     ExprResult VisitParenExpr(ParenExpr *E) {
16428       return rebuildSugarExpr(E);
16429     }
16430 
16431     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16432       return rebuildSugarExpr(E);
16433     }
16434 
16435     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16436       const PointerType *Ptr = DestType->getAs<PointerType>();
16437       if (!Ptr) {
16438         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16439           << E->getSourceRange();
16440         return ExprError();
16441       }
16442 
16443       if (isa<CallExpr>(E->getSubExpr())) {
16444         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16445           << E->getSourceRange();
16446         return ExprError();
16447       }
16448 
16449       assert(E->getValueKind() == VK_RValue);
16450       assert(E->getObjectKind() == OK_Ordinary);
16451       E->setType(DestType);
16452 
16453       // Build the sub-expression as if it were an object of the pointee type.
16454       DestType = Ptr->getPointeeType();
16455       ExprResult SubResult = Visit(E->getSubExpr());
16456       if (SubResult.isInvalid()) return ExprError();
16457       E->setSubExpr(SubResult.get());
16458       return E;
16459     }
16460 
16461     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16462 
16463     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16464 
16465     ExprResult VisitMemberExpr(MemberExpr *E) {
16466       return resolveDecl(E, E->getMemberDecl());
16467     }
16468 
16469     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16470       return resolveDecl(E, E->getDecl());
16471     }
16472   };
16473 }
16474 
16475 /// Rebuilds a call expression which yielded __unknown_anytype.
16476 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16477   Expr *CalleeExpr = E->getCallee();
16478 
16479   enum FnKind {
16480     FK_MemberFunction,
16481     FK_FunctionPointer,
16482     FK_BlockPointer
16483   };
16484 
16485   FnKind Kind;
16486   QualType CalleeType = CalleeExpr->getType();
16487   if (CalleeType == S.Context.BoundMemberTy) {
16488     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16489     Kind = FK_MemberFunction;
16490     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16491   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16492     CalleeType = Ptr->getPointeeType();
16493     Kind = FK_FunctionPointer;
16494   } else {
16495     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16496     Kind = FK_BlockPointer;
16497   }
16498   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16499 
16500   // Verify that this is a legal result type of a function.
16501   if (DestType->isArrayType() || DestType->isFunctionType()) {
16502     unsigned diagID = diag::err_func_returning_array_function;
16503     if (Kind == FK_BlockPointer)
16504       diagID = diag::err_block_returning_array_function;
16505 
16506     S.Diag(E->getExprLoc(), diagID)
16507       << DestType->isFunctionType() << DestType;
16508     return ExprError();
16509   }
16510 
16511   // Otherwise, go ahead and set DestType as the call's result.
16512   E->setType(DestType.getNonLValueExprType(S.Context));
16513   E->setValueKind(Expr::getValueKindForType(DestType));
16514   assert(E->getObjectKind() == OK_Ordinary);
16515 
16516   // Rebuild the function type, replacing the result type with DestType.
16517   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16518   if (Proto) {
16519     // __unknown_anytype(...) is a special case used by the debugger when
16520     // it has no idea what a function's signature is.
16521     //
16522     // We want to build this call essentially under the K&R
16523     // unprototyped rules, but making a FunctionNoProtoType in C++
16524     // would foul up all sorts of assumptions.  However, we cannot
16525     // simply pass all arguments as variadic arguments, nor can we
16526     // portably just call the function under a non-variadic type; see
16527     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16528     // However, it turns out that in practice it is generally safe to
16529     // call a function declared as "A foo(B,C,D);" under the prototype
16530     // "A foo(B,C,D,...);".  The only known exception is with the
16531     // Windows ABI, where any variadic function is implicitly cdecl
16532     // regardless of its normal CC.  Therefore we change the parameter
16533     // types to match the types of the arguments.
16534     //
16535     // This is a hack, but it is far superior to moving the
16536     // corresponding target-specific code from IR-gen to Sema/AST.
16537 
16538     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16539     SmallVector<QualType, 8> ArgTypes;
16540     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16541       ArgTypes.reserve(E->getNumArgs());
16542       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16543         Expr *Arg = E->getArg(i);
16544         QualType ArgType = Arg->getType();
16545         if (E->isLValue()) {
16546           ArgType = S.Context.getLValueReferenceType(ArgType);
16547         } else if (E->isXValue()) {
16548           ArgType = S.Context.getRValueReferenceType(ArgType);
16549         }
16550         ArgTypes.push_back(ArgType);
16551       }
16552       ParamTypes = ArgTypes;
16553     }
16554     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16555                                          Proto->getExtProtoInfo());
16556   } else {
16557     DestType = S.Context.getFunctionNoProtoType(DestType,
16558                                                 FnType->getExtInfo());
16559   }
16560 
16561   // Rebuild the appropriate pointer-to-function type.
16562   switch (Kind) {
16563   case FK_MemberFunction:
16564     // Nothing to do.
16565     break;
16566 
16567   case FK_FunctionPointer:
16568     DestType = S.Context.getPointerType(DestType);
16569     break;
16570 
16571   case FK_BlockPointer:
16572     DestType = S.Context.getBlockPointerType(DestType);
16573     break;
16574   }
16575 
16576   // Finally, we can recurse.
16577   ExprResult CalleeResult = Visit(CalleeExpr);
16578   if (!CalleeResult.isUsable()) return ExprError();
16579   E->setCallee(CalleeResult.get());
16580 
16581   // Bind a temporary if necessary.
16582   return S.MaybeBindToTemporary(E);
16583 }
16584 
16585 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16586   // Verify that this is a legal result type of a call.
16587   if (DestType->isArrayType() || DestType->isFunctionType()) {
16588     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16589       << DestType->isFunctionType() << DestType;
16590     return ExprError();
16591   }
16592 
16593   // Rewrite the method result type if available.
16594   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16595     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16596     Method->setReturnType(DestType);
16597   }
16598 
16599   // Change the type of the message.
16600   E->setType(DestType.getNonReferenceType());
16601   E->setValueKind(Expr::getValueKindForType(DestType));
16602 
16603   return S.MaybeBindToTemporary(E);
16604 }
16605 
16606 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16607   // The only case we should ever see here is a function-to-pointer decay.
16608   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16609     assert(E->getValueKind() == VK_RValue);
16610     assert(E->getObjectKind() == OK_Ordinary);
16611 
16612     E->setType(DestType);
16613 
16614     // Rebuild the sub-expression as the pointee (function) type.
16615     DestType = DestType->castAs<PointerType>()->getPointeeType();
16616 
16617     ExprResult Result = Visit(E->getSubExpr());
16618     if (!Result.isUsable()) return ExprError();
16619 
16620     E->setSubExpr(Result.get());
16621     return E;
16622   } else if (E->getCastKind() == CK_LValueToRValue) {
16623     assert(E->getValueKind() == VK_RValue);
16624     assert(E->getObjectKind() == OK_Ordinary);
16625 
16626     assert(isa<BlockPointerType>(E->getType()));
16627 
16628     E->setType(DestType);
16629 
16630     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16631     DestType = S.Context.getLValueReferenceType(DestType);
16632 
16633     ExprResult Result = Visit(E->getSubExpr());
16634     if (!Result.isUsable()) return ExprError();
16635 
16636     E->setSubExpr(Result.get());
16637     return E;
16638   } else {
16639     llvm_unreachable("Unhandled cast type!");
16640   }
16641 }
16642 
16643 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16644   ExprValueKind ValueKind = VK_LValue;
16645   QualType Type = DestType;
16646 
16647   // We know how to make this work for certain kinds of decls:
16648 
16649   //  - functions
16650   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16651     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16652       DestType = Ptr->getPointeeType();
16653       ExprResult Result = resolveDecl(E, VD);
16654       if (Result.isInvalid()) return ExprError();
16655       return S.ImpCastExprToType(Result.get(), Type,
16656                                  CK_FunctionToPointerDecay, VK_RValue);
16657     }
16658 
16659     if (!Type->isFunctionType()) {
16660       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16661         << VD << E->getSourceRange();
16662       return ExprError();
16663     }
16664     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16665       // We must match the FunctionDecl's type to the hack introduced in
16666       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16667       // type. See the lengthy commentary in that routine.
16668       QualType FDT = FD->getType();
16669       const FunctionType *FnType = FDT->castAs<FunctionType>();
16670       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16671       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16672       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16673         SourceLocation Loc = FD->getLocation();
16674         FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
16675                                       FD->getDeclContext(),
16676                                       Loc, Loc, FD->getNameInfo().getName(),
16677                                       DestType, FD->getTypeSourceInfo(),
16678                                       SC_None, false/*isInlineSpecified*/,
16679                                       FD->hasPrototype(),
16680                                       false/*isConstexprSpecified*/);
16681 
16682         if (FD->getQualifier())
16683           NewFD->setQualifierInfo(FD->getQualifierLoc());
16684 
16685         SmallVector<ParmVarDecl*, 16> Params;
16686         for (const auto &AI : FT->param_types()) {
16687           ParmVarDecl *Param =
16688             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16689           Param->setScopeInfo(0, Params.size());
16690           Params.push_back(Param);
16691         }
16692         NewFD->setParams(Params);
16693         DRE->setDecl(NewFD);
16694         VD = DRE->getDecl();
16695       }
16696     }
16697 
16698     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16699       if (MD->isInstance()) {
16700         ValueKind = VK_RValue;
16701         Type = S.Context.BoundMemberTy;
16702       }
16703 
16704     // Function references aren't l-values in C.
16705     if (!S.getLangOpts().CPlusPlus)
16706       ValueKind = VK_RValue;
16707 
16708   //  - variables
16709   } else if (isa<VarDecl>(VD)) {
16710     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16711       Type = RefTy->getPointeeType();
16712     } else if (Type->isFunctionType()) {
16713       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16714         << VD << E->getSourceRange();
16715       return ExprError();
16716     }
16717 
16718   //  - nothing else
16719   } else {
16720     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16721       << VD << E->getSourceRange();
16722     return ExprError();
16723   }
16724 
16725   // Modifying the declaration like this is friendly to IR-gen but
16726   // also really dangerous.
16727   VD->setType(DestType);
16728   E->setType(Type);
16729   E->setValueKind(ValueKind);
16730   return E;
16731 }
16732 
16733 /// Check a cast of an unknown-any type.  We intentionally only
16734 /// trigger this for C-style casts.
16735 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16736                                      Expr *CastExpr, CastKind &CastKind,
16737                                      ExprValueKind &VK, CXXCastPath &Path) {
16738   // The type we're casting to must be either void or complete.
16739   if (!CastType->isVoidType() &&
16740       RequireCompleteType(TypeRange.getBegin(), CastType,
16741                           diag::err_typecheck_cast_to_incomplete))
16742     return ExprError();
16743 
16744   // Rewrite the casted expression from scratch.
16745   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16746   if (!result.isUsable()) return ExprError();
16747 
16748   CastExpr = result.get();
16749   VK = CastExpr->getValueKind();
16750   CastKind = CK_NoOp;
16751 
16752   return CastExpr;
16753 }
16754 
16755 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16756   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16757 }
16758 
16759 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16760                                     Expr *arg, QualType &paramType) {
16761   // If the syntactic form of the argument is not an explicit cast of
16762   // any sort, just do default argument promotion.
16763   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16764   if (!castArg) {
16765     ExprResult result = DefaultArgumentPromotion(arg);
16766     if (result.isInvalid()) return ExprError();
16767     paramType = result.get()->getType();
16768     return result;
16769   }
16770 
16771   // Otherwise, use the type that was written in the explicit cast.
16772   assert(!arg->hasPlaceholderType());
16773   paramType = castArg->getTypeAsWritten();
16774 
16775   // Copy-initialize a parameter of that type.
16776   InitializedEntity entity =
16777     InitializedEntity::InitializeParameter(Context, paramType,
16778                                            /*consumed*/ false);
16779   return PerformCopyInitialization(entity, callLoc, arg);
16780 }
16781 
16782 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16783   Expr *orig = E;
16784   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16785   while (true) {
16786     E = E->IgnoreParenImpCasts();
16787     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16788       E = call->getCallee();
16789       diagID = diag::err_uncasted_call_of_unknown_any;
16790     } else {
16791       break;
16792     }
16793   }
16794 
16795   SourceLocation loc;
16796   NamedDecl *d;
16797   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16798     loc = ref->getLocation();
16799     d = ref->getDecl();
16800   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16801     loc = mem->getMemberLoc();
16802     d = mem->getMemberDecl();
16803   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16804     diagID = diag::err_uncasted_call_of_unknown_any;
16805     loc = msg->getSelectorStartLoc();
16806     d = msg->getMethodDecl();
16807     if (!d) {
16808       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16809         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16810         << orig->getSourceRange();
16811       return ExprError();
16812     }
16813   } else {
16814     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16815       << E->getSourceRange();
16816     return ExprError();
16817   }
16818 
16819   S.Diag(loc, diagID) << d << orig->getSourceRange();
16820 
16821   // Never recoverable.
16822   return ExprError();
16823 }
16824 
16825 /// Check for operands with placeholder types and complain if found.
16826 /// Returns ExprError() if there was an error and no recovery was possible.
16827 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16828   if (!getLangOpts().CPlusPlus) {
16829     // C cannot handle TypoExpr nodes on either side of a binop because it
16830     // doesn't handle dependent types properly, so make sure any TypoExprs have
16831     // been dealt with before checking the operands.
16832     ExprResult Result = CorrectDelayedTyposInExpr(E);
16833     if (!Result.isUsable()) return ExprError();
16834     E = Result.get();
16835   }
16836 
16837   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16838   if (!placeholderType) return E;
16839 
16840   switch (placeholderType->getKind()) {
16841 
16842   // Overloaded expressions.
16843   case BuiltinType::Overload: {
16844     // Try to resolve a single function template specialization.
16845     // This is obligatory.
16846     ExprResult Result = E;
16847     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16848       return Result;
16849 
16850     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16851     // leaves Result unchanged on failure.
16852     Result = E;
16853     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16854       return Result;
16855 
16856     // If that failed, try to recover with a call.
16857     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16858                          /*complain*/ true);
16859     return Result;
16860   }
16861 
16862   // Bound member functions.
16863   case BuiltinType::BoundMember: {
16864     ExprResult result = E;
16865     const Expr *BME = E->IgnoreParens();
16866     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16867     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16868     if (isa<CXXPseudoDestructorExpr>(BME)) {
16869       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16870     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16871       if (ME->getMemberNameInfo().getName().getNameKind() ==
16872           DeclarationName::CXXDestructorName)
16873         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16874     }
16875     tryToRecoverWithCall(result, PD,
16876                          /*complain*/ true);
16877     return result;
16878   }
16879 
16880   // ARC unbridged casts.
16881   case BuiltinType::ARCUnbridgedCast: {
16882     Expr *realCast = stripARCUnbridgedCast(E);
16883     diagnoseARCUnbridgedCast(realCast);
16884     return realCast;
16885   }
16886 
16887   // Expressions of unknown type.
16888   case BuiltinType::UnknownAny:
16889     return diagnoseUnknownAnyExpr(*this, E);
16890 
16891   // Pseudo-objects.
16892   case BuiltinType::PseudoObject:
16893     return checkPseudoObjectRValue(E);
16894 
16895   case BuiltinType::BuiltinFn: {
16896     // Accept __noop without parens by implicitly converting it to a call expr.
16897     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16898     if (DRE) {
16899       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16900       if (FD->getBuiltinID() == Builtin::BI__noop) {
16901         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16902                               CK_BuiltinFnToFnPtr)
16903                 .get();
16904         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16905                                 VK_RValue, SourceLocation());
16906       }
16907     }
16908 
16909     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16910     return ExprError();
16911   }
16912 
16913   // Expressions of unknown type.
16914   case BuiltinType::OMPArraySection:
16915     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16916     return ExprError();
16917 
16918   // Everything else should be impossible.
16919 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16920   case BuiltinType::Id:
16921 #include "clang/Basic/OpenCLImageTypes.def"
16922 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16923   case BuiltinType::Id:
16924 #include "clang/Basic/OpenCLExtensionTypes.def"
16925 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16926 #define PLACEHOLDER_TYPE(Id, SingletonId)
16927 #include "clang/AST/BuiltinTypes.def"
16928     break;
16929   }
16930 
16931   llvm_unreachable("invalid placeholder type!");
16932 }
16933 
16934 bool Sema::CheckCaseExpression(Expr *E) {
16935   if (E->isTypeDependent())
16936     return true;
16937   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16938     return E->getType()->isIntegralOrEnumerationType();
16939   return false;
16940 }
16941 
16942 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16943 ExprResult
16944 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16945   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16946          "Unknown Objective-C Boolean value!");
16947   QualType BoolT = Context.ObjCBuiltinBoolTy;
16948   if (!Context.getBOOLDecl()) {
16949     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16950                         Sema::LookupOrdinaryName);
16951     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16952       NamedDecl *ND = Result.getFoundDecl();
16953       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16954         Context.setBOOLDecl(TD);
16955     }
16956   }
16957   if (Context.getBOOLDecl())
16958     BoolT = Context.getBOOLType();
16959   return new (Context)
16960       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16961 }
16962 
16963 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16964     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16965     SourceLocation RParen) {
16966 
16967   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16968 
16969   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16970                            [&](const AvailabilitySpec &Spec) {
16971                              return Spec.getPlatform() == Platform;
16972                            });
16973 
16974   VersionTuple Version;
16975   if (Spec != AvailSpecs.end())
16976     Version = Spec->getVersion();
16977 
16978   // The use of `@available` in the enclosing function should be analyzed to
16979   // warn when it's used inappropriately (i.e. not if(@available)).
16980   if (getCurFunctionOrMethodDecl())
16981     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16982   else if (getCurBlock() || getCurLambda())
16983     getCurFunction()->HasPotentialAvailabilityViolations = true;
16984 
16985   return new (Context)
16986       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16987 }
16988