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   ExprResult Res = CheckLValueToRValueConversionOperand(E);
629   if (Res.isInvalid())
630     return Res;
631   E = Res.get();
632 
633   // Loading a __weak object implicitly retains the value, so we need a cleanup to
634   // balance that.
635   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
636     Cleanup.setExprNeedsCleanups(true);
637 
638   // C++ [conv.lval]p3:
639   //   If T is cv std::nullptr_t, the result is a null pointer constant.
640   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
641   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
642 
643   // C11 6.3.2.1p2:
644   //   ... if the lvalue has atomic type, the value has the non-atomic version
645   //   of the type of the lvalue ...
646   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
647     T = Atomic->getValueType().getUnqualifiedType();
648     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
649                                    nullptr, VK_RValue);
650   }
651 
652   return Res;
653 }
654 
655 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
656   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
657   if (Res.isInvalid())
658     return ExprError();
659   Res = DefaultLvalueConversion(Res.get());
660   if (Res.isInvalid())
661     return ExprError();
662   return Res;
663 }
664 
665 /// CallExprUnaryConversions - a special case of an unary conversion
666 /// performed on a function designator of a call expression.
667 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
668   QualType Ty = E->getType();
669   ExprResult Res = E;
670   // Only do implicit cast for a function type, but not for a pointer
671   // to function type.
672   if (Ty->isFunctionType()) {
673     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
674                             CK_FunctionToPointerDecay).get();
675     if (Res.isInvalid())
676       return ExprError();
677   }
678   Res = DefaultLvalueConversion(Res.get());
679   if (Res.isInvalid())
680     return ExprError();
681   return Res.get();
682 }
683 
684 /// UsualUnaryConversions - Performs various conversions that are common to most
685 /// operators (C99 6.3). The conversions of array and function types are
686 /// sometimes suppressed. For example, the array->pointer conversion doesn't
687 /// apply if the array is an argument to the sizeof or address (&) operators.
688 /// In these instances, this routine should *not* be called.
689 ExprResult Sema::UsualUnaryConversions(Expr *E) {
690   // First, convert to an r-value.
691   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
692   if (Res.isInvalid())
693     return ExprError();
694   E = Res.get();
695 
696   QualType Ty = E->getType();
697   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
698 
699   // Half FP have to be promoted to float unless it is natively supported
700   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
701     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
702 
703   // Try to perform integral promotions if the object has a theoretically
704   // promotable type.
705   if (Ty->isIntegralOrUnscopedEnumerationType()) {
706     // C99 6.3.1.1p2:
707     //
708     //   The following may be used in an expression wherever an int or
709     //   unsigned int may be used:
710     //     - an object or expression with an integer type whose integer
711     //       conversion rank is less than or equal to the rank of int
712     //       and unsigned int.
713     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
714     //
715     //   If an int can represent all values of the original type, the
716     //   value is converted to an int; otherwise, it is converted to an
717     //   unsigned int. These are called the integer promotions. All
718     //   other types are unchanged by the integer promotions.
719 
720     QualType PTy = Context.isPromotableBitField(E);
721     if (!PTy.isNull()) {
722       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
723       return E;
724     }
725     if (Ty->isPromotableIntegerType()) {
726       QualType PT = Context.getPromotedIntegerType(Ty);
727       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
728       return E;
729     }
730   }
731   return E;
732 }
733 
734 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
735 /// do not have a prototype. Arguments that have type float or __fp16
736 /// are promoted to double. All other argument types are converted by
737 /// UsualUnaryConversions().
738 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
739   QualType Ty = E->getType();
740   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
741 
742   ExprResult Res = UsualUnaryConversions(E);
743   if (Res.isInvalid())
744     return ExprError();
745   E = Res.get();
746 
747   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
748   // promote to double.
749   // Note that default argument promotion applies only to float (and
750   // half/fp16); it does not apply to _Float16.
751   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
752   if (BTy && (BTy->getKind() == BuiltinType::Half ||
753               BTy->getKind() == BuiltinType::Float)) {
754     if (getLangOpts().OpenCL &&
755         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
756         if (BTy->getKind() == BuiltinType::Half) {
757             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
758         }
759     } else {
760       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
761     }
762   }
763 
764   // C++ performs lvalue-to-rvalue conversion as a default argument
765   // promotion, even on class types, but note:
766   //   C++11 [conv.lval]p2:
767   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
768   //     operand or a subexpression thereof the value contained in the
769   //     referenced object is not accessed. Otherwise, if the glvalue
770   //     has a class type, the conversion copy-initializes a temporary
771   //     of type T from the glvalue and the result of the conversion
772   //     is a prvalue for the temporary.
773   // FIXME: add some way to gate this entire thing for correctness in
774   // potentially potentially evaluated contexts.
775   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
776     ExprResult Temp = PerformCopyInitialization(
777                        InitializedEntity::InitializeTemporary(E->getType()),
778                                                 E->getExprLoc(), E);
779     if (Temp.isInvalid())
780       return ExprError();
781     E = Temp.get();
782   }
783 
784   return E;
785 }
786 
787 /// Determine the degree of POD-ness for an expression.
788 /// Incomplete types are considered POD, since this check can be performed
789 /// when we're in an unevaluated context.
790 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
791   if (Ty->isIncompleteType()) {
792     // C++11 [expr.call]p7:
793     //   After these conversions, if the argument does not have arithmetic,
794     //   enumeration, pointer, pointer to member, or class type, the program
795     //   is ill-formed.
796     //
797     // Since we've already performed array-to-pointer and function-to-pointer
798     // decay, the only such type in C++ is cv void. This also handles
799     // initializer lists as variadic arguments.
800     if (Ty->isVoidType())
801       return VAK_Invalid;
802 
803     if (Ty->isObjCObjectType())
804       return VAK_Invalid;
805     return VAK_Valid;
806   }
807 
808   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
809     return VAK_Invalid;
810 
811   if (Ty.isCXX98PODType(Context))
812     return VAK_Valid;
813 
814   // C++11 [expr.call]p7:
815   //   Passing a potentially-evaluated argument of class type (Clause 9)
816   //   having a non-trivial copy constructor, a non-trivial move constructor,
817   //   or a non-trivial destructor, with no corresponding parameter,
818   //   is conditionally-supported with implementation-defined semantics.
819   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
820     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
821       if (!Record->hasNonTrivialCopyConstructor() &&
822           !Record->hasNonTrivialMoveConstructor() &&
823           !Record->hasNonTrivialDestructor())
824         return VAK_ValidInCXX11;
825 
826   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
827     return VAK_Valid;
828 
829   if (Ty->isObjCObjectType())
830     return VAK_Invalid;
831 
832   if (getLangOpts().MSVCCompat)
833     return VAK_MSVCUndefined;
834 
835   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
836   // permitted to reject them. We should consider doing so.
837   return VAK_Undefined;
838 }
839 
840 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
841   // Don't allow one to pass an Objective-C interface to a vararg.
842   const QualType &Ty = E->getType();
843   VarArgKind VAK = isValidVarArgType(Ty);
844 
845   // Complain about passing non-POD types through varargs.
846   switch (VAK) {
847   case VAK_ValidInCXX11:
848     DiagRuntimeBehavior(
849         E->getBeginLoc(), nullptr,
850         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
851     LLVM_FALLTHROUGH;
852   case VAK_Valid:
853     if (Ty->isRecordType()) {
854       // This is unlikely to be what the user intended. If the class has a
855       // 'c_str' member function, the user probably meant to call that.
856       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
857                           PDiag(diag::warn_pass_class_arg_to_vararg)
858                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
859     }
860     break;
861 
862   case VAK_Undefined:
863   case VAK_MSVCUndefined:
864     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
865                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
866                             << getLangOpts().CPlusPlus11 << Ty << CT);
867     break;
868 
869   case VAK_Invalid:
870     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
871       Diag(E->getBeginLoc(),
872            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
873           << Ty << CT;
874     else if (Ty->isObjCObjectType())
875       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
876                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
877                               << Ty << CT);
878     else
879       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
880           << isa<InitListExpr>(E) << Ty << CT;
881     break;
882   }
883 }
884 
885 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
886 /// will create a trap if the resulting type is not a POD type.
887 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
888                                                   FunctionDecl *FDecl) {
889   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
890     // Strip the unbridged-cast placeholder expression off, if applicable.
891     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
892         (CT == VariadicMethod ||
893          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
894       E = stripARCUnbridgedCast(E);
895 
896     // Otherwise, do normal placeholder checking.
897     } else {
898       ExprResult ExprRes = CheckPlaceholderExpr(E);
899       if (ExprRes.isInvalid())
900         return ExprError();
901       E = ExprRes.get();
902     }
903   }
904 
905   ExprResult ExprRes = DefaultArgumentPromotion(E);
906   if (ExprRes.isInvalid())
907     return ExprError();
908   E = ExprRes.get();
909 
910   // Diagnostics regarding non-POD argument types are
911   // emitted along with format string checking in Sema::CheckFunctionCall().
912   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
913     // Turn this into a trap.
914     CXXScopeSpec SS;
915     SourceLocation TemplateKWLoc;
916     UnqualifiedId Name;
917     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
918                        E->getBeginLoc());
919     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
920                                           /*HasTrailingLParen=*/true,
921                                           /*IsAddressOfOperand=*/false);
922     if (TrapFn.isInvalid())
923       return ExprError();
924 
925     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
926                                     None, E->getEndLoc());
927     if (Call.isInvalid())
928       return ExprError();
929 
930     ExprResult Comma =
931         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
932     if (Comma.isInvalid())
933       return ExprError();
934     return Comma.get();
935   }
936 
937   if (!getLangOpts().CPlusPlus &&
938       RequireCompleteType(E->getExprLoc(), E->getType(),
939                           diag::err_call_incomplete_argument))
940     return ExprError();
941 
942   return E;
943 }
944 
945 /// Converts an integer to complex float type.  Helper function of
946 /// UsualArithmeticConversions()
947 ///
948 /// \return false if the integer expression is an integer type and is
949 /// successfully converted to the complex type.
950 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
951                                                   ExprResult &ComplexExpr,
952                                                   QualType IntTy,
953                                                   QualType ComplexTy,
954                                                   bool SkipCast) {
955   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
956   if (SkipCast) return false;
957   if (IntTy->isIntegerType()) {
958     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
959     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
960     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
961                                   CK_FloatingRealToComplex);
962   } else {
963     assert(IntTy->isComplexIntegerType());
964     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
965                                   CK_IntegralComplexToFloatingComplex);
966   }
967   return false;
968 }
969 
970 /// Handle arithmetic conversion with complex types.  Helper function of
971 /// UsualArithmeticConversions()
972 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
973                                              ExprResult &RHS, QualType LHSType,
974                                              QualType RHSType,
975                                              bool IsCompAssign) {
976   // if we have an integer operand, the result is the complex type.
977   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
978                                              /*skipCast*/false))
979     return LHSType;
980   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
981                                              /*skipCast*/IsCompAssign))
982     return RHSType;
983 
984   // This handles complex/complex, complex/float, or float/complex.
985   // When both operands are complex, the shorter operand is converted to the
986   // type of the longer, and that is the type of the result. This corresponds
987   // to what is done when combining two real floating-point operands.
988   // The fun begins when size promotion occur across type domains.
989   // From H&S 6.3.4: When one operand is complex and the other is a real
990   // floating-point type, the less precise type is converted, within it's
991   // real or complex domain, to the precision of the other type. For example,
992   // when combining a "long double" with a "double _Complex", the
993   // "double _Complex" is promoted to "long double _Complex".
994 
995   // Compute the rank of the two types, regardless of whether they are complex.
996   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
997 
998   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
999   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1000   QualType LHSElementType =
1001       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1002   QualType RHSElementType =
1003       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1004 
1005   QualType ResultType = S.Context.getComplexType(LHSElementType);
1006   if (Order < 0) {
1007     // Promote the precision of the LHS if not an assignment.
1008     ResultType = S.Context.getComplexType(RHSElementType);
1009     if (!IsCompAssign) {
1010       if (LHSComplexType)
1011         LHS =
1012             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1013       else
1014         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1015     }
1016   } else if (Order > 0) {
1017     // Promote the precision of the RHS.
1018     if (RHSComplexType)
1019       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1020     else
1021       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1022   }
1023   return ResultType;
1024 }
1025 
1026 /// Handle arithmetic conversion from integer to float.  Helper function
1027 /// of UsualArithmeticConversions()
1028 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1029                                            ExprResult &IntExpr,
1030                                            QualType FloatTy, QualType IntTy,
1031                                            bool ConvertFloat, bool ConvertInt) {
1032   if (IntTy->isIntegerType()) {
1033     if (ConvertInt)
1034       // Convert intExpr to the lhs floating point type.
1035       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1036                                     CK_IntegralToFloating);
1037     return FloatTy;
1038   }
1039 
1040   // Convert both sides to the appropriate complex float.
1041   assert(IntTy->isComplexIntegerType());
1042   QualType result = S.Context.getComplexType(FloatTy);
1043 
1044   // _Complex int -> _Complex float
1045   if (ConvertInt)
1046     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1047                                   CK_IntegralComplexToFloatingComplex);
1048 
1049   // float -> _Complex float
1050   if (ConvertFloat)
1051     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1052                                     CK_FloatingRealToComplex);
1053 
1054   return result;
1055 }
1056 
1057 /// Handle arithmethic conversion with floating point types.  Helper
1058 /// function of UsualArithmeticConversions()
1059 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1060                                       ExprResult &RHS, QualType LHSType,
1061                                       QualType RHSType, bool IsCompAssign) {
1062   bool LHSFloat = LHSType->isRealFloatingType();
1063   bool RHSFloat = RHSType->isRealFloatingType();
1064 
1065   // If we have two real floating types, convert the smaller operand
1066   // to the bigger result.
1067   if (LHSFloat && RHSFloat) {
1068     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1069     if (order > 0) {
1070       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1071       return LHSType;
1072     }
1073 
1074     assert(order < 0 && "illegal float comparison");
1075     if (!IsCompAssign)
1076       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1077     return RHSType;
1078   }
1079 
1080   if (LHSFloat) {
1081     // Half FP has to be promoted to float unless it is natively supported
1082     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1083       LHSType = S.Context.FloatTy;
1084 
1085     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1086                                       /*ConvertFloat=*/!IsCompAssign,
1087                                       /*ConvertInt=*/ true);
1088   }
1089   assert(RHSFloat);
1090   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1091                                     /*convertInt=*/ true,
1092                                     /*convertFloat=*/!IsCompAssign);
1093 }
1094 
1095 /// Diagnose attempts to convert between __float128 and long double if
1096 /// there is no support for such conversion. Helper function of
1097 /// UsualArithmeticConversions().
1098 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1099                                       QualType RHSType) {
1100   /*  No issue converting if at least one of the types is not a floating point
1101       type or the two types have the same rank.
1102   */
1103   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1104       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1105     return false;
1106 
1107   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1108          "The remaining types must be floating point types.");
1109 
1110   auto *LHSComplex = LHSType->getAs<ComplexType>();
1111   auto *RHSComplex = RHSType->getAs<ComplexType>();
1112 
1113   QualType LHSElemType = LHSComplex ?
1114     LHSComplex->getElementType() : LHSType;
1115   QualType RHSElemType = RHSComplex ?
1116     RHSComplex->getElementType() : RHSType;
1117 
1118   // No issue if the two types have the same representation
1119   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1120       &S.Context.getFloatTypeSemantics(RHSElemType))
1121     return false;
1122 
1123   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1124                                 RHSElemType == S.Context.LongDoubleTy);
1125   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1126                             RHSElemType == S.Context.Float128Ty);
1127 
1128   // We've handled the situation where __float128 and long double have the same
1129   // representation. We allow all conversions for all possible long double types
1130   // except PPC's double double.
1131   return Float128AndLongDouble &&
1132     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1133      &llvm::APFloat::PPCDoubleDouble());
1134 }
1135 
1136 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1137 
1138 namespace {
1139 /// These helper callbacks are placed in an anonymous namespace to
1140 /// permit their use as function template parameters.
1141 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1142   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1143 }
1144 
1145 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1146   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1147                              CK_IntegralComplexCast);
1148 }
1149 }
1150 
1151 /// Handle integer arithmetic conversions.  Helper function of
1152 /// UsualArithmeticConversions()
1153 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1154 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1155                                         ExprResult &RHS, QualType LHSType,
1156                                         QualType RHSType, bool IsCompAssign) {
1157   // The rules for this case are in C99 6.3.1.8
1158   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1159   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1160   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1161   if (LHSSigned == RHSSigned) {
1162     // Same signedness; use the higher-ranked type
1163     if (order >= 0) {
1164       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1165       return LHSType;
1166     } else if (!IsCompAssign)
1167       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1168     return RHSType;
1169   } else if (order != (LHSSigned ? 1 : -1)) {
1170     // The unsigned type has greater than or equal rank to the
1171     // signed type, so use the unsigned type
1172     if (RHSSigned) {
1173       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1174       return LHSType;
1175     } else if (!IsCompAssign)
1176       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1177     return RHSType;
1178   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1179     // The two types are different widths; if we are here, that
1180     // means the signed type is larger than the unsigned type, so
1181     // use the signed type.
1182     if (LHSSigned) {
1183       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1184       return LHSType;
1185     } else if (!IsCompAssign)
1186       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1187     return RHSType;
1188   } else {
1189     // The signed type is higher-ranked than the unsigned type,
1190     // but isn't actually any bigger (like unsigned int and long
1191     // on most 32-bit systems).  Use the unsigned type corresponding
1192     // to the signed type.
1193     QualType result =
1194       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1195     RHS = (*doRHSCast)(S, RHS.get(), result);
1196     if (!IsCompAssign)
1197       LHS = (*doLHSCast)(S, LHS.get(), result);
1198     return result;
1199   }
1200 }
1201 
1202 /// Handle conversions with GCC complex int extension.  Helper function
1203 /// of UsualArithmeticConversions()
1204 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1205                                            ExprResult &RHS, QualType LHSType,
1206                                            QualType RHSType,
1207                                            bool IsCompAssign) {
1208   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1209   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1210 
1211   if (LHSComplexInt && RHSComplexInt) {
1212     QualType LHSEltType = LHSComplexInt->getElementType();
1213     QualType RHSEltType = RHSComplexInt->getElementType();
1214     QualType ScalarType =
1215       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1216         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1217 
1218     return S.Context.getComplexType(ScalarType);
1219   }
1220 
1221   if (LHSComplexInt) {
1222     QualType LHSEltType = LHSComplexInt->getElementType();
1223     QualType ScalarType =
1224       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1225         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1226     QualType ComplexType = S.Context.getComplexType(ScalarType);
1227     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1228                               CK_IntegralRealToComplex);
1229 
1230     return ComplexType;
1231   }
1232 
1233   assert(RHSComplexInt);
1234 
1235   QualType RHSEltType = RHSComplexInt->getElementType();
1236   QualType ScalarType =
1237     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1238       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1239   QualType ComplexType = S.Context.getComplexType(ScalarType);
1240 
1241   if (!IsCompAssign)
1242     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1243                               CK_IntegralRealToComplex);
1244   return ComplexType;
1245 }
1246 
1247 /// Return the rank of a given fixed point or integer type. The value itself
1248 /// doesn't matter, but the values must be increasing with proper increasing
1249 /// rank as described in N1169 4.1.1.
1250 static unsigned GetFixedPointRank(QualType Ty) {
1251   const auto *BTy = Ty->getAs<BuiltinType>();
1252   assert(BTy && "Expected a builtin type.");
1253 
1254   switch (BTy->getKind()) {
1255   case BuiltinType::ShortFract:
1256   case BuiltinType::UShortFract:
1257   case BuiltinType::SatShortFract:
1258   case BuiltinType::SatUShortFract:
1259     return 1;
1260   case BuiltinType::Fract:
1261   case BuiltinType::UFract:
1262   case BuiltinType::SatFract:
1263   case BuiltinType::SatUFract:
1264     return 2;
1265   case BuiltinType::LongFract:
1266   case BuiltinType::ULongFract:
1267   case BuiltinType::SatLongFract:
1268   case BuiltinType::SatULongFract:
1269     return 3;
1270   case BuiltinType::ShortAccum:
1271   case BuiltinType::UShortAccum:
1272   case BuiltinType::SatShortAccum:
1273   case BuiltinType::SatUShortAccum:
1274     return 4;
1275   case BuiltinType::Accum:
1276   case BuiltinType::UAccum:
1277   case BuiltinType::SatAccum:
1278   case BuiltinType::SatUAccum:
1279     return 5;
1280   case BuiltinType::LongAccum:
1281   case BuiltinType::ULongAccum:
1282   case BuiltinType::SatLongAccum:
1283   case BuiltinType::SatULongAccum:
1284     return 6;
1285   default:
1286     if (BTy->isInteger())
1287       return 0;
1288     llvm_unreachable("Unexpected fixed point or integer type");
1289   }
1290 }
1291 
1292 /// handleFixedPointConversion - Fixed point operations between fixed
1293 /// point types and integers or other fixed point types do not fall under
1294 /// usual arithmetic conversion since these conversions could result in loss
1295 /// of precsision (N1169 4.1.4). These operations should be calculated with
1296 /// the full precision of their result type (N1169 4.1.6.2.1).
1297 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1298                                            QualType RHSTy) {
1299   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1300          "Expected at least one of the operands to be a fixed point type");
1301   assert((LHSTy->isFixedPointOrIntegerType() ||
1302           RHSTy->isFixedPointOrIntegerType()) &&
1303          "Special fixed point arithmetic operation conversions are only "
1304          "applied to ints or other fixed point types");
1305 
1306   // If one operand has signed fixed-point type and the other operand has
1307   // unsigned fixed-point type, then the unsigned fixed-point operand is
1308   // converted to its corresponding signed fixed-point type and the resulting
1309   // type is the type of the converted operand.
1310   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1311     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1312   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1313     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1314 
1315   // The result type is the type with the highest rank, whereby a fixed-point
1316   // conversion rank is always greater than an integer conversion rank; if the
1317   // type of either of the operands is a saturating fixedpoint type, the result
1318   // type shall be the saturating fixed-point type corresponding to the type
1319   // with the highest rank; the resulting value is converted (taking into
1320   // account rounding and overflow) to the precision of the resulting type.
1321   // Same ranks between signed and unsigned types are resolved earlier, so both
1322   // types are either signed or both unsigned at this point.
1323   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1324   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1325 
1326   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1327 
1328   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1329     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1330 
1331   return ResultTy;
1332 }
1333 
1334 /// UsualArithmeticConversions - Performs various conversions that are common to
1335 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1336 /// routine returns the first non-arithmetic type found. The client is
1337 /// responsible for emitting appropriate error diagnostics.
1338 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1339                                           bool IsCompAssign) {
1340   if (!IsCompAssign) {
1341     LHS = UsualUnaryConversions(LHS.get());
1342     if (LHS.isInvalid())
1343       return QualType();
1344   }
1345 
1346   RHS = UsualUnaryConversions(RHS.get());
1347   if (RHS.isInvalid())
1348     return QualType();
1349 
1350   // For conversion purposes, we ignore any qualifiers.
1351   // For example, "const float" and "float" are equivalent.
1352   QualType LHSType =
1353     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1354   QualType RHSType =
1355     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1356 
1357   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1358   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1359     LHSType = AtomicLHS->getValueType();
1360 
1361   // If both types are identical, no conversion is needed.
1362   if (LHSType == RHSType)
1363     return LHSType;
1364 
1365   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1366   // The caller can deal with this (e.g. pointer + int).
1367   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1368     return QualType();
1369 
1370   // Apply unary and bitfield promotions to the LHS's type.
1371   QualType LHSUnpromotedType = LHSType;
1372   if (LHSType->isPromotableIntegerType())
1373     LHSType = Context.getPromotedIntegerType(LHSType);
1374   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1375   if (!LHSBitfieldPromoteTy.isNull())
1376     LHSType = LHSBitfieldPromoteTy;
1377   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1378     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1379 
1380   // If both types are identical, no conversion is needed.
1381   if (LHSType == RHSType)
1382     return LHSType;
1383 
1384   // At this point, we have two different arithmetic types.
1385 
1386   // Diagnose attempts to convert between __float128 and long double where
1387   // such conversions currently can't be handled.
1388   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1389     return QualType();
1390 
1391   // Handle complex types first (C99 6.3.1.8p1).
1392   if (LHSType->isComplexType() || RHSType->isComplexType())
1393     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1394                                         IsCompAssign);
1395 
1396   // Now handle "real" floating types (i.e. float, double, long double).
1397   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1398     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1399                                  IsCompAssign);
1400 
1401   // Handle GCC complex int extension.
1402   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1403     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1404                                       IsCompAssign);
1405 
1406   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1407     return handleFixedPointConversion(*this, LHSType, RHSType);
1408 
1409   // Finally, we have two differing integer types.
1410   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1411            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1412 }
1413 
1414 //===----------------------------------------------------------------------===//
1415 //  Semantic Analysis for various Expression Types
1416 //===----------------------------------------------------------------------===//
1417 
1418 
1419 ExprResult
1420 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1421                                 SourceLocation DefaultLoc,
1422                                 SourceLocation RParenLoc,
1423                                 Expr *ControllingExpr,
1424                                 ArrayRef<ParsedType> ArgTypes,
1425                                 ArrayRef<Expr *> ArgExprs) {
1426   unsigned NumAssocs = ArgTypes.size();
1427   assert(NumAssocs == ArgExprs.size());
1428 
1429   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1430   for (unsigned i = 0; i < NumAssocs; ++i) {
1431     if (ArgTypes[i])
1432       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1433     else
1434       Types[i] = nullptr;
1435   }
1436 
1437   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1438                                              ControllingExpr,
1439                                              llvm::makeArrayRef(Types, NumAssocs),
1440                                              ArgExprs);
1441   delete [] Types;
1442   return ER;
1443 }
1444 
1445 ExprResult
1446 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1447                                  SourceLocation DefaultLoc,
1448                                  SourceLocation RParenLoc,
1449                                  Expr *ControllingExpr,
1450                                  ArrayRef<TypeSourceInfo *> Types,
1451                                  ArrayRef<Expr *> Exprs) {
1452   unsigned NumAssocs = Types.size();
1453   assert(NumAssocs == Exprs.size());
1454 
1455   // Decay and strip qualifiers for the controlling expression type, and handle
1456   // placeholder type replacement. See committee discussion from WG14 DR423.
1457   {
1458     EnterExpressionEvaluationContext Unevaluated(
1459         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1460     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1461     if (R.isInvalid())
1462       return ExprError();
1463     ControllingExpr = R.get();
1464   }
1465 
1466   // The controlling expression is an unevaluated operand, so side effects are
1467   // likely unintended.
1468   if (!inTemplateInstantiation() &&
1469       ControllingExpr->HasSideEffects(Context, false))
1470     Diag(ControllingExpr->getExprLoc(),
1471          diag::warn_side_effects_unevaluated_context);
1472 
1473   bool TypeErrorFound = false,
1474        IsResultDependent = ControllingExpr->isTypeDependent(),
1475        ContainsUnexpandedParameterPack
1476          = ControllingExpr->containsUnexpandedParameterPack();
1477 
1478   for (unsigned i = 0; i < NumAssocs; ++i) {
1479     if (Exprs[i]->containsUnexpandedParameterPack())
1480       ContainsUnexpandedParameterPack = true;
1481 
1482     if (Types[i]) {
1483       if (Types[i]->getType()->containsUnexpandedParameterPack())
1484         ContainsUnexpandedParameterPack = true;
1485 
1486       if (Types[i]->getType()->isDependentType()) {
1487         IsResultDependent = true;
1488       } else {
1489         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1490         // complete object type other than a variably modified type."
1491         unsigned D = 0;
1492         if (Types[i]->getType()->isIncompleteType())
1493           D = diag::err_assoc_type_incomplete;
1494         else if (!Types[i]->getType()->isObjectType())
1495           D = diag::err_assoc_type_nonobject;
1496         else if (Types[i]->getType()->isVariablyModifiedType())
1497           D = diag::err_assoc_type_variably_modified;
1498 
1499         if (D != 0) {
1500           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1501             << Types[i]->getTypeLoc().getSourceRange()
1502             << Types[i]->getType();
1503           TypeErrorFound = true;
1504         }
1505 
1506         // C11 6.5.1.1p2 "No two generic associations in the same generic
1507         // selection shall specify compatible types."
1508         for (unsigned j = i+1; j < NumAssocs; ++j)
1509           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1510               Context.typesAreCompatible(Types[i]->getType(),
1511                                          Types[j]->getType())) {
1512             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1513                  diag::err_assoc_compatible_types)
1514               << Types[j]->getTypeLoc().getSourceRange()
1515               << Types[j]->getType()
1516               << Types[i]->getType();
1517             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1518                  diag::note_compat_assoc)
1519               << Types[i]->getTypeLoc().getSourceRange()
1520               << Types[i]->getType();
1521             TypeErrorFound = true;
1522           }
1523       }
1524     }
1525   }
1526   if (TypeErrorFound)
1527     return ExprError();
1528 
1529   // If we determined that the generic selection is result-dependent, don't
1530   // try to compute the result expression.
1531   if (IsResultDependent)
1532     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1533                                         Exprs, DefaultLoc, RParenLoc,
1534                                         ContainsUnexpandedParameterPack);
1535 
1536   SmallVector<unsigned, 1> CompatIndices;
1537   unsigned DefaultIndex = -1U;
1538   for (unsigned i = 0; i < NumAssocs; ++i) {
1539     if (!Types[i])
1540       DefaultIndex = i;
1541     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1542                                         Types[i]->getType()))
1543       CompatIndices.push_back(i);
1544   }
1545 
1546   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1547   // type compatible with at most one of the types named in its generic
1548   // association list."
1549   if (CompatIndices.size() > 1) {
1550     // We strip parens here because the controlling expression is typically
1551     // parenthesized in macro definitions.
1552     ControllingExpr = ControllingExpr->IgnoreParens();
1553     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1554         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1555         << (unsigned)CompatIndices.size();
1556     for (unsigned I : CompatIndices) {
1557       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1558            diag::note_compat_assoc)
1559         << Types[I]->getTypeLoc().getSourceRange()
1560         << Types[I]->getType();
1561     }
1562     return ExprError();
1563   }
1564 
1565   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1566   // its controlling expression shall have type compatible with exactly one of
1567   // the types named in its generic association list."
1568   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1569     // We strip parens here because the controlling expression is typically
1570     // parenthesized in macro definitions.
1571     ControllingExpr = ControllingExpr->IgnoreParens();
1572     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1573         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1574     return ExprError();
1575   }
1576 
1577   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1578   // type name that is compatible with the type of the controlling expression,
1579   // then the result expression of the generic selection is the expression
1580   // in that generic association. Otherwise, the result expression of the
1581   // generic selection is the expression in the default generic association."
1582   unsigned ResultIndex =
1583     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1584 
1585   return GenericSelectionExpr::Create(
1586       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1587       ContainsUnexpandedParameterPack, ResultIndex);
1588 }
1589 
1590 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1591 /// location of the token and the offset of the ud-suffix within it.
1592 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1593                                      unsigned Offset) {
1594   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1595                                         S.getLangOpts());
1596 }
1597 
1598 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1599 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1600 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1601                                                  IdentifierInfo *UDSuffix,
1602                                                  SourceLocation UDSuffixLoc,
1603                                                  ArrayRef<Expr*> Args,
1604                                                  SourceLocation LitEndLoc) {
1605   assert(Args.size() <= 2 && "too many arguments for literal operator");
1606 
1607   QualType ArgTy[2];
1608   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1609     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1610     if (ArgTy[ArgIdx]->isArrayType())
1611       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1612   }
1613 
1614   DeclarationName OpName =
1615     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1616   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1617   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1618 
1619   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1620   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1621                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1622                               /*AllowStringTemplate*/ false,
1623                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1624     return ExprError();
1625 
1626   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1627 }
1628 
1629 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1630 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1631 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1632 /// multiple tokens.  However, the common case is that StringToks points to one
1633 /// string.
1634 ///
1635 ExprResult
1636 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1637   assert(!StringToks.empty() && "Must have at least one string!");
1638 
1639   StringLiteralParser Literal(StringToks, PP);
1640   if (Literal.hadError)
1641     return ExprError();
1642 
1643   SmallVector<SourceLocation, 4> StringTokLocs;
1644   for (const Token &Tok : StringToks)
1645     StringTokLocs.push_back(Tok.getLocation());
1646 
1647   QualType CharTy = Context.CharTy;
1648   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1649   if (Literal.isWide()) {
1650     CharTy = Context.getWideCharType();
1651     Kind = StringLiteral::Wide;
1652   } else if (Literal.isUTF8()) {
1653     if (getLangOpts().Char8)
1654       CharTy = Context.Char8Ty;
1655     Kind = StringLiteral::UTF8;
1656   } else if (Literal.isUTF16()) {
1657     CharTy = Context.Char16Ty;
1658     Kind = StringLiteral::UTF16;
1659   } else if (Literal.isUTF32()) {
1660     CharTy = Context.Char32Ty;
1661     Kind = StringLiteral::UTF32;
1662   } else if (Literal.isPascal()) {
1663     CharTy = Context.UnsignedCharTy;
1664   }
1665 
1666   // Warn on initializing an array of char from a u8 string literal; this
1667   // becomes ill-formed in C++2a.
1668   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1669       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1670     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1671 
1672     // Create removals for all 'u8' prefixes in the string literal(s). This
1673     // ensures C++2a compatibility (but may change the program behavior when
1674     // built by non-Clang compilers for which the execution character set is
1675     // not always UTF-8).
1676     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1677     SourceLocation RemovalDiagLoc;
1678     for (const Token &Tok : StringToks) {
1679       if (Tok.getKind() == tok::utf8_string_literal) {
1680         if (RemovalDiagLoc.isInvalid())
1681           RemovalDiagLoc = Tok.getLocation();
1682         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1683             Tok.getLocation(),
1684             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1685                                            getSourceManager(), getLangOpts())));
1686       }
1687     }
1688     Diag(RemovalDiagLoc, RemovalDiag);
1689   }
1690 
1691   QualType StrTy =
1692       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1693 
1694   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1695   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1696                                              Kind, Literal.Pascal, StrTy,
1697                                              &StringTokLocs[0],
1698                                              StringTokLocs.size());
1699   if (Literal.getUDSuffix().empty())
1700     return Lit;
1701 
1702   // We're building a user-defined literal.
1703   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1704   SourceLocation UDSuffixLoc =
1705     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1706                    Literal.getUDSuffixOffset());
1707 
1708   // Make sure we're allowed user-defined literals here.
1709   if (!UDLScope)
1710     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1711 
1712   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1713   //   operator "" X (str, len)
1714   QualType SizeType = Context.getSizeType();
1715 
1716   DeclarationName OpName =
1717     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1718   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1719   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1720 
1721   QualType ArgTy[] = {
1722     Context.getArrayDecayedType(StrTy), SizeType
1723   };
1724 
1725   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1726   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1727                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1728                                 /*AllowStringTemplate*/ true,
1729                                 /*DiagnoseMissing*/ true)) {
1730 
1731   case LOLR_Cooked: {
1732     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1733     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1734                                                     StringTokLocs[0]);
1735     Expr *Args[] = { Lit, LenArg };
1736 
1737     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1738   }
1739 
1740   case LOLR_StringTemplate: {
1741     TemplateArgumentListInfo ExplicitArgs;
1742 
1743     unsigned CharBits = Context.getIntWidth(CharTy);
1744     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1745     llvm::APSInt Value(CharBits, CharIsUnsigned);
1746 
1747     TemplateArgument TypeArg(CharTy);
1748     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1749     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1750 
1751     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1752       Value = Lit->getCodeUnit(I);
1753       TemplateArgument Arg(Context, Value, CharTy);
1754       TemplateArgumentLocInfo ArgInfo;
1755       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1756     }
1757     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1758                                     &ExplicitArgs);
1759   }
1760   case LOLR_Raw:
1761   case LOLR_Template:
1762   case LOLR_ErrorNoDiagnostic:
1763     llvm_unreachable("unexpected literal operator lookup result");
1764   case LOLR_Error:
1765     return ExprError();
1766   }
1767   llvm_unreachable("unexpected literal operator lookup result");
1768 }
1769 
1770 DeclRefExpr *
1771 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1772                        SourceLocation Loc,
1773                        const CXXScopeSpec *SS) {
1774   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1775   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1776 }
1777 
1778 DeclRefExpr *
1779 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1780                        const DeclarationNameInfo &NameInfo,
1781                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1782                        SourceLocation TemplateKWLoc,
1783                        const TemplateArgumentListInfo *TemplateArgs) {
1784   NestedNameSpecifierLoc NNS =
1785       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1786   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1787                           TemplateArgs);
1788 }
1789 
1790 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1791   // A declaration named in an unevaluated operand never constitutes an odr-use.
1792   if (isUnevaluatedContext())
1793     return NOUR_Unevaluated;
1794 
1795   // C++2a [basic.def.odr]p4:
1796   //   A variable x whose name appears as a potentially-evaluated expression e
1797   //   is odr-used by e unless [...] x is a reference that is usable in
1798   //   constant expressions.
1799   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800     if (VD->getType()->isReferenceType() &&
1801         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1802         VD->isUsableInConstantExpressions(Context))
1803       return NOUR_Constant;
1804   }
1805 
1806   // All remaining non-variable cases constitute an odr-use. For variables, we
1807   // need to wait and see how the expression is used.
1808   return NOUR_None;
1809 }
1810 
1811 /// BuildDeclRefExpr - Build an expression that references a
1812 /// declaration that does not require a closure capture.
1813 DeclRefExpr *
1814 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1815                        const DeclarationNameInfo &NameInfo,
1816                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1817                        SourceLocation TemplateKWLoc,
1818                        const TemplateArgumentListInfo *TemplateArgs) {
1819   bool RefersToCapturedVariable =
1820       isa<VarDecl>(D) &&
1821       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1822 
1823   DeclRefExpr *E = DeclRefExpr::Create(
1824       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1825       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1826   MarkDeclRefReferenced(E);
1827 
1828   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1829       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1830       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1831     getCurFunction()->recordUseOfWeak(E);
1832 
1833   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1834   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1835     FD = IFD->getAnonField();
1836   if (FD) {
1837     UnusedPrivateFields.remove(FD);
1838     // Just in case we're building an illegal pointer-to-member.
1839     if (FD->isBitField())
1840       E->setObjectKind(OK_BitField);
1841   }
1842 
1843   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1844   // designates a bit-field.
1845   if (auto *BD = dyn_cast<BindingDecl>(D))
1846     if (auto *BE = BD->getBinding())
1847       E->setObjectKind(BE->getObjectKind());
1848 
1849   return E;
1850 }
1851 
1852 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1853 /// possibly a list of template arguments.
1854 ///
1855 /// If this produces template arguments, it is permitted to call
1856 /// DecomposeTemplateName.
1857 ///
1858 /// This actually loses a lot of source location information for
1859 /// non-standard name kinds; we should consider preserving that in
1860 /// some way.
1861 void
1862 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1863                              TemplateArgumentListInfo &Buffer,
1864                              DeclarationNameInfo &NameInfo,
1865                              const TemplateArgumentListInfo *&TemplateArgs) {
1866   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1867     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1868     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1869 
1870     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1871                                        Id.TemplateId->NumArgs);
1872     translateTemplateArguments(TemplateArgsPtr, Buffer);
1873 
1874     TemplateName TName = Id.TemplateId->Template.get();
1875     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1876     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1877     TemplateArgs = &Buffer;
1878   } else {
1879     NameInfo = GetNameFromUnqualifiedId(Id);
1880     TemplateArgs = nullptr;
1881   }
1882 }
1883 
1884 static void emitEmptyLookupTypoDiagnostic(
1885     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1886     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1887     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1888   DeclContext *Ctx =
1889       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1890   if (!TC) {
1891     // Emit a special diagnostic for failed member lookups.
1892     // FIXME: computing the declaration context might fail here (?)
1893     if (Ctx)
1894       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1895                                                  << SS.getRange();
1896     else
1897       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1898     return;
1899   }
1900 
1901   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1902   bool DroppedSpecifier =
1903       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1904   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1905                         ? diag::note_implicit_param_decl
1906                         : diag::note_previous_decl;
1907   if (!Ctx)
1908     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1909                          SemaRef.PDiag(NoteID));
1910   else
1911     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1912                                  << Typo << Ctx << DroppedSpecifier
1913                                  << SS.getRange(),
1914                          SemaRef.PDiag(NoteID));
1915 }
1916 
1917 /// Diagnose an empty lookup.
1918 ///
1919 /// \return false if new lookup candidates were found
1920 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1921                                CorrectionCandidateCallback &CCC,
1922                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1923                                ArrayRef<Expr *> Args, TypoExpr **Out) {
1924   DeclarationName Name = R.getLookupName();
1925 
1926   unsigned diagnostic = diag::err_undeclared_var_use;
1927   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1928   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1929       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1930       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1931     diagnostic = diag::err_undeclared_use;
1932     diagnostic_suggest = diag::err_undeclared_use_suggest;
1933   }
1934 
1935   // If the original lookup was an unqualified lookup, fake an
1936   // unqualified lookup.  This is useful when (for example) the
1937   // original lookup would not have found something because it was a
1938   // dependent name.
1939   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1940   while (DC) {
1941     if (isa<CXXRecordDecl>(DC)) {
1942       LookupQualifiedName(R, DC);
1943 
1944       if (!R.empty()) {
1945         // Don't give errors about ambiguities in this lookup.
1946         R.suppressDiagnostics();
1947 
1948         // During a default argument instantiation the CurContext points
1949         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1950         // function parameter list, hence add an explicit check.
1951         bool isDefaultArgument =
1952             !CodeSynthesisContexts.empty() &&
1953             CodeSynthesisContexts.back().Kind ==
1954                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1955         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1956         bool isInstance = CurMethod &&
1957                           CurMethod->isInstance() &&
1958                           DC == CurMethod->getParent() && !isDefaultArgument;
1959 
1960         // Give a code modification hint to insert 'this->'.
1961         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1962         // Actually quite difficult!
1963         if (getLangOpts().MSVCCompat)
1964           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1965         if (isInstance) {
1966           Diag(R.getNameLoc(), diagnostic) << Name
1967             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1968           CheckCXXThisCapture(R.getNameLoc());
1969         } else {
1970           Diag(R.getNameLoc(), diagnostic) << Name;
1971         }
1972 
1973         // Do we really want to note all of these?
1974         for (NamedDecl *D : R)
1975           Diag(D->getLocation(), diag::note_dependent_var_use);
1976 
1977         // Return true if we are inside a default argument instantiation
1978         // and the found name refers to an instance member function, otherwise
1979         // the function calling DiagnoseEmptyLookup will try to create an
1980         // implicit member call and this is wrong for default argument.
1981         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1982           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1983           return true;
1984         }
1985 
1986         // Tell the callee to try to recover.
1987         return false;
1988       }
1989 
1990       R.clear();
1991     }
1992 
1993     DC = DC->getLookupParent();
1994   }
1995 
1996   // We didn't find anything, so try to correct for a typo.
1997   TypoCorrection Corrected;
1998   if (S && Out) {
1999     SourceLocation TypoLoc = R.getNameLoc();
2000     assert(!ExplicitTemplateArgs &&
2001            "Diagnosing an empty lookup with explicit template args!");
2002     *Out = CorrectTypoDelayed(
2003         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2004         [=](const TypoCorrection &TC) {
2005           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2006                                         diagnostic, diagnostic_suggest);
2007         },
2008         nullptr, CTK_ErrorRecovery);
2009     if (*Out)
2010       return true;
2011   } else if (S &&
2012              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2013                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2014     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2015     bool DroppedSpecifier =
2016         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2017     R.setLookupName(Corrected.getCorrection());
2018 
2019     bool AcceptableWithRecovery = false;
2020     bool AcceptableWithoutRecovery = false;
2021     NamedDecl *ND = Corrected.getFoundDecl();
2022     if (ND) {
2023       if (Corrected.isOverloaded()) {
2024         OverloadCandidateSet OCS(R.getNameLoc(),
2025                                  OverloadCandidateSet::CSK_Normal);
2026         OverloadCandidateSet::iterator Best;
2027         for (NamedDecl *CD : Corrected) {
2028           if (FunctionTemplateDecl *FTD =
2029                    dyn_cast<FunctionTemplateDecl>(CD))
2030             AddTemplateOverloadCandidate(
2031                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2032                 Args, OCS);
2033           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2034             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2035               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2036                                    Args, OCS);
2037         }
2038         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2039         case OR_Success:
2040           ND = Best->FoundDecl;
2041           Corrected.setCorrectionDecl(ND);
2042           break;
2043         default:
2044           // FIXME: Arbitrarily pick the first declaration for the note.
2045           Corrected.setCorrectionDecl(ND);
2046           break;
2047         }
2048       }
2049       R.addDecl(ND);
2050       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2051         CXXRecordDecl *Record = nullptr;
2052         if (Corrected.getCorrectionSpecifier()) {
2053           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2054           Record = Ty->getAsCXXRecordDecl();
2055         }
2056         if (!Record)
2057           Record = cast<CXXRecordDecl>(
2058               ND->getDeclContext()->getRedeclContext());
2059         R.setNamingClass(Record);
2060       }
2061 
2062       auto *UnderlyingND = ND->getUnderlyingDecl();
2063       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2064                                isa<FunctionTemplateDecl>(UnderlyingND);
2065       // FIXME: If we ended up with a typo for a type name or
2066       // Objective-C class name, we're in trouble because the parser
2067       // is in the wrong place to recover. Suggest the typo
2068       // correction, but don't make it a fix-it since we're not going
2069       // to recover well anyway.
2070       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2071                                   getAsTypeTemplateDecl(UnderlyingND) ||
2072                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2073     } else {
2074       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2075       // because we aren't able to recover.
2076       AcceptableWithoutRecovery = true;
2077     }
2078 
2079     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2080       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2081                             ? diag::note_implicit_param_decl
2082                             : diag::note_previous_decl;
2083       if (SS.isEmpty())
2084         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2085                      PDiag(NoteID), AcceptableWithRecovery);
2086       else
2087         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2088                                   << Name << computeDeclContext(SS, false)
2089                                   << DroppedSpecifier << SS.getRange(),
2090                      PDiag(NoteID), AcceptableWithRecovery);
2091 
2092       // Tell the callee whether to try to recover.
2093       return !AcceptableWithRecovery;
2094     }
2095   }
2096   R.clear();
2097 
2098   // Emit a special diagnostic for failed member lookups.
2099   // FIXME: computing the declaration context might fail here (?)
2100   if (!SS.isEmpty()) {
2101     Diag(R.getNameLoc(), diag::err_no_member)
2102       << Name << computeDeclContext(SS, false)
2103       << SS.getRange();
2104     return true;
2105   }
2106 
2107   // Give up, we can't recover.
2108   Diag(R.getNameLoc(), diagnostic) << Name;
2109   return true;
2110 }
2111 
2112 /// In Microsoft mode, if we are inside a template class whose parent class has
2113 /// dependent base classes, and we can't resolve an unqualified identifier, then
2114 /// assume the identifier is a member of a dependent base class.  We can only
2115 /// recover successfully in static methods, instance methods, and other contexts
2116 /// where 'this' is available.  This doesn't precisely match MSVC's
2117 /// instantiation model, but it's close enough.
2118 static Expr *
2119 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2120                                DeclarationNameInfo &NameInfo,
2121                                SourceLocation TemplateKWLoc,
2122                                const TemplateArgumentListInfo *TemplateArgs) {
2123   // Only try to recover from lookup into dependent bases in static methods or
2124   // contexts where 'this' is available.
2125   QualType ThisType = S.getCurrentThisType();
2126   const CXXRecordDecl *RD = nullptr;
2127   if (!ThisType.isNull())
2128     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2129   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2130     RD = MD->getParent();
2131   if (!RD || !RD->hasAnyDependentBases())
2132     return nullptr;
2133 
2134   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2135   // is available, suggest inserting 'this->' as a fixit.
2136   SourceLocation Loc = NameInfo.getLoc();
2137   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2138   DB << NameInfo.getName() << RD;
2139 
2140   if (!ThisType.isNull()) {
2141     DB << FixItHint::CreateInsertion(Loc, "this->");
2142     return CXXDependentScopeMemberExpr::Create(
2143         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2144         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2145         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2146   }
2147 
2148   // Synthesize a fake NNS that points to the derived class.  This will
2149   // perform name lookup during template instantiation.
2150   CXXScopeSpec SS;
2151   auto *NNS =
2152       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2153   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2154   return DependentScopeDeclRefExpr::Create(
2155       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2156       TemplateArgs);
2157 }
2158 
2159 ExprResult
2160 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2161                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2162                         bool HasTrailingLParen, bool IsAddressOfOperand,
2163                         CorrectionCandidateCallback *CCC,
2164                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2165   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2166          "cannot be direct & operand and have a trailing lparen");
2167   if (SS.isInvalid())
2168     return ExprError();
2169 
2170   TemplateArgumentListInfo TemplateArgsBuffer;
2171 
2172   // Decompose the UnqualifiedId into the following data.
2173   DeclarationNameInfo NameInfo;
2174   const TemplateArgumentListInfo *TemplateArgs;
2175   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2176 
2177   DeclarationName Name = NameInfo.getName();
2178   IdentifierInfo *II = Name.getAsIdentifierInfo();
2179   SourceLocation NameLoc = NameInfo.getLoc();
2180 
2181   if (II && II->isEditorPlaceholder()) {
2182     // FIXME: When typed placeholders are supported we can create a typed
2183     // placeholder expression node.
2184     return ExprError();
2185   }
2186 
2187   // C++ [temp.dep.expr]p3:
2188   //   An id-expression is type-dependent if it contains:
2189   //     -- an identifier that was declared with a dependent type,
2190   //        (note: handled after lookup)
2191   //     -- a template-id that is dependent,
2192   //        (note: handled in BuildTemplateIdExpr)
2193   //     -- a conversion-function-id that specifies a dependent type,
2194   //     -- a nested-name-specifier that contains a class-name that
2195   //        names a dependent type.
2196   // Determine whether this is a member of an unknown specialization;
2197   // we need to handle these differently.
2198   bool DependentID = false;
2199   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2200       Name.getCXXNameType()->isDependentType()) {
2201     DependentID = true;
2202   } else if (SS.isSet()) {
2203     if (DeclContext *DC = computeDeclContext(SS, false)) {
2204       if (RequireCompleteDeclContext(SS, DC))
2205         return ExprError();
2206     } else {
2207       DependentID = true;
2208     }
2209   }
2210 
2211   if (DependentID)
2212     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2213                                       IsAddressOfOperand, TemplateArgs);
2214 
2215   // Perform the required lookup.
2216   LookupResult R(*this, NameInfo,
2217                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2218                      ? LookupObjCImplicitSelfParam
2219                      : LookupOrdinaryName);
2220   if (TemplateKWLoc.isValid() || TemplateArgs) {
2221     // Lookup the template name again to correctly establish the context in
2222     // which it was found. This is really unfortunate as we already did the
2223     // lookup to determine that it was a template name in the first place. If
2224     // this becomes a performance hit, we can work harder to preserve those
2225     // results until we get here but it's likely not worth it.
2226     bool MemberOfUnknownSpecialization;
2227     AssumedTemplateKind AssumedTemplate;
2228     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2229                            MemberOfUnknownSpecialization, TemplateKWLoc,
2230                            &AssumedTemplate))
2231       return ExprError();
2232 
2233     if (MemberOfUnknownSpecialization ||
2234         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2235       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2236                                         IsAddressOfOperand, TemplateArgs);
2237   } else {
2238     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2239     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2240 
2241     // If the result might be in a dependent base class, this is a dependent
2242     // id-expression.
2243     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2244       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2245                                         IsAddressOfOperand, TemplateArgs);
2246 
2247     // If this reference is in an Objective-C method, then we need to do
2248     // some special Objective-C lookup, too.
2249     if (IvarLookupFollowUp) {
2250       ExprResult E(LookupInObjCMethod(R, S, II, true));
2251       if (E.isInvalid())
2252         return ExprError();
2253 
2254       if (Expr *Ex = E.getAs<Expr>())
2255         return Ex;
2256     }
2257   }
2258 
2259   if (R.isAmbiguous())
2260     return ExprError();
2261 
2262   // This could be an implicitly declared function reference (legal in C90,
2263   // extension in C99, forbidden in C++).
2264   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2265     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2266     if (D) R.addDecl(D);
2267   }
2268 
2269   // Determine whether this name might be a candidate for
2270   // argument-dependent lookup.
2271   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2272 
2273   if (R.empty() && !ADL) {
2274     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2275       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2276                                                    TemplateKWLoc, TemplateArgs))
2277         return E;
2278     }
2279 
2280     // Don't diagnose an empty lookup for inline assembly.
2281     if (IsInlineAsmIdentifier)
2282       return ExprError();
2283 
2284     // If this name wasn't predeclared and if this is not a function
2285     // call, diagnose the problem.
2286     TypoExpr *TE = nullptr;
2287     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2288                                                        : nullptr);
2289     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2290     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2291            "Typo correction callback misconfigured");
2292     if (CCC) {
2293       // Make sure the callback knows what the typo being diagnosed is.
2294       CCC->setTypoName(II);
2295       if (SS.isValid())
2296         CCC->setTypoNNS(SS.getScopeRep());
2297     }
2298     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2299     // a template name, but we happen to have always already looked up the name
2300     // before we get here if it must be a template name.
2301     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2302                             None, &TE)) {
2303       if (TE && KeywordReplacement) {
2304         auto &State = getTypoExprState(TE);
2305         auto BestTC = State.Consumer->getNextCorrection();
2306         if (BestTC.isKeyword()) {
2307           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2308           if (State.DiagHandler)
2309             State.DiagHandler(BestTC);
2310           KeywordReplacement->startToken();
2311           KeywordReplacement->setKind(II->getTokenID());
2312           KeywordReplacement->setIdentifierInfo(II);
2313           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2314           // Clean up the state associated with the TypoExpr, since it has
2315           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2316           clearDelayedTypo(TE);
2317           // Signal that a correction to a keyword was performed by returning a
2318           // valid-but-null ExprResult.
2319           return (Expr*)nullptr;
2320         }
2321         State.Consumer->resetCorrectionStream();
2322       }
2323       return TE ? TE : ExprError();
2324     }
2325 
2326     assert(!R.empty() &&
2327            "DiagnoseEmptyLookup returned false but added no results");
2328 
2329     // If we found an Objective-C instance variable, let
2330     // LookupInObjCMethod build the appropriate expression to
2331     // reference the ivar.
2332     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2333       R.clear();
2334       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2335       // In a hopelessly buggy code, Objective-C instance variable
2336       // lookup fails and no expression will be built to reference it.
2337       if (!E.isInvalid() && !E.get())
2338         return ExprError();
2339       return E;
2340     }
2341   }
2342 
2343   // This is guaranteed from this point on.
2344   assert(!R.empty() || ADL);
2345 
2346   // Check whether this might be a C++ implicit instance member access.
2347   // C++ [class.mfct.non-static]p3:
2348   //   When an id-expression that is not part of a class member access
2349   //   syntax and not used to form a pointer to member is used in the
2350   //   body of a non-static member function of class X, if name lookup
2351   //   resolves the name in the id-expression to a non-static non-type
2352   //   member of some class C, the id-expression is transformed into a
2353   //   class member access expression using (*this) as the
2354   //   postfix-expression to the left of the . operator.
2355   //
2356   // But we don't actually need to do this for '&' operands if R
2357   // resolved to a function or overloaded function set, because the
2358   // expression is ill-formed if it actually works out to be a
2359   // non-static member function:
2360   //
2361   // C++ [expr.ref]p4:
2362   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2363   //   [t]he expression can be used only as the left-hand operand of a
2364   //   member function call.
2365   //
2366   // There are other safeguards against such uses, but it's important
2367   // to get this right here so that we don't end up making a
2368   // spuriously dependent expression if we're inside a dependent
2369   // instance method.
2370   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2371     bool MightBeImplicitMember;
2372     if (!IsAddressOfOperand)
2373       MightBeImplicitMember = true;
2374     else if (!SS.isEmpty())
2375       MightBeImplicitMember = false;
2376     else if (R.isOverloadedResult())
2377       MightBeImplicitMember = false;
2378     else if (R.isUnresolvableResult())
2379       MightBeImplicitMember = true;
2380     else
2381       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2382                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2383                               isa<MSPropertyDecl>(R.getFoundDecl());
2384 
2385     if (MightBeImplicitMember)
2386       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2387                                              R, TemplateArgs, S);
2388   }
2389 
2390   if (TemplateArgs || TemplateKWLoc.isValid()) {
2391 
2392     // In C++1y, if this is a variable template id, then check it
2393     // in BuildTemplateIdExpr().
2394     // The single lookup result must be a variable template declaration.
2395     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2396         Id.TemplateId->Kind == TNK_Var_template) {
2397       assert(R.getAsSingle<VarTemplateDecl>() &&
2398              "There should only be one declaration found.");
2399     }
2400 
2401     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2402   }
2403 
2404   return BuildDeclarationNameExpr(SS, R, ADL);
2405 }
2406 
2407 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2408 /// declaration name, generally during template instantiation.
2409 /// There's a large number of things which don't need to be done along
2410 /// this path.
2411 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2412     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2413     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2414   DeclContext *DC = computeDeclContext(SS, false);
2415   if (!DC)
2416     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2417                                      NameInfo, /*TemplateArgs=*/nullptr);
2418 
2419   if (RequireCompleteDeclContext(SS, DC))
2420     return ExprError();
2421 
2422   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2423   LookupQualifiedName(R, DC);
2424 
2425   if (R.isAmbiguous())
2426     return ExprError();
2427 
2428   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2429     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2430                                      NameInfo, /*TemplateArgs=*/nullptr);
2431 
2432   if (R.empty()) {
2433     Diag(NameInfo.getLoc(), diag::err_no_member)
2434       << NameInfo.getName() << DC << SS.getRange();
2435     return ExprError();
2436   }
2437 
2438   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2439     // Diagnose a missing typename if this resolved unambiguously to a type in
2440     // a dependent context.  If we can recover with a type, downgrade this to
2441     // a warning in Microsoft compatibility mode.
2442     unsigned DiagID = diag::err_typename_missing;
2443     if (RecoveryTSI && getLangOpts().MSVCCompat)
2444       DiagID = diag::ext_typename_missing;
2445     SourceLocation Loc = SS.getBeginLoc();
2446     auto D = Diag(Loc, DiagID);
2447     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2448       << SourceRange(Loc, NameInfo.getEndLoc());
2449 
2450     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2451     // context.
2452     if (!RecoveryTSI)
2453       return ExprError();
2454 
2455     // Only issue the fixit if we're prepared to recover.
2456     D << FixItHint::CreateInsertion(Loc, "typename ");
2457 
2458     // Recover by pretending this was an elaborated type.
2459     QualType Ty = Context.getTypeDeclType(TD);
2460     TypeLocBuilder TLB;
2461     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2462 
2463     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2464     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2465     QTL.setElaboratedKeywordLoc(SourceLocation());
2466     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2467 
2468     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2469 
2470     return ExprEmpty();
2471   }
2472 
2473   // Defend against this resolving to an implicit member access. We usually
2474   // won't get here if this might be a legitimate a class member (we end up in
2475   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2476   // a pointer-to-member or in an unevaluated context in C++11.
2477   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2478     return BuildPossibleImplicitMemberExpr(SS,
2479                                            /*TemplateKWLoc=*/SourceLocation(),
2480                                            R, /*TemplateArgs=*/nullptr, S);
2481 
2482   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2483 }
2484 
2485 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2486 /// detected that we're currently inside an ObjC method.  Perform some
2487 /// additional lookup.
2488 ///
2489 /// Ideally, most of this would be done by lookup, but there's
2490 /// actually quite a lot of extra work involved.
2491 ///
2492 /// Returns a null sentinel to indicate trivial success.
2493 ExprResult
2494 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2495                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2496   SourceLocation Loc = Lookup.getNameLoc();
2497   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2498 
2499   // Check for error condition which is already reported.
2500   if (!CurMethod)
2501     return ExprError();
2502 
2503   // There are two cases to handle here.  1) scoped lookup could have failed,
2504   // in which case we should look for an ivar.  2) scoped lookup could have
2505   // found a decl, but that decl is outside the current instance method (i.e.
2506   // a global variable).  In these two cases, we do a lookup for an ivar with
2507   // this name, if the lookup sucedes, we replace it our current decl.
2508 
2509   // If we're in a class method, we don't normally want to look for
2510   // ivars.  But if we don't find anything else, and there's an
2511   // ivar, that's an error.
2512   bool IsClassMethod = CurMethod->isClassMethod();
2513 
2514   bool LookForIvars;
2515   if (Lookup.empty())
2516     LookForIvars = true;
2517   else if (IsClassMethod)
2518     LookForIvars = false;
2519   else
2520     LookForIvars = (Lookup.isSingleResult() &&
2521                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2522   ObjCInterfaceDecl *IFace = nullptr;
2523   if (LookForIvars) {
2524     IFace = CurMethod->getClassInterface();
2525     ObjCInterfaceDecl *ClassDeclared;
2526     ObjCIvarDecl *IV = nullptr;
2527     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2528       // Diagnose using an ivar in a class method.
2529       if (IsClassMethod)
2530         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2531                          << IV->getDeclName());
2532 
2533       // If we're referencing an invalid decl, just return this as a silent
2534       // error node.  The error diagnostic was already emitted on the decl.
2535       if (IV->isInvalidDecl())
2536         return ExprError();
2537 
2538       // Check if referencing a field with __attribute__((deprecated)).
2539       if (DiagnoseUseOfDecl(IV, Loc))
2540         return ExprError();
2541 
2542       // Diagnose the use of an ivar outside of the declaring class.
2543       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2544           !declaresSameEntity(ClassDeclared, IFace) &&
2545           !getLangOpts().DebuggerSupport)
2546         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2547 
2548       // FIXME: This should use a new expr for a direct reference, don't
2549       // turn this into Self->ivar, just return a BareIVarExpr or something.
2550       IdentifierInfo &II = Context.Idents.get("self");
2551       UnqualifiedId SelfName;
2552       SelfName.setIdentifier(&II, SourceLocation());
2553       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2554       CXXScopeSpec SelfScopeSpec;
2555       SourceLocation TemplateKWLoc;
2556       ExprResult SelfExpr =
2557           ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2558                             /*HasTrailingLParen=*/false,
2559                             /*IsAddressOfOperand=*/false);
2560       if (SelfExpr.isInvalid())
2561         return ExprError();
2562 
2563       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2564       if (SelfExpr.isInvalid())
2565         return ExprError();
2566 
2567       MarkAnyDeclReferenced(Loc, IV, true);
2568 
2569       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2570       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2571           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2572         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2573 
2574       ObjCIvarRefExpr *Result = new (Context)
2575           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2576                           IV->getLocation(), SelfExpr.get(), true, true);
2577 
2578       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2579         if (!isUnevaluatedContext() &&
2580             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2581           getCurFunction()->recordUseOfWeak(Result);
2582       }
2583       if (getLangOpts().ObjCAutoRefCount)
2584         if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2585           ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2586 
2587       return Result;
2588     }
2589   } else if (CurMethod->isInstanceMethod()) {
2590     // We should warn if a local variable hides an ivar.
2591     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2592       ObjCInterfaceDecl *ClassDeclared;
2593       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2594         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2595             declaresSameEntity(IFace, ClassDeclared))
2596           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2597       }
2598     }
2599   } else if (Lookup.isSingleResult() &&
2600              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2601     // If accessing a stand-alone ivar in a class method, this is an error.
2602     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2603       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2604                        << IV->getDeclName());
2605   }
2606 
2607   if (Lookup.empty() && II && AllowBuiltinCreation) {
2608     // FIXME. Consolidate this with similar code in LookupName.
2609     if (unsigned BuiltinID = II->getBuiltinID()) {
2610       if (!(getLangOpts().CPlusPlus &&
2611             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2612         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2613                                            S, Lookup.isForRedeclaration(),
2614                                            Lookup.getNameLoc());
2615         if (D) Lookup.addDecl(D);
2616       }
2617     }
2618   }
2619   // Sentinel value saying that we didn't do anything special.
2620   return ExprResult((Expr *)nullptr);
2621 }
2622 
2623 /// Cast a base object to a member's actual type.
2624 ///
2625 /// Logically this happens in three phases:
2626 ///
2627 /// * First we cast from the base type to the naming class.
2628 ///   The naming class is the class into which we were looking
2629 ///   when we found the member;  it's the qualifier type if a
2630 ///   qualifier was provided, and otherwise it's the base type.
2631 ///
2632 /// * Next we cast from the naming class to the declaring class.
2633 ///   If the member we found was brought into a class's scope by
2634 ///   a using declaration, this is that class;  otherwise it's
2635 ///   the class declaring the member.
2636 ///
2637 /// * Finally we cast from the declaring class to the "true"
2638 ///   declaring class of the member.  This conversion does not
2639 ///   obey access control.
2640 ExprResult
2641 Sema::PerformObjectMemberConversion(Expr *From,
2642                                     NestedNameSpecifier *Qualifier,
2643                                     NamedDecl *FoundDecl,
2644                                     NamedDecl *Member) {
2645   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2646   if (!RD)
2647     return From;
2648 
2649   QualType DestRecordType;
2650   QualType DestType;
2651   QualType FromRecordType;
2652   QualType FromType = From->getType();
2653   bool PointerConversions = false;
2654   if (isa<FieldDecl>(Member)) {
2655     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2656     auto FromPtrType = FromType->getAs<PointerType>();
2657     DestRecordType = Context.getAddrSpaceQualType(
2658         DestRecordType, FromPtrType
2659                             ? FromType->getPointeeType().getAddressSpace()
2660                             : FromType.getAddressSpace());
2661 
2662     if (FromPtrType) {
2663       DestType = Context.getPointerType(DestRecordType);
2664       FromRecordType = FromPtrType->getPointeeType();
2665       PointerConversions = true;
2666     } else {
2667       DestType = DestRecordType;
2668       FromRecordType = FromType;
2669     }
2670   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2671     if (Method->isStatic())
2672       return From;
2673 
2674     DestType = Method->getThisType();
2675     DestRecordType = DestType->getPointeeType();
2676 
2677     if (FromType->getAs<PointerType>()) {
2678       FromRecordType = FromType->getPointeeType();
2679       PointerConversions = true;
2680     } else {
2681       FromRecordType = FromType;
2682       DestType = DestRecordType;
2683     }
2684   } else {
2685     // No conversion necessary.
2686     return From;
2687   }
2688 
2689   if (DestType->isDependentType() || FromType->isDependentType())
2690     return From;
2691 
2692   // If the unqualified types are the same, no conversion is necessary.
2693   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2694     return From;
2695 
2696   SourceRange FromRange = From->getSourceRange();
2697   SourceLocation FromLoc = FromRange.getBegin();
2698 
2699   ExprValueKind VK = From->getValueKind();
2700 
2701   // C++ [class.member.lookup]p8:
2702   //   [...] Ambiguities can often be resolved by qualifying a name with its
2703   //   class name.
2704   //
2705   // If the member was a qualified name and the qualified referred to a
2706   // specific base subobject type, we'll cast to that intermediate type
2707   // first and then to the object in which the member is declared. That allows
2708   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2709   //
2710   //   class Base { public: int x; };
2711   //   class Derived1 : public Base { };
2712   //   class Derived2 : public Base { };
2713   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2714   //
2715   //   void VeryDerived::f() {
2716   //     x = 17; // error: ambiguous base subobjects
2717   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2718   //   }
2719   if (Qualifier && Qualifier->getAsType()) {
2720     QualType QType = QualType(Qualifier->getAsType(), 0);
2721     assert(QType->isRecordType() && "lookup done with non-record type");
2722 
2723     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2724 
2725     // In C++98, the qualifier type doesn't actually have to be a base
2726     // type of the object type, in which case we just ignore it.
2727     // Otherwise build the appropriate casts.
2728     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2729       CXXCastPath BasePath;
2730       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2731                                        FromLoc, FromRange, &BasePath))
2732         return ExprError();
2733 
2734       if (PointerConversions)
2735         QType = Context.getPointerType(QType);
2736       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2737                                VK, &BasePath).get();
2738 
2739       FromType = QType;
2740       FromRecordType = QRecordType;
2741 
2742       // If the qualifier type was the same as the destination type,
2743       // we're done.
2744       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2745         return From;
2746     }
2747   }
2748 
2749   bool IgnoreAccess = false;
2750 
2751   // If we actually found the member through a using declaration, cast
2752   // down to the using declaration's type.
2753   //
2754   // Pointer equality is fine here because only one declaration of a
2755   // class ever has member declarations.
2756   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2757     assert(isa<UsingShadowDecl>(FoundDecl));
2758     QualType URecordType = Context.getTypeDeclType(
2759                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2760 
2761     // We only need to do this if the naming-class to declaring-class
2762     // conversion is non-trivial.
2763     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2764       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2765       CXXCastPath BasePath;
2766       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2767                                        FromLoc, FromRange, &BasePath))
2768         return ExprError();
2769 
2770       QualType UType = URecordType;
2771       if (PointerConversions)
2772         UType = Context.getPointerType(UType);
2773       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2774                                VK, &BasePath).get();
2775       FromType = UType;
2776       FromRecordType = URecordType;
2777     }
2778 
2779     // We don't do access control for the conversion from the
2780     // declaring class to the true declaring class.
2781     IgnoreAccess = true;
2782   }
2783 
2784   CXXCastPath BasePath;
2785   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2786                                    FromLoc, FromRange, &BasePath,
2787                                    IgnoreAccess))
2788     return ExprError();
2789 
2790   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2791                            VK, &BasePath);
2792 }
2793 
2794 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2795                                       const LookupResult &R,
2796                                       bool HasTrailingLParen) {
2797   // Only when used directly as the postfix-expression of a call.
2798   if (!HasTrailingLParen)
2799     return false;
2800 
2801   // Never if a scope specifier was provided.
2802   if (SS.isSet())
2803     return false;
2804 
2805   // Only in C++ or ObjC++.
2806   if (!getLangOpts().CPlusPlus)
2807     return false;
2808 
2809   // Turn off ADL when we find certain kinds of declarations during
2810   // normal lookup:
2811   for (NamedDecl *D : R) {
2812     // C++0x [basic.lookup.argdep]p3:
2813     //     -- a declaration of a class member
2814     // Since using decls preserve this property, we check this on the
2815     // original decl.
2816     if (D->isCXXClassMember())
2817       return false;
2818 
2819     // C++0x [basic.lookup.argdep]p3:
2820     //     -- a block-scope function declaration that is not a
2821     //        using-declaration
2822     // NOTE: we also trigger this for function templates (in fact, we
2823     // don't check the decl type at all, since all other decl types
2824     // turn off ADL anyway).
2825     if (isa<UsingShadowDecl>(D))
2826       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2827     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2828       return false;
2829 
2830     // C++0x [basic.lookup.argdep]p3:
2831     //     -- a declaration that is neither a function or a function
2832     //        template
2833     // And also for builtin functions.
2834     if (isa<FunctionDecl>(D)) {
2835       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2836 
2837       // But also builtin functions.
2838       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2839         return false;
2840     } else if (!isa<FunctionTemplateDecl>(D))
2841       return false;
2842   }
2843 
2844   return true;
2845 }
2846 
2847 
2848 /// Diagnoses obvious problems with the use of the given declaration
2849 /// as an expression.  This is only actually called for lookups that
2850 /// were not overloaded, and it doesn't promise that the declaration
2851 /// will in fact be used.
2852 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2853   if (D->isInvalidDecl())
2854     return true;
2855 
2856   if (isa<TypedefNameDecl>(D)) {
2857     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2858     return true;
2859   }
2860 
2861   if (isa<ObjCInterfaceDecl>(D)) {
2862     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2863     return true;
2864   }
2865 
2866   if (isa<NamespaceDecl>(D)) {
2867     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2868     return true;
2869   }
2870 
2871   return false;
2872 }
2873 
2874 // Certain multiversion types should be treated as overloaded even when there is
2875 // only one result.
2876 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2877   assert(R.isSingleResult() && "Expected only a single result");
2878   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2879   return FD &&
2880          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2881 }
2882 
2883 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2884                                           LookupResult &R, bool NeedsADL,
2885                                           bool AcceptInvalidDecl) {
2886   // If this is a single, fully-resolved result and we don't need ADL,
2887   // just build an ordinary singleton decl ref.
2888   if (!NeedsADL && R.isSingleResult() &&
2889       !R.getAsSingle<FunctionTemplateDecl>() &&
2890       !ShouldLookupResultBeMultiVersionOverload(R))
2891     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2892                                     R.getRepresentativeDecl(), nullptr,
2893                                     AcceptInvalidDecl);
2894 
2895   // We only need to check the declaration if there's exactly one
2896   // result, because in the overloaded case the results can only be
2897   // functions and function templates.
2898   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2899       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2900     return ExprError();
2901 
2902   // Otherwise, just build an unresolved lookup expression.  Suppress
2903   // any lookup-related diagnostics; we'll hash these out later, when
2904   // we've picked a target.
2905   R.suppressDiagnostics();
2906 
2907   UnresolvedLookupExpr *ULE
2908     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2909                                    SS.getWithLocInContext(Context),
2910                                    R.getLookupNameInfo(),
2911                                    NeedsADL, R.isOverloadedResult(),
2912                                    R.begin(), R.end());
2913 
2914   return ULE;
2915 }
2916 
2917 static void
2918 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2919                                    ValueDecl *var, DeclContext *DC);
2920 
2921 /// Complete semantic analysis for a reference to the given declaration.
2922 ExprResult Sema::BuildDeclarationNameExpr(
2923     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2924     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2925     bool AcceptInvalidDecl) {
2926   assert(D && "Cannot refer to a NULL declaration");
2927   assert(!isa<FunctionTemplateDecl>(D) &&
2928          "Cannot refer unambiguously to a function template");
2929 
2930   SourceLocation Loc = NameInfo.getLoc();
2931   if (CheckDeclInExpr(*this, Loc, D))
2932     return ExprError();
2933 
2934   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2935     // Specifically diagnose references to class templates that are missing
2936     // a template argument list.
2937     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2938     return ExprError();
2939   }
2940 
2941   // Make sure that we're referring to a value.
2942   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2943   if (!VD) {
2944     Diag(Loc, diag::err_ref_non_value)
2945       << D << SS.getRange();
2946     Diag(D->getLocation(), diag::note_declared_at);
2947     return ExprError();
2948   }
2949 
2950   // Check whether this declaration can be used. Note that we suppress
2951   // this check when we're going to perform argument-dependent lookup
2952   // on this function name, because this might not be the function
2953   // that overload resolution actually selects.
2954   if (DiagnoseUseOfDecl(VD, Loc))
2955     return ExprError();
2956 
2957   // Only create DeclRefExpr's for valid Decl's.
2958   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2959     return ExprError();
2960 
2961   // Handle members of anonymous structs and unions.  If we got here,
2962   // and the reference is to a class member indirect field, then this
2963   // must be the subject of a pointer-to-member expression.
2964   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2965     if (!indirectField->isCXXClassMember())
2966       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2967                                                       indirectField);
2968 
2969   {
2970     QualType type = VD->getType();
2971     if (type.isNull())
2972       return ExprError();
2973     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2974       // C++ [except.spec]p17:
2975       //   An exception-specification is considered to be needed when:
2976       //   - in an expression, the function is the unique lookup result or
2977       //     the selected member of a set of overloaded functions.
2978       ResolveExceptionSpec(Loc, FPT);
2979       type = VD->getType();
2980     }
2981     ExprValueKind valueKind = VK_RValue;
2982 
2983     switch (D->getKind()) {
2984     // Ignore all the non-ValueDecl kinds.
2985 #define ABSTRACT_DECL(kind)
2986 #define VALUE(type, base)
2987 #define DECL(type, base) \
2988     case Decl::type:
2989 #include "clang/AST/DeclNodes.inc"
2990       llvm_unreachable("invalid value decl kind");
2991 
2992     // These shouldn't make it here.
2993     case Decl::ObjCAtDefsField:
2994       llvm_unreachable("forming non-member reference to ivar?");
2995 
2996     // Enum constants are always r-values and never references.
2997     // Unresolved using declarations are dependent.
2998     case Decl::EnumConstant:
2999     case Decl::UnresolvedUsingValue:
3000     case Decl::OMPDeclareReduction:
3001     case Decl::OMPDeclareMapper:
3002       valueKind = VK_RValue;
3003       break;
3004 
3005     // Fields and indirect fields that got here must be for
3006     // pointer-to-member expressions; we just call them l-values for
3007     // internal consistency, because this subexpression doesn't really
3008     // exist in the high-level semantics.
3009     case Decl::Field:
3010     case Decl::IndirectField:
3011     case Decl::ObjCIvar:
3012       assert(getLangOpts().CPlusPlus &&
3013              "building reference to field in C?");
3014 
3015       // These can't have reference type in well-formed programs, but
3016       // for internal consistency we do this anyway.
3017       type = type.getNonReferenceType();
3018       valueKind = VK_LValue;
3019       break;
3020 
3021     // Non-type template parameters are either l-values or r-values
3022     // depending on the type.
3023     case Decl::NonTypeTemplateParm: {
3024       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3025         type = reftype->getPointeeType();
3026         valueKind = VK_LValue; // even if the parameter is an r-value reference
3027         break;
3028       }
3029 
3030       // For non-references, we need to strip qualifiers just in case
3031       // the template parameter was declared as 'const int' or whatever.
3032       valueKind = VK_RValue;
3033       type = type.getUnqualifiedType();
3034       break;
3035     }
3036 
3037     case Decl::Var:
3038     case Decl::VarTemplateSpecialization:
3039     case Decl::VarTemplatePartialSpecialization:
3040     case Decl::Decomposition:
3041     case Decl::OMPCapturedExpr:
3042       // In C, "extern void blah;" is valid and is an r-value.
3043       if (!getLangOpts().CPlusPlus &&
3044           !type.hasQualifiers() &&
3045           type->isVoidType()) {
3046         valueKind = VK_RValue;
3047         break;
3048       }
3049       LLVM_FALLTHROUGH;
3050 
3051     case Decl::ImplicitParam:
3052     case Decl::ParmVar: {
3053       // These are always l-values.
3054       valueKind = VK_LValue;
3055       type = type.getNonReferenceType();
3056 
3057       // FIXME: Does the addition of const really only apply in
3058       // potentially-evaluated contexts? Since the variable isn't actually
3059       // captured in an unevaluated context, it seems that the answer is no.
3060       if (!isUnevaluatedContext()) {
3061         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3062         if (!CapturedType.isNull())
3063           type = CapturedType;
3064       }
3065 
3066       break;
3067     }
3068 
3069     case Decl::Binding: {
3070       // These are always lvalues.
3071       valueKind = VK_LValue;
3072       type = type.getNonReferenceType();
3073       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3074       // decides how that's supposed to work.
3075       auto *BD = cast<BindingDecl>(VD);
3076       if (BD->getDeclContext() != CurContext) {
3077         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3078         if (DD && DD->hasLocalStorage())
3079           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3080       }
3081       break;
3082     }
3083 
3084     case Decl::Function: {
3085       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3086         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3087           type = Context.BuiltinFnTy;
3088           valueKind = VK_RValue;
3089           break;
3090         }
3091       }
3092 
3093       const FunctionType *fty = type->castAs<FunctionType>();
3094 
3095       // If we're referring to a function with an __unknown_anytype
3096       // result type, make the entire expression __unknown_anytype.
3097       if (fty->getReturnType() == Context.UnknownAnyTy) {
3098         type = Context.UnknownAnyTy;
3099         valueKind = VK_RValue;
3100         break;
3101       }
3102 
3103       // Functions are l-values in C++.
3104       if (getLangOpts().CPlusPlus) {
3105         valueKind = VK_LValue;
3106         break;
3107       }
3108 
3109       // C99 DR 316 says that, if a function type comes from a
3110       // function definition (without a prototype), that type is only
3111       // used for checking compatibility. Therefore, when referencing
3112       // the function, we pretend that we don't have the full function
3113       // type.
3114       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3115           isa<FunctionProtoType>(fty))
3116         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3117                                               fty->getExtInfo());
3118 
3119       // Functions are r-values in C.
3120       valueKind = VK_RValue;
3121       break;
3122     }
3123 
3124     case Decl::CXXDeductionGuide:
3125       llvm_unreachable("building reference to deduction guide");
3126 
3127     case Decl::MSProperty:
3128       valueKind = VK_LValue;
3129       break;
3130 
3131     case Decl::CXXMethod:
3132       // If we're referring to a method with an __unknown_anytype
3133       // result type, make the entire expression __unknown_anytype.
3134       // This should only be possible with a type written directly.
3135       if (const FunctionProtoType *proto
3136             = dyn_cast<FunctionProtoType>(VD->getType()))
3137         if (proto->getReturnType() == Context.UnknownAnyTy) {
3138           type = Context.UnknownAnyTy;
3139           valueKind = VK_RValue;
3140           break;
3141         }
3142 
3143       // C++ methods are l-values if static, r-values if non-static.
3144       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3145         valueKind = VK_LValue;
3146         break;
3147       }
3148       LLVM_FALLTHROUGH;
3149 
3150     case Decl::CXXConversion:
3151     case Decl::CXXDestructor:
3152     case Decl::CXXConstructor:
3153       valueKind = VK_RValue;
3154       break;
3155     }
3156 
3157     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3158                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3159                             TemplateArgs);
3160   }
3161 }
3162 
3163 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3164                                     SmallString<32> &Target) {
3165   Target.resize(CharByteWidth * (Source.size() + 1));
3166   char *ResultPtr = &Target[0];
3167   const llvm::UTF8 *ErrorPtr;
3168   bool success =
3169       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3170   (void)success;
3171   assert(success);
3172   Target.resize(ResultPtr - &Target[0]);
3173 }
3174 
3175 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3176                                      PredefinedExpr::IdentKind IK) {
3177   // Pick the current block, lambda, captured statement or function.
3178   Decl *currentDecl = nullptr;
3179   if (const BlockScopeInfo *BSI = getCurBlock())
3180     currentDecl = BSI->TheDecl;
3181   else if (const LambdaScopeInfo *LSI = getCurLambda())
3182     currentDecl = LSI->CallOperator;
3183   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3184     currentDecl = CSI->TheCapturedDecl;
3185   else
3186     currentDecl = getCurFunctionOrMethodDecl();
3187 
3188   if (!currentDecl) {
3189     Diag(Loc, diag::ext_predef_outside_function);
3190     currentDecl = Context.getTranslationUnitDecl();
3191   }
3192 
3193   QualType ResTy;
3194   StringLiteral *SL = nullptr;
3195   if (cast<DeclContext>(currentDecl)->isDependentContext())
3196     ResTy = Context.DependentTy;
3197   else {
3198     // Pre-defined identifiers are of type char[x], where x is the length of
3199     // the string.
3200     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3201     unsigned Length = Str.length();
3202 
3203     llvm::APInt LengthI(32, Length + 1);
3204     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3205       ResTy =
3206           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3207       SmallString<32> RawChars;
3208       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3209                               Str, RawChars);
3210       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3211                                            ArrayType::Normal,
3212                                            /*IndexTypeQuals*/ 0);
3213       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3214                                  /*Pascal*/ false, ResTy, Loc);
3215     } else {
3216       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3217       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3218                                            ArrayType::Normal,
3219                                            /*IndexTypeQuals*/ 0);
3220       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3221                                  /*Pascal*/ false, ResTy, Loc);
3222     }
3223   }
3224 
3225   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3226 }
3227 
3228 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3229   PredefinedExpr::IdentKind IK;
3230 
3231   switch (Kind) {
3232   default: llvm_unreachable("Unknown simple primary expr!");
3233   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3234   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3235   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3236   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3237   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3238   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3239   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3240   }
3241 
3242   return BuildPredefinedExpr(Loc, IK);
3243 }
3244 
3245 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3246   SmallString<16> CharBuffer;
3247   bool Invalid = false;
3248   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3249   if (Invalid)
3250     return ExprError();
3251 
3252   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3253                             PP, Tok.getKind());
3254   if (Literal.hadError())
3255     return ExprError();
3256 
3257   QualType Ty;
3258   if (Literal.isWide())
3259     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3260   else if (Literal.isUTF8() && getLangOpts().Char8)
3261     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3262   else if (Literal.isUTF16())
3263     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3264   else if (Literal.isUTF32())
3265     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3266   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3267     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3268   else
3269     Ty = Context.CharTy;  // 'x' -> char in C++
3270 
3271   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3272   if (Literal.isWide())
3273     Kind = CharacterLiteral::Wide;
3274   else if (Literal.isUTF16())
3275     Kind = CharacterLiteral::UTF16;
3276   else if (Literal.isUTF32())
3277     Kind = CharacterLiteral::UTF32;
3278   else if (Literal.isUTF8())
3279     Kind = CharacterLiteral::UTF8;
3280 
3281   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3282                                              Tok.getLocation());
3283 
3284   if (Literal.getUDSuffix().empty())
3285     return Lit;
3286 
3287   // We're building a user-defined literal.
3288   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3289   SourceLocation UDSuffixLoc =
3290     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3291 
3292   // Make sure we're allowed user-defined literals here.
3293   if (!UDLScope)
3294     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3295 
3296   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3297   //   operator "" X (ch)
3298   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3299                                         Lit, Tok.getLocation());
3300 }
3301 
3302 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3303   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3304   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3305                                 Context.IntTy, Loc);
3306 }
3307 
3308 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3309                                   QualType Ty, SourceLocation Loc) {
3310   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3311 
3312   using llvm::APFloat;
3313   APFloat Val(Format);
3314 
3315   APFloat::opStatus result = Literal.GetFloatValue(Val);
3316 
3317   // Overflow is always an error, but underflow is only an error if
3318   // we underflowed to zero (APFloat reports denormals as underflow).
3319   if ((result & APFloat::opOverflow) ||
3320       ((result & APFloat::opUnderflow) && Val.isZero())) {
3321     unsigned diagnostic;
3322     SmallString<20> buffer;
3323     if (result & APFloat::opOverflow) {
3324       diagnostic = diag::warn_float_overflow;
3325       APFloat::getLargest(Format).toString(buffer);
3326     } else {
3327       diagnostic = diag::warn_float_underflow;
3328       APFloat::getSmallest(Format).toString(buffer);
3329     }
3330 
3331     S.Diag(Loc, diagnostic)
3332       << Ty
3333       << StringRef(buffer.data(), buffer.size());
3334   }
3335 
3336   bool isExact = (result == APFloat::opOK);
3337   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3338 }
3339 
3340 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3341   assert(E && "Invalid expression");
3342 
3343   if (E->isValueDependent())
3344     return false;
3345 
3346   QualType QT = E->getType();
3347   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3348     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3349     return true;
3350   }
3351 
3352   llvm::APSInt ValueAPS;
3353   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3354 
3355   if (R.isInvalid())
3356     return true;
3357 
3358   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3359   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3360     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3361         << ValueAPS.toString(10) << ValueIsPositive;
3362     return true;
3363   }
3364 
3365   return false;
3366 }
3367 
3368 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3369   // Fast path for a single digit (which is quite common).  A single digit
3370   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3371   if (Tok.getLength() == 1) {
3372     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3373     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3374   }
3375 
3376   SmallString<128> SpellingBuffer;
3377   // NumericLiteralParser wants to overread by one character.  Add padding to
3378   // the buffer in case the token is copied to the buffer.  If getSpelling()
3379   // returns a StringRef to the memory buffer, it should have a null char at
3380   // the EOF, so it is also safe.
3381   SpellingBuffer.resize(Tok.getLength() + 1);
3382 
3383   // Get the spelling of the token, which eliminates trigraphs, etc.
3384   bool Invalid = false;
3385   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3386   if (Invalid)
3387     return ExprError();
3388 
3389   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3390   if (Literal.hadError)
3391     return ExprError();
3392 
3393   if (Literal.hasUDSuffix()) {
3394     // We're building a user-defined literal.
3395     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3396     SourceLocation UDSuffixLoc =
3397       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3398 
3399     // Make sure we're allowed user-defined literals here.
3400     if (!UDLScope)
3401       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3402 
3403     QualType CookedTy;
3404     if (Literal.isFloatingLiteral()) {
3405       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3406       // long double, the literal is treated as a call of the form
3407       //   operator "" X (f L)
3408       CookedTy = Context.LongDoubleTy;
3409     } else {
3410       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3411       // unsigned long long, the literal is treated as a call of the form
3412       //   operator "" X (n ULL)
3413       CookedTy = Context.UnsignedLongLongTy;
3414     }
3415 
3416     DeclarationName OpName =
3417       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3418     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3419     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3420 
3421     SourceLocation TokLoc = Tok.getLocation();
3422 
3423     // Perform literal operator lookup to determine if we're building a raw
3424     // literal or a cooked one.
3425     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3426     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3427                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3428                                   /*AllowStringTemplate*/ false,
3429                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3430     case LOLR_ErrorNoDiagnostic:
3431       // Lookup failure for imaginary constants isn't fatal, there's still the
3432       // GNU extension producing _Complex types.
3433       break;
3434     case LOLR_Error:
3435       return ExprError();
3436     case LOLR_Cooked: {
3437       Expr *Lit;
3438       if (Literal.isFloatingLiteral()) {
3439         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3440       } else {
3441         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3442         if (Literal.GetIntegerValue(ResultVal))
3443           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3444               << /* Unsigned */ 1;
3445         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3446                                      Tok.getLocation());
3447       }
3448       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3449     }
3450 
3451     case LOLR_Raw: {
3452       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3453       // literal is treated as a call of the form
3454       //   operator "" X ("n")
3455       unsigned Length = Literal.getUDSuffixOffset();
3456       QualType StrTy = Context.getConstantArrayType(
3457           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3458           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3459       Expr *Lit = StringLiteral::Create(
3460           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3461           /*Pascal*/false, StrTy, &TokLoc, 1);
3462       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3463     }
3464 
3465     case LOLR_Template: {
3466       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3467       // template), L is treated as a call fo the form
3468       //   operator "" X <'c1', 'c2', ... 'ck'>()
3469       // where n is the source character sequence c1 c2 ... ck.
3470       TemplateArgumentListInfo ExplicitArgs;
3471       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3472       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3473       llvm::APSInt Value(CharBits, CharIsUnsigned);
3474       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3475         Value = TokSpelling[I];
3476         TemplateArgument Arg(Context, Value, Context.CharTy);
3477         TemplateArgumentLocInfo ArgInfo;
3478         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3479       }
3480       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3481                                       &ExplicitArgs);
3482     }
3483     case LOLR_StringTemplate:
3484       llvm_unreachable("unexpected literal operator lookup result");
3485     }
3486   }
3487 
3488   Expr *Res;
3489 
3490   if (Literal.isFixedPointLiteral()) {
3491     QualType Ty;
3492 
3493     if (Literal.isAccum) {
3494       if (Literal.isHalf) {
3495         Ty = Context.ShortAccumTy;
3496       } else if (Literal.isLong) {
3497         Ty = Context.LongAccumTy;
3498       } else {
3499         Ty = Context.AccumTy;
3500       }
3501     } else if (Literal.isFract) {
3502       if (Literal.isHalf) {
3503         Ty = Context.ShortFractTy;
3504       } else if (Literal.isLong) {
3505         Ty = Context.LongFractTy;
3506       } else {
3507         Ty = Context.FractTy;
3508       }
3509     }
3510 
3511     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3512 
3513     bool isSigned = !Literal.isUnsigned;
3514     unsigned scale = Context.getFixedPointScale(Ty);
3515     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3516 
3517     llvm::APInt Val(bit_width, 0, isSigned);
3518     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3519     bool ValIsZero = Val.isNullValue() && !Overflowed;
3520 
3521     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3522     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3523       // Clause 6.4.4 - The value of a constant shall be in the range of
3524       // representable values for its type, with exception for constants of a
3525       // fract type with a value of exactly 1; such a constant shall denote
3526       // the maximal value for the type.
3527       --Val;
3528     else if (Val.ugt(MaxVal) || Overflowed)
3529       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3530 
3531     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3532                                               Tok.getLocation(), scale);
3533   } else if (Literal.isFloatingLiteral()) {
3534     QualType Ty;
3535     if (Literal.isHalf){
3536       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3537         Ty = Context.HalfTy;
3538       else {
3539         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3540         return ExprError();
3541       }
3542     } else if (Literal.isFloat)
3543       Ty = Context.FloatTy;
3544     else if (Literal.isLong)
3545       Ty = Context.LongDoubleTy;
3546     else if (Literal.isFloat16)
3547       Ty = Context.Float16Ty;
3548     else if (Literal.isFloat128)
3549       Ty = Context.Float128Ty;
3550     else
3551       Ty = Context.DoubleTy;
3552 
3553     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3554 
3555     if (Ty == Context.DoubleTy) {
3556       if (getLangOpts().SinglePrecisionConstants) {
3557         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3558         if (BTy->getKind() != BuiltinType::Float) {
3559           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3560         }
3561       } else if (getLangOpts().OpenCL &&
3562                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3563         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3564         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3565         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3566       }
3567     }
3568   } else if (!Literal.isIntegerLiteral()) {
3569     return ExprError();
3570   } else {
3571     QualType Ty;
3572 
3573     // 'long long' is a C99 or C++11 feature.
3574     if (!getLangOpts().C99 && Literal.isLongLong) {
3575       if (getLangOpts().CPlusPlus)
3576         Diag(Tok.getLocation(),
3577              getLangOpts().CPlusPlus11 ?
3578              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3579       else
3580         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3581     }
3582 
3583     // Get the value in the widest-possible width.
3584     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3585     llvm::APInt ResultVal(MaxWidth, 0);
3586 
3587     if (Literal.GetIntegerValue(ResultVal)) {
3588       // If this value didn't fit into uintmax_t, error and force to ull.
3589       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3590           << /* Unsigned */ 1;
3591       Ty = Context.UnsignedLongLongTy;
3592       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3593              "long long is not intmax_t?");
3594     } else {
3595       // If this value fits into a ULL, try to figure out what else it fits into
3596       // according to the rules of C99 6.4.4.1p5.
3597 
3598       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3599       // be an unsigned int.
3600       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3601 
3602       // Check from smallest to largest, picking the smallest type we can.
3603       unsigned Width = 0;
3604 
3605       // Microsoft specific integer suffixes are explicitly sized.
3606       if (Literal.MicrosoftInteger) {
3607         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3608           Width = 8;
3609           Ty = Context.CharTy;
3610         } else {
3611           Width = Literal.MicrosoftInteger;
3612           Ty = Context.getIntTypeForBitwidth(Width,
3613                                              /*Signed=*/!Literal.isUnsigned);
3614         }
3615       }
3616 
3617       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3618         // Are int/unsigned possibilities?
3619         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3620 
3621         // Does it fit in a unsigned int?
3622         if (ResultVal.isIntN(IntSize)) {
3623           // Does it fit in a signed int?
3624           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3625             Ty = Context.IntTy;
3626           else if (AllowUnsigned)
3627             Ty = Context.UnsignedIntTy;
3628           Width = IntSize;
3629         }
3630       }
3631 
3632       // Are long/unsigned long possibilities?
3633       if (Ty.isNull() && !Literal.isLongLong) {
3634         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3635 
3636         // Does it fit in a unsigned long?
3637         if (ResultVal.isIntN(LongSize)) {
3638           // Does it fit in a signed long?
3639           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3640             Ty = Context.LongTy;
3641           else if (AllowUnsigned)
3642             Ty = Context.UnsignedLongTy;
3643           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3644           // is compatible.
3645           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3646             const unsigned LongLongSize =
3647                 Context.getTargetInfo().getLongLongWidth();
3648             Diag(Tok.getLocation(),
3649                  getLangOpts().CPlusPlus
3650                      ? Literal.isLong
3651                            ? diag::warn_old_implicitly_unsigned_long_cxx
3652                            : /*C++98 UB*/ diag::
3653                                  ext_old_implicitly_unsigned_long_cxx
3654                      : diag::warn_old_implicitly_unsigned_long)
3655                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3656                                             : /*will be ill-formed*/ 1);
3657             Ty = Context.UnsignedLongTy;
3658           }
3659           Width = LongSize;
3660         }
3661       }
3662 
3663       // Check long long if needed.
3664       if (Ty.isNull()) {
3665         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3666 
3667         // Does it fit in a unsigned long long?
3668         if (ResultVal.isIntN(LongLongSize)) {
3669           // Does it fit in a signed long long?
3670           // To be compatible with MSVC, hex integer literals ending with the
3671           // LL or i64 suffix are always signed in Microsoft mode.
3672           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3673               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3674             Ty = Context.LongLongTy;
3675           else if (AllowUnsigned)
3676             Ty = Context.UnsignedLongLongTy;
3677           Width = LongLongSize;
3678         }
3679       }
3680 
3681       // If we still couldn't decide a type, we probably have something that
3682       // does not fit in a signed long long, but has no U suffix.
3683       if (Ty.isNull()) {
3684         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3685         Ty = Context.UnsignedLongLongTy;
3686         Width = Context.getTargetInfo().getLongLongWidth();
3687       }
3688 
3689       if (ResultVal.getBitWidth() != Width)
3690         ResultVal = ResultVal.trunc(Width);
3691     }
3692     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3693   }
3694 
3695   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3696   if (Literal.isImaginary) {
3697     Res = new (Context) ImaginaryLiteral(Res,
3698                                         Context.getComplexType(Res->getType()));
3699 
3700     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3701   }
3702   return Res;
3703 }
3704 
3705 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3706   assert(E && "ActOnParenExpr() missing expr");
3707   return new (Context) ParenExpr(L, R, E);
3708 }
3709 
3710 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3711                                          SourceLocation Loc,
3712                                          SourceRange ArgRange) {
3713   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3714   // scalar or vector data type argument..."
3715   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3716   // type (C99 6.2.5p18) or void.
3717   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3718     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3719       << T << ArgRange;
3720     return true;
3721   }
3722 
3723   assert((T->isVoidType() || !T->isIncompleteType()) &&
3724          "Scalar types should always be complete");
3725   return false;
3726 }
3727 
3728 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3729                                            SourceLocation Loc,
3730                                            SourceRange ArgRange,
3731                                            UnaryExprOrTypeTrait TraitKind) {
3732   // Invalid types must be hard errors for SFINAE in C++.
3733   if (S.LangOpts.CPlusPlus)
3734     return true;
3735 
3736   // C99 6.5.3.4p1:
3737   if (T->isFunctionType() &&
3738       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3739        TraitKind == UETT_PreferredAlignOf)) {
3740     // sizeof(function)/alignof(function) is allowed as an extension.
3741     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3742       << TraitKind << ArgRange;
3743     return false;
3744   }
3745 
3746   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3747   // this is an error (OpenCL v1.1 s6.3.k)
3748   if (T->isVoidType()) {
3749     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3750                                         : diag::ext_sizeof_alignof_void_type;
3751     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3752     return false;
3753   }
3754 
3755   return true;
3756 }
3757 
3758 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3759                                              SourceLocation Loc,
3760                                              SourceRange ArgRange,
3761                                              UnaryExprOrTypeTrait TraitKind) {
3762   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3763   // runtime doesn't allow it.
3764   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3765     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3766       << T << (TraitKind == UETT_SizeOf)
3767       << ArgRange;
3768     return true;
3769   }
3770 
3771   return false;
3772 }
3773 
3774 /// Check whether E is a pointer from a decayed array type (the decayed
3775 /// pointer type is equal to T) and emit a warning if it is.
3776 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3777                                      Expr *E) {
3778   // Don't warn if the operation changed the type.
3779   if (T != E->getType())
3780     return;
3781 
3782   // Now look for array decays.
3783   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3784   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3785     return;
3786 
3787   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3788                                              << ICE->getType()
3789                                              << ICE->getSubExpr()->getType();
3790 }
3791 
3792 /// Check the constraints on expression operands to unary type expression
3793 /// and type traits.
3794 ///
3795 /// Completes any types necessary and validates the constraints on the operand
3796 /// expression. The logic mostly mirrors the type-based overload, but may modify
3797 /// the expression as it completes the type for that expression through template
3798 /// instantiation, etc.
3799 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3800                                             UnaryExprOrTypeTrait ExprKind) {
3801   QualType ExprTy = E->getType();
3802   assert(!ExprTy->isReferenceType());
3803 
3804   if (ExprKind == UETT_VecStep)
3805     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3806                                         E->getSourceRange());
3807 
3808   // Whitelist some types as extensions
3809   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3810                                       E->getSourceRange(), ExprKind))
3811     return false;
3812 
3813   // 'alignof' applied to an expression only requires the base element type of
3814   // the expression to be complete. 'sizeof' requires the expression's type to
3815   // be complete (and will attempt to complete it if it's an array of unknown
3816   // bound).
3817   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3818     if (RequireCompleteType(E->getExprLoc(),
3819                             Context.getBaseElementType(E->getType()),
3820                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3821                             E->getSourceRange()))
3822       return true;
3823   } else {
3824     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3825                                 ExprKind, E->getSourceRange()))
3826       return true;
3827   }
3828 
3829   // Completing the expression's type may have changed it.
3830   ExprTy = E->getType();
3831   assert(!ExprTy->isReferenceType());
3832 
3833   if (ExprTy->isFunctionType()) {
3834     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3835       << ExprKind << E->getSourceRange();
3836     return true;
3837   }
3838 
3839   // The operand for sizeof and alignof is in an unevaluated expression context,
3840   // so side effects could result in unintended consequences.
3841   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3842        ExprKind == UETT_PreferredAlignOf) &&
3843       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3844     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3845 
3846   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3847                                        E->getSourceRange(), ExprKind))
3848     return true;
3849 
3850   if (ExprKind == UETT_SizeOf) {
3851     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3852       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3853         QualType OType = PVD->getOriginalType();
3854         QualType Type = PVD->getType();
3855         if (Type->isPointerType() && OType->isArrayType()) {
3856           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3857             << Type << OType;
3858           Diag(PVD->getLocation(), diag::note_declared_at);
3859         }
3860       }
3861     }
3862 
3863     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3864     // decays into a pointer and returns an unintended result. This is most
3865     // likely a typo for "sizeof(array) op x".
3866     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3867       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3868                                BO->getLHS());
3869       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3870                                BO->getRHS());
3871     }
3872   }
3873 
3874   return false;
3875 }
3876 
3877 /// Check the constraints on operands to unary expression and type
3878 /// traits.
3879 ///
3880 /// This will complete any types necessary, and validate the various constraints
3881 /// on those operands.
3882 ///
3883 /// The UsualUnaryConversions() function is *not* called by this routine.
3884 /// C99 6.3.2.1p[2-4] all state:
3885 ///   Except when it is the operand of the sizeof operator ...
3886 ///
3887 /// C++ [expr.sizeof]p4
3888 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3889 ///   standard conversions are not applied to the operand of sizeof.
3890 ///
3891 /// This policy is followed for all of the unary trait expressions.
3892 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3893                                             SourceLocation OpLoc,
3894                                             SourceRange ExprRange,
3895                                             UnaryExprOrTypeTrait ExprKind) {
3896   if (ExprType->isDependentType())
3897     return false;
3898 
3899   // C++ [expr.sizeof]p2:
3900   //     When applied to a reference or a reference type, the result
3901   //     is the size of the referenced type.
3902   // C++11 [expr.alignof]p3:
3903   //     When alignof is applied to a reference type, the result
3904   //     shall be the alignment of the referenced type.
3905   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3906     ExprType = Ref->getPointeeType();
3907 
3908   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3909   //   When alignof or _Alignof is applied to an array type, the result
3910   //   is the alignment of the element type.
3911   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3912       ExprKind == UETT_OpenMPRequiredSimdAlign)
3913     ExprType = Context.getBaseElementType(ExprType);
3914 
3915   if (ExprKind == UETT_VecStep)
3916     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3917 
3918   // Whitelist some types as extensions
3919   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3920                                       ExprKind))
3921     return false;
3922 
3923   if (RequireCompleteType(OpLoc, ExprType,
3924                           diag::err_sizeof_alignof_incomplete_type,
3925                           ExprKind, ExprRange))
3926     return true;
3927 
3928   if (ExprType->isFunctionType()) {
3929     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3930       << ExprKind << ExprRange;
3931     return true;
3932   }
3933 
3934   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3935                                        ExprKind))
3936     return true;
3937 
3938   return false;
3939 }
3940 
3941 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3942   E = E->IgnoreParens();
3943 
3944   // Cannot know anything else if the expression is dependent.
3945   if (E->isTypeDependent())
3946     return false;
3947 
3948   if (E->getObjectKind() == OK_BitField) {
3949     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3950        << 1 << E->getSourceRange();
3951     return true;
3952   }
3953 
3954   ValueDecl *D = nullptr;
3955   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3956     D = DRE->getDecl();
3957   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3958     D = ME->getMemberDecl();
3959   }
3960 
3961   // If it's a field, require the containing struct to have a
3962   // complete definition so that we can compute the layout.
3963   //
3964   // This can happen in C++11 onwards, either by naming the member
3965   // in a way that is not transformed into a member access expression
3966   // (in an unevaluated operand, for instance), or by naming the member
3967   // in a trailing-return-type.
3968   //
3969   // For the record, since __alignof__ on expressions is a GCC
3970   // extension, GCC seems to permit this but always gives the
3971   // nonsensical answer 0.
3972   //
3973   // We don't really need the layout here --- we could instead just
3974   // directly check for all the appropriate alignment-lowing
3975   // attributes --- but that would require duplicating a lot of
3976   // logic that just isn't worth duplicating for such a marginal
3977   // use-case.
3978   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3979     // Fast path this check, since we at least know the record has a
3980     // definition if we can find a member of it.
3981     if (!FD->getParent()->isCompleteDefinition()) {
3982       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3983         << E->getSourceRange();
3984       return true;
3985     }
3986 
3987     // Otherwise, if it's a field, and the field doesn't have
3988     // reference type, then it must have a complete type (or be a
3989     // flexible array member, which we explicitly want to
3990     // white-list anyway), which makes the following checks trivial.
3991     if (!FD->getType()->isReferenceType())
3992       return false;
3993   }
3994 
3995   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3996 }
3997 
3998 bool Sema::CheckVecStepExpr(Expr *E) {
3999   E = E->IgnoreParens();
4000 
4001   // Cannot know anything else if the expression is dependent.
4002   if (E->isTypeDependent())
4003     return false;
4004 
4005   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4006 }
4007 
4008 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4009                                         CapturingScopeInfo *CSI) {
4010   assert(T->isVariablyModifiedType());
4011   assert(CSI != nullptr);
4012 
4013   // We're going to walk down into the type and look for VLA expressions.
4014   do {
4015     const Type *Ty = T.getTypePtr();
4016     switch (Ty->getTypeClass()) {
4017 #define TYPE(Class, Base)
4018 #define ABSTRACT_TYPE(Class, Base)
4019 #define NON_CANONICAL_TYPE(Class, Base)
4020 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4021 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4022 #include "clang/AST/TypeNodes.inc"
4023       T = QualType();
4024       break;
4025     // These types are never variably-modified.
4026     case Type::Builtin:
4027     case Type::Complex:
4028     case Type::Vector:
4029     case Type::ExtVector:
4030     case Type::Record:
4031     case Type::Enum:
4032     case Type::Elaborated:
4033     case Type::TemplateSpecialization:
4034     case Type::ObjCObject:
4035     case Type::ObjCInterface:
4036     case Type::ObjCObjectPointer:
4037     case Type::ObjCTypeParam:
4038     case Type::Pipe:
4039       llvm_unreachable("type class is never variably-modified!");
4040     case Type::Adjusted:
4041       T = cast<AdjustedType>(Ty)->getOriginalType();
4042       break;
4043     case Type::Decayed:
4044       T = cast<DecayedType>(Ty)->getPointeeType();
4045       break;
4046     case Type::Pointer:
4047       T = cast<PointerType>(Ty)->getPointeeType();
4048       break;
4049     case Type::BlockPointer:
4050       T = cast<BlockPointerType>(Ty)->getPointeeType();
4051       break;
4052     case Type::LValueReference:
4053     case Type::RValueReference:
4054       T = cast<ReferenceType>(Ty)->getPointeeType();
4055       break;
4056     case Type::MemberPointer:
4057       T = cast<MemberPointerType>(Ty)->getPointeeType();
4058       break;
4059     case Type::ConstantArray:
4060     case Type::IncompleteArray:
4061       // Losing element qualification here is fine.
4062       T = cast<ArrayType>(Ty)->getElementType();
4063       break;
4064     case Type::VariableArray: {
4065       // Losing element qualification here is fine.
4066       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4067 
4068       // Unknown size indication requires no size computation.
4069       // Otherwise, evaluate and record it.
4070       auto Size = VAT->getSizeExpr();
4071       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4072           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4073         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4074 
4075       T = VAT->getElementType();
4076       break;
4077     }
4078     case Type::FunctionProto:
4079     case Type::FunctionNoProto:
4080       T = cast<FunctionType>(Ty)->getReturnType();
4081       break;
4082     case Type::Paren:
4083     case Type::TypeOf:
4084     case Type::UnaryTransform:
4085     case Type::Attributed:
4086     case Type::SubstTemplateTypeParm:
4087     case Type::PackExpansion:
4088     case Type::MacroQualified:
4089       // Keep walking after single level desugaring.
4090       T = T.getSingleStepDesugaredType(Context);
4091       break;
4092     case Type::Typedef:
4093       T = cast<TypedefType>(Ty)->desugar();
4094       break;
4095     case Type::Decltype:
4096       T = cast<DecltypeType>(Ty)->desugar();
4097       break;
4098     case Type::Auto:
4099     case Type::DeducedTemplateSpecialization:
4100       T = cast<DeducedType>(Ty)->getDeducedType();
4101       break;
4102     case Type::TypeOfExpr:
4103       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4104       break;
4105     case Type::Atomic:
4106       T = cast<AtomicType>(Ty)->getValueType();
4107       break;
4108     }
4109   } while (!T.isNull() && T->isVariablyModifiedType());
4110 }
4111 
4112 /// Build a sizeof or alignof expression given a type operand.
4113 ExprResult
4114 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4115                                      SourceLocation OpLoc,
4116                                      UnaryExprOrTypeTrait ExprKind,
4117                                      SourceRange R) {
4118   if (!TInfo)
4119     return ExprError();
4120 
4121   QualType T = TInfo->getType();
4122 
4123   if (!T->isDependentType() &&
4124       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4125     return ExprError();
4126 
4127   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4128     if (auto *TT = T->getAs<TypedefType>()) {
4129       for (auto I = FunctionScopes.rbegin(),
4130                 E = std::prev(FunctionScopes.rend());
4131            I != E; ++I) {
4132         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4133         if (CSI == nullptr)
4134           break;
4135         DeclContext *DC = nullptr;
4136         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4137           DC = LSI->CallOperator;
4138         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4139           DC = CRSI->TheCapturedDecl;
4140         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4141           DC = BSI->TheDecl;
4142         if (DC) {
4143           if (DC->containsDecl(TT->getDecl()))
4144             break;
4145           captureVariablyModifiedType(Context, T, CSI);
4146         }
4147       }
4148     }
4149   }
4150 
4151   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4152   return new (Context) UnaryExprOrTypeTraitExpr(
4153       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4154 }
4155 
4156 /// Build a sizeof or alignof expression given an expression
4157 /// operand.
4158 ExprResult
4159 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4160                                      UnaryExprOrTypeTrait ExprKind) {
4161   ExprResult PE = CheckPlaceholderExpr(E);
4162   if (PE.isInvalid())
4163     return ExprError();
4164 
4165   E = PE.get();
4166 
4167   // Verify that the operand is valid.
4168   bool isInvalid = false;
4169   if (E->isTypeDependent()) {
4170     // Delay type-checking for type-dependent expressions.
4171   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4172     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4173   } else if (ExprKind == UETT_VecStep) {
4174     isInvalid = CheckVecStepExpr(E);
4175   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4176       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4177       isInvalid = true;
4178   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4179     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4180     isInvalid = true;
4181   } else {
4182     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4183   }
4184 
4185   if (isInvalid)
4186     return ExprError();
4187 
4188   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4189     PE = TransformToPotentiallyEvaluated(E);
4190     if (PE.isInvalid()) return ExprError();
4191     E = PE.get();
4192   }
4193 
4194   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4195   return new (Context) UnaryExprOrTypeTraitExpr(
4196       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4197 }
4198 
4199 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4200 /// expr and the same for @c alignof and @c __alignof
4201 /// Note that the ArgRange is invalid if isType is false.
4202 ExprResult
4203 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4204                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4205                                     void *TyOrEx, SourceRange ArgRange) {
4206   // If error parsing type, ignore.
4207   if (!TyOrEx) return ExprError();
4208 
4209   if (IsType) {
4210     TypeSourceInfo *TInfo;
4211     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4212     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4213   }
4214 
4215   Expr *ArgEx = (Expr *)TyOrEx;
4216   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4217   return Result;
4218 }
4219 
4220 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4221                                      bool IsReal) {
4222   if (V.get()->isTypeDependent())
4223     return S.Context.DependentTy;
4224 
4225   // _Real and _Imag are only l-values for normal l-values.
4226   if (V.get()->getObjectKind() != OK_Ordinary) {
4227     V = S.DefaultLvalueConversion(V.get());
4228     if (V.isInvalid())
4229       return QualType();
4230   }
4231 
4232   // These operators return the element type of a complex type.
4233   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4234     return CT->getElementType();
4235 
4236   // Otherwise they pass through real integer and floating point types here.
4237   if (V.get()->getType()->isArithmeticType())
4238     return V.get()->getType();
4239 
4240   // Test for placeholders.
4241   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4242   if (PR.isInvalid()) return QualType();
4243   if (PR.get() != V.get()) {
4244     V = PR;
4245     return CheckRealImagOperand(S, V, Loc, IsReal);
4246   }
4247 
4248   // Reject anything else.
4249   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4250     << (IsReal ? "__real" : "__imag");
4251   return QualType();
4252 }
4253 
4254 
4255 
4256 ExprResult
4257 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4258                           tok::TokenKind Kind, Expr *Input) {
4259   UnaryOperatorKind Opc;
4260   switch (Kind) {
4261   default: llvm_unreachable("Unknown unary op!");
4262   case tok::plusplus:   Opc = UO_PostInc; break;
4263   case tok::minusminus: Opc = UO_PostDec; break;
4264   }
4265 
4266   // Since this might is a postfix expression, get rid of ParenListExprs.
4267   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4268   if (Result.isInvalid()) return ExprError();
4269   Input = Result.get();
4270 
4271   return BuildUnaryOp(S, OpLoc, Opc, Input);
4272 }
4273 
4274 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4275 ///
4276 /// \return true on error
4277 static bool checkArithmeticOnObjCPointer(Sema &S,
4278                                          SourceLocation opLoc,
4279                                          Expr *op) {
4280   assert(op->getType()->isObjCObjectPointerType());
4281   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4282       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4283     return false;
4284 
4285   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4286     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4287     << op->getSourceRange();
4288   return true;
4289 }
4290 
4291 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4292   auto *BaseNoParens = Base->IgnoreParens();
4293   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4294     return MSProp->getPropertyDecl()->getType()->isArrayType();
4295   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4296 }
4297 
4298 ExprResult
4299 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4300                               Expr *idx, SourceLocation rbLoc) {
4301   if (base && !base->getType().isNull() &&
4302       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4303     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4304                                     /*Length=*/nullptr, rbLoc);
4305 
4306   // Since this might be a postfix expression, get rid of ParenListExprs.
4307   if (isa<ParenListExpr>(base)) {
4308     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4309     if (result.isInvalid()) return ExprError();
4310     base = result.get();
4311   }
4312 
4313   // A comma-expression as the index is deprecated in C++2a onwards.
4314   if (getLangOpts().CPlusPlus2a &&
4315       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4316        (isa<CXXOperatorCallExpr>(idx) &&
4317         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4318     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4319       << SourceRange(base->getBeginLoc(), rbLoc);
4320   }
4321 
4322   // Handle any non-overload placeholder types in the base and index
4323   // expressions.  We can't handle overloads here because the other
4324   // operand might be an overloadable type, in which case the overload
4325   // resolution for the operator overload should get the first crack
4326   // at the overload.
4327   bool IsMSPropertySubscript = false;
4328   if (base->getType()->isNonOverloadPlaceholderType()) {
4329     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4330     if (!IsMSPropertySubscript) {
4331       ExprResult result = CheckPlaceholderExpr(base);
4332       if (result.isInvalid())
4333         return ExprError();
4334       base = result.get();
4335     }
4336   }
4337   if (idx->getType()->isNonOverloadPlaceholderType()) {
4338     ExprResult result = CheckPlaceholderExpr(idx);
4339     if (result.isInvalid()) return ExprError();
4340     idx = result.get();
4341   }
4342 
4343   // Build an unanalyzed expression if either operand is type-dependent.
4344   if (getLangOpts().CPlusPlus &&
4345       (base->isTypeDependent() || idx->isTypeDependent())) {
4346     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4347                                             VK_LValue, OK_Ordinary, rbLoc);
4348   }
4349 
4350   // MSDN, property (C++)
4351   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4352   // This attribute can also be used in the declaration of an empty array in a
4353   // class or structure definition. For example:
4354   // __declspec(property(get=GetX, put=PutX)) int x[];
4355   // The above statement indicates that x[] can be used with one or more array
4356   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4357   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4358   if (IsMSPropertySubscript) {
4359     // Build MS property subscript expression if base is MS property reference
4360     // or MS property subscript.
4361     return new (Context) MSPropertySubscriptExpr(
4362         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4363   }
4364 
4365   // Use C++ overloaded-operator rules if either operand has record
4366   // type.  The spec says to do this if either type is *overloadable*,
4367   // but enum types can't declare subscript operators or conversion
4368   // operators, so there's nothing interesting for overload resolution
4369   // to do if there aren't any record types involved.
4370   //
4371   // ObjC pointers have their own subscripting logic that is not tied
4372   // to overload resolution and so should not take this path.
4373   if (getLangOpts().CPlusPlus &&
4374       (base->getType()->isRecordType() ||
4375        (!base->getType()->isObjCObjectPointerType() &&
4376         idx->getType()->isRecordType()))) {
4377     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4378   }
4379 
4380   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4381 
4382   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4383     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4384 
4385   return Res;
4386 }
4387 
4388 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4389   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4390   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4391 
4392   // For expressions like `&(*s).b`, the base is recorded and what should be
4393   // checked.
4394   const MemberExpr *Member = nullptr;
4395   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4396     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4397 
4398   LastRecord.PossibleDerefs.erase(StrippedExpr);
4399 }
4400 
4401 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4402   QualType ResultTy = E->getType();
4403   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4404 
4405   // Bail if the element is an array since it is not memory access.
4406   if (isa<ArrayType>(ResultTy))
4407     return;
4408 
4409   if (ResultTy->hasAttr(attr::NoDeref)) {
4410     LastRecord.PossibleDerefs.insert(E);
4411     return;
4412   }
4413 
4414   // Check if the base type is a pointer to a member access of a struct
4415   // marked with noderef.
4416   const Expr *Base = E->getBase();
4417   QualType BaseTy = Base->getType();
4418   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4419     // Not a pointer access
4420     return;
4421 
4422   const MemberExpr *Member = nullptr;
4423   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4424          Member->isArrow())
4425     Base = Member->getBase();
4426 
4427   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4428     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4429       LastRecord.PossibleDerefs.insert(E);
4430   }
4431 }
4432 
4433 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4434                                           Expr *LowerBound,
4435                                           SourceLocation ColonLoc, Expr *Length,
4436                                           SourceLocation RBLoc) {
4437   if (Base->getType()->isPlaceholderType() &&
4438       !Base->getType()->isSpecificPlaceholderType(
4439           BuiltinType::OMPArraySection)) {
4440     ExprResult Result = CheckPlaceholderExpr(Base);
4441     if (Result.isInvalid())
4442       return ExprError();
4443     Base = Result.get();
4444   }
4445   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4446     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4447     if (Result.isInvalid())
4448       return ExprError();
4449     Result = DefaultLvalueConversion(Result.get());
4450     if (Result.isInvalid())
4451       return ExprError();
4452     LowerBound = Result.get();
4453   }
4454   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4455     ExprResult Result = CheckPlaceholderExpr(Length);
4456     if (Result.isInvalid())
4457       return ExprError();
4458     Result = DefaultLvalueConversion(Result.get());
4459     if (Result.isInvalid())
4460       return ExprError();
4461     Length = Result.get();
4462   }
4463 
4464   // Build an unanalyzed expression if either operand is type-dependent.
4465   if (Base->isTypeDependent() ||
4466       (LowerBound &&
4467        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4468       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4469     return new (Context)
4470         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4471                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4472   }
4473 
4474   // Perform default conversions.
4475   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4476   QualType ResultTy;
4477   if (OriginalTy->isAnyPointerType()) {
4478     ResultTy = OriginalTy->getPointeeType();
4479   } else if (OriginalTy->isArrayType()) {
4480     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4481   } else {
4482     return ExprError(
4483         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4484         << Base->getSourceRange());
4485   }
4486   // C99 6.5.2.1p1
4487   if (LowerBound) {
4488     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4489                                                       LowerBound);
4490     if (Res.isInvalid())
4491       return ExprError(Diag(LowerBound->getExprLoc(),
4492                             diag::err_omp_typecheck_section_not_integer)
4493                        << 0 << LowerBound->getSourceRange());
4494     LowerBound = Res.get();
4495 
4496     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4497         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4498       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4499           << 0 << LowerBound->getSourceRange();
4500   }
4501   if (Length) {
4502     auto Res =
4503         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4504     if (Res.isInvalid())
4505       return ExprError(Diag(Length->getExprLoc(),
4506                             diag::err_omp_typecheck_section_not_integer)
4507                        << 1 << Length->getSourceRange());
4508     Length = Res.get();
4509 
4510     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4511         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4512       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4513           << 1 << Length->getSourceRange();
4514   }
4515 
4516   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4517   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4518   // type. Note that functions are not objects, and that (in C99 parlance)
4519   // incomplete types are not object types.
4520   if (ResultTy->isFunctionType()) {
4521     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4522         << ResultTy << Base->getSourceRange();
4523     return ExprError();
4524   }
4525 
4526   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4527                           diag::err_omp_section_incomplete_type, Base))
4528     return ExprError();
4529 
4530   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4531     Expr::EvalResult Result;
4532     if (LowerBound->EvaluateAsInt(Result, Context)) {
4533       // OpenMP 4.5, [2.4 Array Sections]
4534       // The array section must be a subset of the original array.
4535       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4536       if (LowerBoundValue.isNegative()) {
4537         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4538             << LowerBound->getSourceRange();
4539         return ExprError();
4540       }
4541     }
4542   }
4543 
4544   if (Length) {
4545     Expr::EvalResult Result;
4546     if (Length->EvaluateAsInt(Result, Context)) {
4547       // OpenMP 4.5, [2.4 Array Sections]
4548       // The length must evaluate to non-negative integers.
4549       llvm::APSInt LengthValue = Result.Val.getInt();
4550       if (LengthValue.isNegative()) {
4551         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4552             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4553             << Length->getSourceRange();
4554         return ExprError();
4555       }
4556     }
4557   } else if (ColonLoc.isValid() &&
4558              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4559                                       !OriginalTy->isVariableArrayType()))) {
4560     // OpenMP 4.5, [2.4 Array Sections]
4561     // When the size of the array dimension is not known, the length must be
4562     // specified explicitly.
4563     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4564         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4565     return ExprError();
4566   }
4567 
4568   if (!Base->getType()->isSpecificPlaceholderType(
4569           BuiltinType::OMPArraySection)) {
4570     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4571     if (Result.isInvalid())
4572       return ExprError();
4573     Base = Result.get();
4574   }
4575   return new (Context)
4576       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4577                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4578 }
4579 
4580 ExprResult
4581 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4582                                       Expr *Idx, SourceLocation RLoc) {
4583   Expr *LHSExp = Base;
4584   Expr *RHSExp = Idx;
4585 
4586   ExprValueKind VK = VK_LValue;
4587   ExprObjectKind OK = OK_Ordinary;
4588 
4589   // Per C++ core issue 1213, the result is an xvalue if either operand is
4590   // a non-lvalue array, and an lvalue otherwise.
4591   if (getLangOpts().CPlusPlus11) {
4592     for (auto *Op : {LHSExp, RHSExp}) {
4593       Op = Op->IgnoreImplicit();
4594       if (Op->getType()->isArrayType() && !Op->isLValue())
4595         VK = VK_XValue;
4596     }
4597   }
4598 
4599   // Perform default conversions.
4600   if (!LHSExp->getType()->getAs<VectorType>()) {
4601     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4602     if (Result.isInvalid())
4603       return ExprError();
4604     LHSExp = Result.get();
4605   }
4606   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4607   if (Result.isInvalid())
4608     return ExprError();
4609   RHSExp = Result.get();
4610 
4611   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4612 
4613   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4614   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4615   // in the subscript position. As a result, we need to derive the array base
4616   // and index from the expression types.
4617   Expr *BaseExpr, *IndexExpr;
4618   QualType ResultType;
4619   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4620     BaseExpr = LHSExp;
4621     IndexExpr = RHSExp;
4622     ResultType = Context.DependentTy;
4623   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4624     BaseExpr = LHSExp;
4625     IndexExpr = RHSExp;
4626     ResultType = PTy->getPointeeType();
4627   } else if (const ObjCObjectPointerType *PTy =
4628                LHSTy->getAs<ObjCObjectPointerType>()) {
4629     BaseExpr = LHSExp;
4630     IndexExpr = RHSExp;
4631 
4632     // Use custom logic if this should be the pseudo-object subscript
4633     // expression.
4634     if (!LangOpts.isSubscriptPointerArithmetic())
4635       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4636                                           nullptr);
4637 
4638     ResultType = PTy->getPointeeType();
4639   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4640      // Handle the uncommon case of "123[Ptr]".
4641     BaseExpr = RHSExp;
4642     IndexExpr = LHSExp;
4643     ResultType = PTy->getPointeeType();
4644   } else if (const ObjCObjectPointerType *PTy =
4645                RHSTy->getAs<ObjCObjectPointerType>()) {
4646      // Handle the uncommon case of "123[Ptr]".
4647     BaseExpr = RHSExp;
4648     IndexExpr = LHSExp;
4649     ResultType = PTy->getPointeeType();
4650     if (!LangOpts.isSubscriptPointerArithmetic()) {
4651       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4652         << ResultType << BaseExpr->getSourceRange();
4653       return ExprError();
4654     }
4655   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4656     BaseExpr = LHSExp;    // vectors: V[123]
4657     IndexExpr = RHSExp;
4658     // We apply C++ DR1213 to vector subscripting too.
4659     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4660       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4661       if (Materialized.isInvalid())
4662         return ExprError();
4663       LHSExp = Materialized.get();
4664     }
4665     VK = LHSExp->getValueKind();
4666     if (VK != VK_RValue)
4667       OK = OK_VectorComponent;
4668 
4669     ResultType = VTy->getElementType();
4670     QualType BaseType = BaseExpr->getType();
4671     Qualifiers BaseQuals = BaseType.getQualifiers();
4672     Qualifiers MemberQuals = ResultType.getQualifiers();
4673     Qualifiers Combined = BaseQuals + MemberQuals;
4674     if (Combined != MemberQuals)
4675       ResultType = Context.getQualifiedType(ResultType, Combined);
4676   } else if (LHSTy->isArrayType()) {
4677     // If we see an array that wasn't promoted by
4678     // DefaultFunctionArrayLvalueConversion, it must be an array that
4679     // wasn't promoted because of the C90 rule that doesn't
4680     // allow promoting non-lvalue arrays.  Warn, then
4681     // force the promotion here.
4682     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4683         << LHSExp->getSourceRange();
4684     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4685                                CK_ArrayToPointerDecay).get();
4686     LHSTy = LHSExp->getType();
4687 
4688     BaseExpr = LHSExp;
4689     IndexExpr = RHSExp;
4690     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4691   } else if (RHSTy->isArrayType()) {
4692     // Same as previous, except for 123[f().a] case
4693     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4694         << RHSExp->getSourceRange();
4695     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4696                                CK_ArrayToPointerDecay).get();
4697     RHSTy = RHSExp->getType();
4698 
4699     BaseExpr = RHSExp;
4700     IndexExpr = LHSExp;
4701     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4702   } else {
4703     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4704        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4705   }
4706   // C99 6.5.2.1p1
4707   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4708     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4709                      << IndexExpr->getSourceRange());
4710 
4711   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4712        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4713          && !IndexExpr->isTypeDependent())
4714     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4715 
4716   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4717   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4718   // type. Note that Functions are not objects, and that (in C99 parlance)
4719   // incomplete types are not object types.
4720   if (ResultType->isFunctionType()) {
4721     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4722         << ResultType << BaseExpr->getSourceRange();
4723     return ExprError();
4724   }
4725 
4726   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4727     // GNU extension: subscripting on pointer to void
4728     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4729       << BaseExpr->getSourceRange();
4730 
4731     // C forbids expressions of unqualified void type from being l-values.
4732     // See IsCForbiddenLValueType.
4733     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4734   } else if (!ResultType->isDependentType() &&
4735       RequireCompleteType(LLoc, ResultType,
4736                           diag::err_subscript_incomplete_type, BaseExpr))
4737     return ExprError();
4738 
4739   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4740          !ResultType.isCForbiddenLValueType());
4741 
4742   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4743       FunctionScopes.size() > 1) {
4744     if (auto *TT =
4745             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4746       for (auto I = FunctionScopes.rbegin(),
4747                 E = std::prev(FunctionScopes.rend());
4748            I != E; ++I) {
4749         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4750         if (CSI == nullptr)
4751           break;
4752         DeclContext *DC = nullptr;
4753         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4754           DC = LSI->CallOperator;
4755         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4756           DC = CRSI->TheCapturedDecl;
4757         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4758           DC = BSI->TheDecl;
4759         if (DC) {
4760           if (DC->containsDecl(TT->getDecl()))
4761             break;
4762           captureVariablyModifiedType(
4763               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4764         }
4765       }
4766     }
4767   }
4768 
4769   return new (Context)
4770       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4771 }
4772 
4773 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4774                                   ParmVarDecl *Param) {
4775   if (Param->hasUnparsedDefaultArg()) {
4776     Diag(CallLoc,
4777          diag::err_use_of_default_argument_to_function_declared_later) <<
4778       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4779     Diag(UnparsedDefaultArgLocs[Param],
4780          diag::note_default_argument_declared_here);
4781     return true;
4782   }
4783 
4784   if (Param->hasUninstantiatedDefaultArg()) {
4785     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4786 
4787     EnterExpressionEvaluationContext EvalContext(
4788         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4789 
4790     // Instantiate the expression.
4791     //
4792     // FIXME: Pass in a correct Pattern argument, otherwise
4793     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4794     //
4795     // template<typename T>
4796     // struct A {
4797     //   static int FooImpl();
4798     //
4799     //   template<typename Tp>
4800     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4801     //   // template argument list [[T], [Tp]], should be [[Tp]].
4802     //   friend A<Tp> Foo(int a);
4803     // };
4804     //
4805     // template<typename T>
4806     // A<T> Foo(int a = A<T>::FooImpl());
4807     MultiLevelTemplateArgumentList MutiLevelArgList
4808       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4809 
4810     InstantiatingTemplate Inst(*this, CallLoc, Param,
4811                                MutiLevelArgList.getInnermost());
4812     if (Inst.isInvalid())
4813       return true;
4814     if (Inst.isAlreadyInstantiating()) {
4815       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4816       Param->setInvalidDecl();
4817       return true;
4818     }
4819 
4820     ExprResult Result;
4821     {
4822       // C++ [dcl.fct.default]p5:
4823       //   The names in the [default argument] expression are bound, and
4824       //   the semantic constraints are checked, at the point where the
4825       //   default argument expression appears.
4826       ContextRAII SavedContext(*this, FD);
4827       LocalInstantiationScope Local(*this);
4828       runWithSufficientStackSpace(CallLoc, [&] {
4829         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4830                                   /*DirectInit*/false);
4831       });
4832     }
4833     if (Result.isInvalid())
4834       return true;
4835 
4836     // Check the expression as an initializer for the parameter.
4837     InitializedEntity Entity
4838       = InitializedEntity::InitializeParameter(Context, Param);
4839     InitializationKind Kind = InitializationKind::CreateCopy(
4840         Param->getLocation(),
4841         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4842     Expr *ResultE = Result.getAs<Expr>();
4843 
4844     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4845     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4846     if (Result.isInvalid())
4847       return true;
4848 
4849     Result =
4850         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4851                             /*DiscardedValue*/ false);
4852     if (Result.isInvalid())
4853       return true;
4854 
4855     // Remember the instantiated default argument.
4856     Param->setDefaultArg(Result.getAs<Expr>());
4857     if (ASTMutationListener *L = getASTMutationListener()) {
4858       L->DefaultArgumentInstantiated(Param);
4859     }
4860   }
4861 
4862   // If the default argument expression is not set yet, we are building it now.
4863   if (!Param->hasInit()) {
4864     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4865     Param->setInvalidDecl();
4866     return true;
4867   }
4868 
4869   // If the default expression creates temporaries, we need to
4870   // push them to the current stack of expression temporaries so they'll
4871   // be properly destroyed.
4872   // FIXME: We should really be rebuilding the default argument with new
4873   // bound temporaries; see the comment in PR5810.
4874   // We don't need to do that with block decls, though, because
4875   // blocks in default argument expression can never capture anything.
4876   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4877     // Set the "needs cleanups" bit regardless of whether there are
4878     // any explicit objects.
4879     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4880 
4881     // Append all the objects to the cleanup list.  Right now, this
4882     // should always be a no-op, because blocks in default argument
4883     // expressions should never be able to capture anything.
4884     assert(!Init->getNumObjects() &&
4885            "default argument expression has capturing blocks?");
4886   }
4887 
4888   // We already type-checked the argument, so we know it works.
4889   // Just mark all of the declarations in this potentially-evaluated expression
4890   // as being "referenced".
4891   EnterExpressionEvaluationContext EvalContext(
4892       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4893   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4894                                    /*SkipLocalVariables=*/true);
4895   return false;
4896 }
4897 
4898 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4899                                         FunctionDecl *FD, ParmVarDecl *Param) {
4900   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4901     return ExprError();
4902   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4903 }
4904 
4905 Sema::VariadicCallType
4906 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4907                           Expr *Fn) {
4908   if (Proto && Proto->isVariadic()) {
4909     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4910       return VariadicConstructor;
4911     else if (Fn && Fn->getType()->isBlockPointerType())
4912       return VariadicBlock;
4913     else if (FDecl) {
4914       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4915         if (Method->isInstance())
4916           return VariadicMethod;
4917     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4918       return VariadicMethod;
4919     return VariadicFunction;
4920   }
4921   return VariadicDoesNotApply;
4922 }
4923 
4924 namespace {
4925 class FunctionCallCCC final : public FunctionCallFilterCCC {
4926 public:
4927   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4928                   unsigned NumArgs, MemberExpr *ME)
4929       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4930         FunctionName(FuncName) {}
4931 
4932   bool ValidateCandidate(const TypoCorrection &candidate) override {
4933     if (!candidate.getCorrectionSpecifier() ||
4934         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4935       return false;
4936     }
4937 
4938     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4939   }
4940 
4941   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4942     return std::make_unique<FunctionCallCCC>(*this);
4943   }
4944 
4945 private:
4946   const IdentifierInfo *const FunctionName;
4947 };
4948 }
4949 
4950 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4951                                                FunctionDecl *FDecl,
4952                                                ArrayRef<Expr *> Args) {
4953   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4954   DeclarationName FuncName = FDecl->getDeclName();
4955   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4956 
4957   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4958   if (TypoCorrection Corrected = S.CorrectTypo(
4959           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4960           S.getScopeForContext(S.CurContext), nullptr, CCC,
4961           Sema::CTK_ErrorRecovery)) {
4962     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4963       if (Corrected.isOverloaded()) {
4964         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4965         OverloadCandidateSet::iterator Best;
4966         for (NamedDecl *CD : Corrected) {
4967           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4968             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4969                                    OCS);
4970         }
4971         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4972         case OR_Success:
4973           ND = Best->FoundDecl;
4974           Corrected.setCorrectionDecl(ND);
4975           break;
4976         default:
4977           break;
4978         }
4979       }
4980       ND = ND->getUnderlyingDecl();
4981       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4982         return Corrected;
4983     }
4984   }
4985   return TypoCorrection();
4986 }
4987 
4988 /// ConvertArgumentsForCall - Converts the arguments specified in
4989 /// Args/NumArgs to the parameter types of the function FDecl with
4990 /// function prototype Proto. Call is the call expression itself, and
4991 /// Fn is the function expression. For a C++ member function, this
4992 /// routine does not attempt to convert the object argument. Returns
4993 /// true if the call is ill-formed.
4994 bool
4995 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4996                               FunctionDecl *FDecl,
4997                               const FunctionProtoType *Proto,
4998                               ArrayRef<Expr *> Args,
4999                               SourceLocation RParenLoc,
5000                               bool IsExecConfig) {
5001   // Bail out early if calling a builtin with custom typechecking.
5002   if (FDecl)
5003     if (unsigned ID = FDecl->getBuiltinID())
5004       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5005         return false;
5006 
5007   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5008   // assignment, to the types of the corresponding parameter, ...
5009   unsigned NumParams = Proto->getNumParams();
5010   bool Invalid = false;
5011   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5012   unsigned FnKind = Fn->getType()->isBlockPointerType()
5013                        ? 1 /* block */
5014                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5015                                        : 0 /* function */);
5016 
5017   // If too few arguments are available (and we don't have default
5018   // arguments for the remaining parameters), don't make the call.
5019   if (Args.size() < NumParams) {
5020     if (Args.size() < MinArgs) {
5021       TypoCorrection TC;
5022       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5023         unsigned diag_id =
5024             MinArgs == NumParams && !Proto->isVariadic()
5025                 ? diag::err_typecheck_call_too_few_args_suggest
5026                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5027         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5028                                         << static_cast<unsigned>(Args.size())
5029                                         << TC.getCorrectionRange());
5030       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5031         Diag(RParenLoc,
5032              MinArgs == NumParams && !Proto->isVariadic()
5033                  ? diag::err_typecheck_call_too_few_args_one
5034                  : diag::err_typecheck_call_too_few_args_at_least_one)
5035             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5036       else
5037         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5038                             ? diag::err_typecheck_call_too_few_args
5039                             : diag::err_typecheck_call_too_few_args_at_least)
5040             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5041             << Fn->getSourceRange();
5042 
5043       // Emit the location of the prototype.
5044       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5045         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5046 
5047       return true;
5048     }
5049     // We reserve space for the default arguments when we create
5050     // the call expression, before calling ConvertArgumentsForCall.
5051     assert((Call->getNumArgs() == NumParams) &&
5052            "We should have reserved space for the default arguments before!");
5053   }
5054 
5055   // If too many are passed and not variadic, error on the extras and drop
5056   // them.
5057   if (Args.size() > NumParams) {
5058     if (!Proto->isVariadic()) {
5059       TypoCorrection TC;
5060       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5061         unsigned diag_id =
5062             MinArgs == NumParams && !Proto->isVariadic()
5063                 ? diag::err_typecheck_call_too_many_args_suggest
5064                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5065         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5066                                         << static_cast<unsigned>(Args.size())
5067                                         << TC.getCorrectionRange());
5068       } else if (NumParams == 1 && FDecl &&
5069                  FDecl->getParamDecl(0)->getDeclName())
5070         Diag(Args[NumParams]->getBeginLoc(),
5071              MinArgs == NumParams
5072                  ? diag::err_typecheck_call_too_many_args_one
5073                  : diag::err_typecheck_call_too_many_args_at_most_one)
5074             << FnKind << FDecl->getParamDecl(0)
5075             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5076             << SourceRange(Args[NumParams]->getBeginLoc(),
5077                            Args.back()->getEndLoc());
5078       else
5079         Diag(Args[NumParams]->getBeginLoc(),
5080              MinArgs == NumParams
5081                  ? diag::err_typecheck_call_too_many_args
5082                  : diag::err_typecheck_call_too_many_args_at_most)
5083             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5084             << Fn->getSourceRange()
5085             << SourceRange(Args[NumParams]->getBeginLoc(),
5086                            Args.back()->getEndLoc());
5087 
5088       // Emit the location of the prototype.
5089       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5090         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5091 
5092       // This deletes the extra arguments.
5093       Call->shrinkNumArgs(NumParams);
5094       return true;
5095     }
5096   }
5097   SmallVector<Expr *, 8> AllArgs;
5098   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5099 
5100   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5101                                    AllArgs, CallType);
5102   if (Invalid)
5103     return true;
5104   unsigned TotalNumArgs = AllArgs.size();
5105   for (unsigned i = 0; i < TotalNumArgs; ++i)
5106     Call->setArg(i, AllArgs[i]);
5107 
5108   return false;
5109 }
5110 
5111 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5112                                   const FunctionProtoType *Proto,
5113                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5114                                   SmallVectorImpl<Expr *> &AllArgs,
5115                                   VariadicCallType CallType, bool AllowExplicit,
5116                                   bool IsListInitialization) {
5117   unsigned NumParams = Proto->getNumParams();
5118   bool Invalid = false;
5119   size_t ArgIx = 0;
5120   // Continue to check argument types (even if we have too few/many args).
5121   for (unsigned i = FirstParam; i < NumParams; i++) {
5122     QualType ProtoArgType = Proto->getParamType(i);
5123 
5124     Expr *Arg;
5125     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5126     if (ArgIx < Args.size()) {
5127       Arg = Args[ArgIx++];
5128 
5129       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5130                               diag::err_call_incomplete_argument, Arg))
5131         return true;
5132 
5133       // Strip the unbridged-cast placeholder expression off, if applicable.
5134       bool CFAudited = false;
5135       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5136           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5137           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5138         Arg = stripARCUnbridgedCast(Arg);
5139       else if (getLangOpts().ObjCAutoRefCount &&
5140                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5141                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5142         CFAudited = true;
5143 
5144       if (Proto->getExtParameterInfo(i).isNoEscape())
5145         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5146           BE->getBlockDecl()->setDoesNotEscape();
5147 
5148       InitializedEntity Entity =
5149           Param ? InitializedEntity::InitializeParameter(Context, Param,
5150                                                          ProtoArgType)
5151                 : InitializedEntity::InitializeParameter(
5152                       Context, ProtoArgType, Proto->isParamConsumed(i));
5153 
5154       // Remember that parameter belongs to a CF audited API.
5155       if (CFAudited)
5156         Entity.setParameterCFAudited();
5157 
5158       ExprResult ArgE = PerformCopyInitialization(
5159           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5160       if (ArgE.isInvalid())
5161         return true;
5162 
5163       Arg = ArgE.getAs<Expr>();
5164     } else {
5165       assert(Param && "can't use default arguments without a known callee");
5166 
5167       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5168       if (ArgExpr.isInvalid())
5169         return true;
5170 
5171       Arg = ArgExpr.getAs<Expr>();
5172     }
5173 
5174     // Check for array bounds violations for each argument to the call. This
5175     // check only triggers warnings when the argument isn't a more complex Expr
5176     // with its own checking, such as a BinaryOperator.
5177     CheckArrayAccess(Arg);
5178 
5179     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5180     CheckStaticArrayArgument(CallLoc, Param, Arg);
5181 
5182     AllArgs.push_back(Arg);
5183   }
5184 
5185   // If this is a variadic call, handle args passed through "...".
5186   if (CallType != VariadicDoesNotApply) {
5187     // Assume that extern "C" functions with variadic arguments that
5188     // return __unknown_anytype aren't *really* variadic.
5189     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5190         FDecl->isExternC()) {
5191       for (Expr *A : Args.slice(ArgIx)) {
5192         QualType paramType; // ignored
5193         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5194         Invalid |= arg.isInvalid();
5195         AllArgs.push_back(arg.get());
5196       }
5197 
5198     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5199     } else {
5200       for (Expr *A : Args.slice(ArgIx)) {
5201         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5202         Invalid |= Arg.isInvalid();
5203         AllArgs.push_back(Arg.get());
5204       }
5205     }
5206 
5207     // Check for array bounds violations.
5208     for (Expr *A : Args.slice(ArgIx))
5209       CheckArrayAccess(A);
5210   }
5211   return Invalid;
5212 }
5213 
5214 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5215   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5216   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5217     TL = DTL.getOriginalLoc();
5218   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5219     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5220       << ATL.getLocalSourceRange();
5221 }
5222 
5223 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5224 /// array parameter, check that it is non-null, and that if it is formed by
5225 /// array-to-pointer decay, the underlying array is sufficiently large.
5226 ///
5227 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5228 /// array type derivation, then for each call to the function, the value of the
5229 /// corresponding actual argument shall provide access to the first element of
5230 /// an array with at least as many elements as specified by the size expression.
5231 void
5232 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5233                                ParmVarDecl *Param,
5234                                const Expr *ArgExpr) {
5235   // Static array parameters are not supported in C++.
5236   if (!Param || getLangOpts().CPlusPlus)
5237     return;
5238 
5239   QualType OrigTy = Param->getOriginalType();
5240 
5241   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5242   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5243     return;
5244 
5245   if (ArgExpr->isNullPointerConstant(Context,
5246                                      Expr::NPC_NeverValueDependent)) {
5247     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5248     DiagnoseCalleeStaticArrayParam(*this, Param);
5249     return;
5250   }
5251 
5252   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5253   if (!CAT)
5254     return;
5255 
5256   const ConstantArrayType *ArgCAT =
5257     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5258   if (!ArgCAT)
5259     return;
5260 
5261   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5262                                              ArgCAT->getElementType())) {
5263     if (ArgCAT->getSize().ult(CAT->getSize())) {
5264       Diag(CallLoc, diag::warn_static_array_too_small)
5265           << ArgExpr->getSourceRange()
5266           << (unsigned)ArgCAT->getSize().getZExtValue()
5267           << (unsigned)CAT->getSize().getZExtValue() << 0;
5268       DiagnoseCalleeStaticArrayParam(*this, Param);
5269     }
5270     return;
5271   }
5272 
5273   Optional<CharUnits> ArgSize =
5274       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5275   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5276   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5277     Diag(CallLoc, diag::warn_static_array_too_small)
5278         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5279         << (unsigned)ParmSize->getQuantity() << 1;
5280     DiagnoseCalleeStaticArrayParam(*this, Param);
5281   }
5282 }
5283 
5284 /// Given a function expression of unknown-any type, try to rebuild it
5285 /// to have a function type.
5286 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5287 
5288 /// Is the given type a placeholder that we need to lower out
5289 /// immediately during argument processing?
5290 static bool isPlaceholderToRemoveAsArg(QualType type) {
5291   // Placeholders are never sugared.
5292   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5293   if (!placeholder) return false;
5294 
5295   switch (placeholder->getKind()) {
5296   // Ignore all the non-placeholder types.
5297 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5298   case BuiltinType::Id:
5299 #include "clang/Basic/OpenCLImageTypes.def"
5300 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5301   case BuiltinType::Id:
5302 #include "clang/Basic/OpenCLExtensionTypes.def"
5303   // In practice we'll never use this, since all SVE types are sugared
5304   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5305 #define SVE_TYPE(Name, Id, SingletonId) \
5306   case BuiltinType::Id:
5307 #include "clang/Basic/AArch64SVEACLETypes.def"
5308 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5309 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5310 #include "clang/AST/BuiltinTypes.def"
5311     return false;
5312 
5313   // We cannot lower out overload sets; they might validly be resolved
5314   // by the call machinery.
5315   case BuiltinType::Overload:
5316     return false;
5317 
5318   // Unbridged casts in ARC can be handled in some call positions and
5319   // should be left in place.
5320   case BuiltinType::ARCUnbridgedCast:
5321     return false;
5322 
5323   // Pseudo-objects should be converted as soon as possible.
5324   case BuiltinType::PseudoObject:
5325     return true;
5326 
5327   // The debugger mode could theoretically but currently does not try
5328   // to resolve unknown-typed arguments based on known parameter types.
5329   case BuiltinType::UnknownAny:
5330     return true;
5331 
5332   // These are always invalid as call arguments and should be reported.
5333   case BuiltinType::BoundMember:
5334   case BuiltinType::BuiltinFn:
5335   case BuiltinType::OMPArraySection:
5336     return true;
5337 
5338   }
5339   llvm_unreachable("bad builtin type kind");
5340 }
5341 
5342 /// Check an argument list for placeholders that we won't try to
5343 /// handle later.
5344 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5345   // Apply this processing to all the arguments at once instead of
5346   // dying at the first failure.
5347   bool hasInvalid = false;
5348   for (size_t i = 0, e = args.size(); i != e; i++) {
5349     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5350       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5351       if (result.isInvalid()) hasInvalid = true;
5352       else args[i] = result.get();
5353     } else if (hasInvalid) {
5354       (void)S.CorrectDelayedTyposInExpr(args[i]);
5355     }
5356   }
5357   return hasInvalid;
5358 }
5359 
5360 /// If a builtin function has a pointer argument with no explicit address
5361 /// space, then it should be able to accept a pointer to any address
5362 /// space as input.  In order to do this, we need to replace the
5363 /// standard builtin declaration with one that uses the same address space
5364 /// as the call.
5365 ///
5366 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5367 ///                  it does not contain any pointer arguments without
5368 ///                  an address space qualifer.  Otherwise the rewritten
5369 ///                  FunctionDecl is returned.
5370 /// TODO: Handle pointer return types.
5371 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5372                                                 FunctionDecl *FDecl,
5373                                                 MultiExprArg ArgExprs) {
5374 
5375   QualType DeclType = FDecl->getType();
5376   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5377 
5378   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5379       ArgExprs.size() < FT->getNumParams())
5380     return nullptr;
5381 
5382   bool NeedsNewDecl = false;
5383   unsigned i = 0;
5384   SmallVector<QualType, 8> OverloadParams;
5385 
5386   for (QualType ParamType : FT->param_types()) {
5387 
5388     // Convert array arguments to pointer to simplify type lookup.
5389     ExprResult ArgRes =
5390         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5391     if (ArgRes.isInvalid())
5392       return nullptr;
5393     Expr *Arg = ArgRes.get();
5394     QualType ArgType = Arg->getType();
5395     if (!ParamType->isPointerType() ||
5396         ParamType.getQualifiers().hasAddressSpace() ||
5397         !ArgType->isPointerType() ||
5398         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5399       OverloadParams.push_back(ParamType);
5400       continue;
5401     }
5402 
5403     QualType PointeeType = ParamType->getPointeeType();
5404     if (PointeeType.getQualifiers().hasAddressSpace())
5405       continue;
5406 
5407     NeedsNewDecl = true;
5408     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5409 
5410     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5411     OverloadParams.push_back(Context.getPointerType(PointeeType));
5412   }
5413 
5414   if (!NeedsNewDecl)
5415     return nullptr;
5416 
5417   FunctionProtoType::ExtProtoInfo EPI;
5418   EPI.Variadic = FT->isVariadic();
5419   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5420                                                 OverloadParams, EPI);
5421   DeclContext *Parent = FDecl->getParent();
5422   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5423                                                     FDecl->getLocation(),
5424                                                     FDecl->getLocation(),
5425                                                     FDecl->getIdentifier(),
5426                                                     OverloadTy,
5427                                                     /*TInfo=*/nullptr,
5428                                                     SC_Extern, false,
5429                                                     /*hasPrototype=*/true);
5430   SmallVector<ParmVarDecl*, 16> Params;
5431   FT = cast<FunctionProtoType>(OverloadTy);
5432   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5433     QualType ParamType = FT->getParamType(i);
5434     ParmVarDecl *Parm =
5435         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5436                                 SourceLocation(), nullptr, ParamType,
5437                                 /*TInfo=*/nullptr, SC_None, nullptr);
5438     Parm->setScopeInfo(0, i);
5439     Params.push_back(Parm);
5440   }
5441   OverloadDecl->setParams(Params);
5442   return OverloadDecl;
5443 }
5444 
5445 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5446                                     FunctionDecl *Callee,
5447                                     MultiExprArg ArgExprs) {
5448   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5449   // similar attributes) really don't like it when functions are called with an
5450   // invalid number of args.
5451   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5452                          /*PartialOverloading=*/false) &&
5453       !Callee->isVariadic())
5454     return;
5455   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5456     return;
5457 
5458   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5459     S.Diag(Fn->getBeginLoc(),
5460            isa<CXXMethodDecl>(Callee)
5461                ? diag::err_ovl_no_viable_member_function_in_call
5462                : diag::err_ovl_no_viable_function_in_call)
5463         << Callee << Callee->getSourceRange();
5464     S.Diag(Callee->getLocation(),
5465            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5466         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5467     return;
5468   }
5469 }
5470 
5471 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5472     const UnresolvedMemberExpr *const UME, Sema &S) {
5473 
5474   const auto GetFunctionLevelDCIfCXXClass =
5475       [](Sema &S) -> const CXXRecordDecl * {
5476     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5477     if (!DC || !DC->getParent())
5478       return nullptr;
5479 
5480     // If the call to some member function was made from within a member
5481     // function body 'M' return return 'M's parent.
5482     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5483       return MD->getParent()->getCanonicalDecl();
5484     // else the call was made from within a default member initializer of a
5485     // class, so return the class.
5486     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5487       return RD->getCanonicalDecl();
5488     return nullptr;
5489   };
5490   // If our DeclContext is neither a member function nor a class (in the
5491   // case of a lambda in a default member initializer), we can't have an
5492   // enclosing 'this'.
5493 
5494   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5495   if (!CurParentClass)
5496     return false;
5497 
5498   // The naming class for implicit member functions call is the class in which
5499   // name lookup starts.
5500   const CXXRecordDecl *const NamingClass =
5501       UME->getNamingClass()->getCanonicalDecl();
5502   assert(NamingClass && "Must have naming class even for implicit access");
5503 
5504   // If the unresolved member functions were found in a 'naming class' that is
5505   // related (either the same or derived from) to the class that contains the
5506   // member function that itself contained the implicit member access.
5507 
5508   return CurParentClass == NamingClass ||
5509          CurParentClass->isDerivedFrom(NamingClass);
5510 }
5511 
5512 static void
5513 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5514     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5515 
5516   if (!UME)
5517     return;
5518 
5519   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5520   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5521   // already been captured, or if this is an implicit member function call (if
5522   // it isn't, an attempt to capture 'this' should already have been made).
5523   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5524       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5525     return;
5526 
5527   // Check if the naming class in which the unresolved members were found is
5528   // related (same as or is a base of) to the enclosing class.
5529 
5530   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5531     return;
5532 
5533 
5534   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5535   // If the enclosing function is not dependent, then this lambda is
5536   // capture ready, so if we can capture this, do so.
5537   if (!EnclosingFunctionCtx->isDependentContext()) {
5538     // If the current lambda and all enclosing lambdas can capture 'this' -
5539     // then go ahead and capture 'this' (since our unresolved overload set
5540     // contains at least one non-static member function).
5541     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5542       S.CheckCXXThisCapture(CallLoc);
5543   } else if (S.CurContext->isDependentContext()) {
5544     // ... since this is an implicit member reference, that might potentially
5545     // involve a 'this' capture, mark 'this' for potential capture in
5546     // enclosing lambdas.
5547     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5548       CurLSI->addPotentialThisCapture(CallLoc);
5549   }
5550 }
5551 
5552 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5553                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5554                                Expr *ExecConfig) {
5555   ExprResult Call =
5556       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5557   if (Call.isInvalid())
5558     return Call;
5559 
5560   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5561   // language modes.
5562   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5563     if (ULE->hasExplicitTemplateArgs() &&
5564         ULE->decls_begin() == ULE->decls_end()) {
5565       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5566                                  ? diag::warn_cxx17_compat_adl_only_template_id
5567                                  : diag::ext_adl_only_template_id)
5568           << ULE->getName();
5569     }
5570   }
5571 
5572   return Call;
5573 }
5574 
5575 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5576 /// This provides the location of the left/right parens and a list of comma
5577 /// locations.
5578 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5579                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5580                                Expr *ExecConfig, bool IsExecConfig) {
5581   // Since this might be a postfix expression, get rid of ParenListExprs.
5582   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5583   if (Result.isInvalid()) return ExprError();
5584   Fn = Result.get();
5585 
5586   if (checkArgsForPlaceholders(*this, ArgExprs))
5587     return ExprError();
5588 
5589   if (getLangOpts().CPlusPlus) {
5590     // If this is a pseudo-destructor expression, build the call immediately.
5591     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5592       if (!ArgExprs.empty()) {
5593         // Pseudo-destructor calls should not have any arguments.
5594         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5595             << FixItHint::CreateRemoval(
5596                    SourceRange(ArgExprs.front()->getBeginLoc(),
5597                                ArgExprs.back()->getEndLoc()));
5598       }
5599 
5600       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5601                               VK_RValue, RParenLoc);
5602     }
5603     if (Fn->getType() == Context.PseudoObjectTy) {
5604       ExprResult result = CheckPlaceholderExpr(Fn);
5605       if (result.isInvalid()) return ExprError();
5606       Fn = result.get();
5607     }
5608 
5609     // Determine whether this is a dependent call inside a C++ template,
5610     // in which case we won't do any semantic analysis now.
5611     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5612       if (ExecConfig) {
5613         return CUDAKernelCallExpr::Create(
5614             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5615             Context.DependentTy, VK_RValue, RParenLoc);
5616       } else {
5617 
5618         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5619             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5620             Fn->getBeginLoc());
5621 
5622         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5623                                 VK_RValue, RParenLoc);
5624       }
5625     }
5626 
5627     // Determine whether this is a call to an object (C++ [over.call.object]).
5628     if (Fn->getType()->isRecordType())
5629       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5630                                           RParenLoc);
5631 
5632     if (Fn->getType() == Context.UnknownAnyTy) {
5633       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5634       if (result.isInvalid()) return ExprError();
5635       Fn = result.get();
5636     }
5637 
5638     if (Fn->getType() == Context.BoundMemberTy) {
5639       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5640                                        RParenLoc);
5641     }
5642   }
5643 
5644   // Check for overloaded calls.  This can happen even in C due to extensions.
5645   if (Fn->getType() == Context.OverloadTy) {
5646     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5647 
5648     // We aren't supposed to apply this logic if there's an '&' involved.
5649     if (!find.HasFormOfMemberPointer) {
5650       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5651         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5652                                 VK_RValue, RParenLoc);
5653       OverloadExpr *ovl = find.Expression;
5654       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5655         return BuildOverloadedCallExpr(
5656             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5657             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5658       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5659                                        RParenLoc);
5660     }
5661   }
5662 
5663   // If we're directly calling a function, get the appropriate declaration.
5664   if (Fn->getType() == Context.UnknownAnyTy) {
5665     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5666     if (result.isInvalid()) return ExprError();
5667     Fn = result.get();
5668   }
5669 
5670   Expr *NakedFn = Fn->IgnoreParens();
5671 
5672   bool CallingNDeclIndirectly = false;
5673   NamedDecl *NDecl = nullptr;
5674   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5675     if (UnOp->getOpcode() == UO_AddrOf) {
5676       CallingNDeclIndirectly = true;
5677       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5678     }
5679   }
5680 
5681   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5682     NDecl = DRE->getDecl();
5683 
5684     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5685     if (FDecl && FDecl->getBuiltinID()) {
5686       // Rewrite the function decl for this builtin by replacing parameters
5687       // with no explicit address space with the address space of the arguments
5688       // in ArgExprs.
5689       if ((FDecl =
5690                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5691         NDecl = FDecl;
5692         Fn = DeclRefExpr::Create(
5693             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5694             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5695             nullptr, DRE->isNonOdrUse());
5696       }
5697     }
5698   } else if (isa<MemberExpr>(NakedFn))
5699     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5700 
5701   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5702     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5703                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5704       return ExprError();
5705 
5706     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5707       return ExprError();
5708 
5709     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5710   }
5711 
5712   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5713                                ExecConfig, IsExecConfig);
5714 }
5715 
5716 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5717 ///
5718 /// __builtin_astype( value, dst type )
5719 ///
5720 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5721                                  SourceLocation BuiltinLoc,
5722                                  SourceLocation RParenLoc) {
5723   ExprValueKind VK = VK_RValue;
5724   ExprObjectKind OK = OK_Ordinary;
5725   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5726   QualType SrcTy = E->getType();
5727   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5728     return ExprError(Diag(BuiltinLoc,
5729                           diag::err_invalid_astype_of_different_size)
5730                      << DstTy
5731                      << SrcTy
5732                      << E->getSourceRange());
5733   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5734 }
5735 
5736 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5737 /// provided arguments.
5738 ///
5739 /// __builtin_convertvector( value, dst type )
5740 ///
5741 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5742                                         SourceLocation BuiltinLoc,
5743                                         SourceLocation RParenLoc) {
5744   TypeSourceInfo *TInfo;
5745   GetTypeFromParser(ParsedDestTy, &TInfo);
5746   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5747 }
5748 
5749 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5750 /// i.e. an expression not of \p OverloadTy.  The expression should
5751 /// unary-convert to an expression of function-pointer or
5752 /// block-pointer type.
5753 ///
5754 /// \param NDecl the declaration being called, if available
5755 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5756                                        SourceLocation LParenLoc,
5757                                        ArrayRef<Expr *> Args,
5758                                        SourceLocation RParenLoc, Expr *Config,
5759                                        bool IsExecConfig, ADLCallKind UsesADL) {
5760   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5761   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5762 
5763   // Functions with 'interrupt' attribute cannot be called directly.
5764   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5765     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5766     return ExprError();
5767   }
5768 
5769   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5770   // so there's some risk when calling out to non-interrupt handler functions
5771   // that the callee might not preserve them. This is easy to diagnose here,
5772   // but can be very challenging to debug.
5773   if (auto *Caller = getCurFunctionDecl())
5774     if (Caller->hasAttr<ARMInterruptAttr>()) {
5775       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5776       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5777         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5778     }
5779 
5780   // Promote the function operand.
5781   // We special-case function promotion here because we only allow promoting
5782   // builtin functions to function pointers in the callee of a call.
5783   ExprResult Result;
5784   QualType ResultTy;
5785   if (BuiltinID &&
5786       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5787     // Extract the return type from the (builtin) function pointer type.
5788     // FIXME Several builtins still have setType in
5789     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5790     // Builtins.def to ensure they are correct before removing setType calls.
5791     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5792     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5793     ResultTy = FDecl->getCallResultType();
5794   } else {
5795     Result = CallExprUnaryConversions(Fn);
5796     ResultTy = Context.BoolTy;
5797   }
5798   if (Result.isInvalid())
5799     return ExprError();
5800   Fn = Result.get();
5801 
5802   // Check for a valid function type, but only if it is not a builtin which
5803   // requires custom type checking. These will be handled by
5804   // CheckBuiltinFunctionCall below just after creation of the call expression.
5805   const FunctionType *FuncT = nullptr;
5806   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5807   retry:
5808     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5809       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5810       // have type pointer to function".
5811       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5812       if (!FuncT)
5813         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5814                          << Fn->getType() << Fn->getSourceRange());
5815     } else if (const BlockPointerType *BPT =
5816                    Fn->getType()->getAs<BlockPointerType>()) {
5817       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5818     } else {
5819       // Handle calls to expressions of unknown-any type.
5820       if (Fn->getType() == Context.UnknownAnyTy) {
5821         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5822         if (rewrite.isInvalid())
5823           return ExprError();
5824         Fn = rewrite.get();
5825         goto retry;
5826       }
5827 
5828       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5829                        << Fn->getType() << Fn->getSourceRange());
5830     }
5831   }
5832 
5833   // Get the number of parameters in the function prototype, if any.
5834   // We will allocate space for max(Args.size(), NumParams) arguments
5835   // in the call expression.
5836   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5837   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5838 
5839   CallExpr *TheCall;
5840   if (Config) {
5841     assert(UsesADL == ADLCallKind::NotADL &&
5842            "CUDAKernelCallExpr should not use ADL");
5843     TheCall =
5844         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5845                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5846   } else {
5847     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5848                                RParenLoc, NumParams, UsesADL);
5849   }
5850 
5851   if (!getLangOpts().CPlusPlus) {
5852     // Forget about the nulled arguments since typo correction
5853     // do not handle them well.
5854     TheCall->shrinkNumArgs(Args.size());
5855     // C cannot always handle TypoExpr nodes in builtin calls and direct
5856     // function calls as their argument checking don't necessarily handle
5857     // dependent types properly, so make sure any TypoExprs have been
5858     // dealt with.
5859     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5860     if (!Result.isUsable()) return ExprError();
5861     CallExpr *TheOldCall = TheCall;
5862     TheCall = dyn_cast<CallExpr>(Result.get());
5863     bool CorrectedTypos = TheCall != TheOldCall;
5864     if (!TheCall) return Result;
5865     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5866 
5867     // A new call expression node was created if some typos were corrected.
5868     // However it may not have been constructed with enough storage. In this
5869     // case, rebuild the node with enough storage. The waste of space is
5870     // immaterial since this only happens when some typos were corrected.
5871     if (CorrectedTypos && Args.size() < NumParams) {
5872       if (Config)
5873         TheCall = CUDAKernelCallExpr::Create(
5874             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5875             RParenLoc, NumParams);
5876       else
5877         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5878                                    RParenLoc, NumParams, UsesADL);
5879     }
5880     // We can now handle the nulled arguments for the default arguments.
5881     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5882   }
5883 
5884   // Bail out early if calling a builtin with custom type checking.
5885   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5886     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5887 
5888   if (getLangOpts().CUDA) {
5889     if (Config) {
5890       // CUDA: Kernel calls must be to global functions
5891       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5892         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5893             << FDecl << Fn->getSourceRange());
5894 
5895       // CUDA: Kernel function must have 'void' return type
5896       if (!FuncT->getReturnType()->isVoidType() &&
5897           !FuncT->getReturnType()->getAs<AutoType>() &&
5898           !FuncT->getReturnType()->isInstantiationDependentType())
5899         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5900             << Fn->getType() << Fn->getSourceRange());
5901     } else {
5902       // CUDA: Calls to global functions must be configured
5903       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5904         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5905             << FDecl << Fn->getSourceRange());
5906     }
5907   }
5908 
5909   // Check for a valid return type
5910   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5911                           FDecl))
5912     return ExprError();
5913 
5914   // We know the result type of the call, set it.
5915   TheCall->setType(FuncT->getCallResultType(Context));
5916   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5917 
5918   if (Proto) {
5919     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5920                                 IsExecConfig))
5921       return ExprError();
5922   } else {
5923     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5924 
5925     if (FDecl) {
5926       // Check if we have too few/too many template arguments, based
5927       // on our knowledge of the function definition.
5928       const FunctionDecl *Def = nullptr;
5929       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5930         Proto = Def->getType()->getAs<FunctionProtoType>();
5931        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5932           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5933           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5934       }
5935 
5936       // If the function we're calling isn't a function prototype, but we have
5937       // a function prototype from a prior declaratiom, use that prototype.
5938       if (!FDecl->hasPrototype())
5939         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5940     }
5941 
5942     // Promote the arguments (C99 6.5.2.2p6).
5943     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5944       Expr *Arg = Args[i];
5945 
5946       if (Proto && i < Proto->getNumParams()) {
5947         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5948             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5949         ExprResult ArgE =
5950             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5951         if (ArgE.isInvalid())
5952           return true;
5953 
5954         Arg = ArgE.getAs<Expr>();
5955 
5956       } else {
5957         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5958 
5959         if (ArgE.isInvalid())
5960           return true;
5961 
5962         Arg = ArgE.getAs<Expr>();
5963       }
5964 
5965       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5966                               diag::err_call_incomplete_argument, Arg))
5967         return ExprError();
5968 
5969       TheCall->setArg(i, Arg);
5970     }
5971   }
5972 
5973   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5974     if (!Method->isStatic())
5975       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5976         << Fn->getSourceRange());
5977 
5978   // Check for sentinels
5979   if (NDecl)
5980     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5981 
5982   // Do special checking on direct calls to functions.
5983   if (FDecl) {
5984     if (CheckFunctionCall(FDecl, TheCall, Proto))
5985       return ExprError();
5986 
5987     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5988 
5989     if (BuiltinID)
5990       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5991   } else if (NDecl) {
5992     if (CheckPointerCall(NDecl, TheCall, Proto))
5993       return ExprError();
5994   } else {
5995     if (CheckOtherCall(TheCall, Proto))
5996       return ExprError();
5997   }
5998 
5999   return MaybeBindToTemporary(TheCall);
6000 }
6001 
6002 ExprResult
6003 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6004                            SourceLocation RParenLoc, Expr *InitExpr) {
6005   assert(Ty && "ActOnCompoundLiteral(): missing type");
6006   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6007 
6008   TypeSourceInfo *TInfo;
6009   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6010   if (!TInfo)
6011     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6012 
6013   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6014 }
6015 
6016 ExprResult
6017 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6018                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6019   QualType literalType = TInfo->getType();
6020 
6021   if (literalType->isArrayType()) {
6022     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6023           diag::err_illegal_decl_array_incomplete_type,
6024           SourceRange(LParenLoc,
6025                       LiteralExpr->getSourceRange().getEnd())))
6026       return ExprError();
6027     if (literalType->isVariableArrayType())
6028       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6029         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6030   } else if (!literalType->isDependentType() &&
6031              RequireCompleteType(LParenLoc, literalType,
6032                diag::err_typecheck_decl_incomplete_type,
6033                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6034     return ExprError();
6035 
6036   InitializedEntity Entity
6037     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6038   InitializationKind Kind
6039     = InitializationKind::CreateCStyleCast(LParenLoc,
6040                                            SourceRange(LParenLoc, RParenLoc),
6041                                            /*InitList=*/true);
6042   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6043   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6044                                       &literalType);
6045   if (Result.isInvalid())
6046     return ExprError();
6047   LiteralExpr = Result.get();
6048 
6049   bool isFileScope = !CurContext->isFunctionOrMethod();
6050 
6051   // In C, compound literals are l-values for some reason.
6052   // For GCC compatibility, in C++, file-scope array compound literals with
6053   // constant initializers are also l-values, and compound literals are
6054   // otherwise prvalues.
6055   //
6056   // (GCC also treats C++ list-initialized file-scope array prvalues with
6057   // constant initializers as l-values, but that's non-conforming, so we don't
6058   // follow it there.)
6059   //
6060   // FIXME: It would be better to handle the lvalue cases as materializing and
6061   // lifetime-extending a temporary object, but our materialized temporaries
6062   // representation only supports lifetime extension from a variable, not "out
6063   // of thin air".
6064   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6065   // is bound to the result of applying array-to-pointer decay to the compound
6066   // literal.
6067   // FIXME: GCC supports compound literals of reference type, which should
6068   // obviously have a value kind derived from the kind of reference involved.
6069   ExprValueKind VK =
6070       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6071           ? VK_RValue
6072           : VK_LValue;
6073 
6074   if (isFileScope)
6075     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6076       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6077         Expr *Init = ILE->getInit(i);
6078         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6079       }
6080 
6081   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6082                                               VK, LiteralExpr, isFileScope);
6083   if (isFileScope) {
6084     if (!LiteralExpr->isTypeDependent() &&
6085         !LiteralExpr->isValueDependent() &&
6086         !literalType->isDependentType()) // C99 6.5.2.5p3
6087       if (CheckForConstantInitializer(LiteralExpr, literalType))
6088         return ExprError();
6089   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6090              literalType.getAddressSpace() != LangAS::Default) {
6091     // Embedded-C extensions to C99 6.5.2.5:
6092     //   "If the compound literal occurs inside the body of a function, the
6093     //   type name shall not be qualified by an address-space qualifier."
6094     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6095       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6096     return ExprError();
6097   }
6098 
6099   // Compound literals that have automatic storage duration are destroyed at
6100   // the end of the scope. Emit diagnostics if it is or contains a C union type
6101   // that is non-trivial to destruct.
6102   if (!isFileScope)
6103     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6104       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6105                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6106 
6107   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6108       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6109     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6110                                        E->getInitializer()->getExprLoc());
6111 
6112   return MaybeBindToTemporary(E);
6113 }
6114 
6115 ExprResult
6116 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6117                     SourceLocation RBraceLoc) {
6118   // Only produce each kind of designated initialization diagnostic once.
6119   SourceLocation FirstDesignator;
6120   bool DiagnosedArrayDesignator = false;
6121   bool DiagnosedNestedDesignator = false;
6122   bool DiagnosedMixedDesignator = false;
6123 
6124   // Check that any designated initializers are syntactically valid in the
6125   // current language mode.
6126   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6127     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6128       if (FirstDesignator.isInvalid())
6129         FirstDesignator = DIE->getBeginLoc();
6130 
6131       if (!getLangOpts().CPlusPlus)
6132         break;
6133 
6134       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6135         DiagnosedNestedDesignator = true;
6136         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6137           << DIE->getDesignatorsSourceRange();
6138       }
6139 
6140       for (auto &Desig : DIE->designators()) {
6141         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6142           DiagnosedArrayDesignator = true;
6143           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6144             << Desig.getSourceRange();
6145         }
6146       }
6147 
6148       if (!DiagnosedMixedDesignator &&
6149           !isa<DesignatedInitExpr>(InitArgList[0])) {
6150         DiagnosedMixedDesignator = true;
6151         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6152           << DIE->getSourceRange();
6153         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6154           << InitArgList[0]->getSourceRange();
6155       }
6156     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6157                isa<DesignatedInitExpr>(InitArgList[0])) {
6158       DiagnosedMixedDesignator = true;
6159       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6160       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6161         << DIE->getSourceRange();
6162       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6163         << InitArgList[I]->getSourceRange();
6164     }
6165   }
6166 
6167   if (FirstDesignator.isValid()) {
6168     // Only diagnose designated initiaization as a C++20 extension if we didn't
6169     // already diagnose use of (non-C++20) C99 designator syntax.
6170     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6171         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6172       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6173                                 ? diag::warn_cxx17_compat_designated_init
6174                                 : diag::ext_cxx_designated_init);
6175     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6176       Diag(FirstDesignator, diag::ext_designated_init);
6177     }
6178   }
6179 
6180   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6181 }
6182 
6183 ExprResult
6184 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6185                     SourceLocation RBraceLoc) {
6186   // Semantic analysis for initializers is done by ActOnDeclarator() and
6187   // CheckInitializer() - it requires knowledge of the object being initialized.
6188 
6189   // Immediately handle non-overload placeholders.  Overloads can be
6190   // resolved contextually, but everything else here can't.
6191   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6192     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6193       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6194 
6195       // Ignore failures; dropping the entire initializer list because
6196       // of one failure would be terrible for indexing/etc.
6197       if (result.isInvalid()) continue;
6198 
6199       InitArgList[I] = result.get();
6200     }
6201   }
6202 
6203   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6204                                                RBraceLoc);
6205   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6206   return E;
6207 }
6208 
6209 /// Do an explicit extend of the given block pointer if we're in ARC.
6210 void Sema::maybeExtendBlockObject(ExprResult &E) {
6211   assert(E.get()->getType()->isBlockPointerType());
6212   assert(E.get()->isRValue());
6213 
6214   // Only do this in an r-value context.
6215   if (!getLangOpts().ObjCAutoRefCount) return;
6216 
6217   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6218                                CK_ARCExtendBlockObject, E.get(),
6219                                /*base path*/ nullptr, VK_RValue);
6220   Cleanup.setExprNeedsCleanups(true);
6221 }
6222 
6223 /// Prepare a conversion of the given expression to an ObjC object
6224 /// pointer type.
6225 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6226   QualType type = E.get()->getType();
6227   if (type->isObjCObjectPointerType()) {
6228     return CK_BitCast;
6229   } else if (type->isBlockPointerType()) {
6230     maybeExtendBlockObject(E);
6231     return CK_BlockPointerToObjCPointerCast;
6232   } else {
6233     assert(type->isPointerType());
6234     return CK_CPointerToObjCPointerCast;
6235   }
6236 }
6237 
6238 /// Prepares for a scalar cast, performing all the necessary stages
6239 /// except the final cast and returning the kind required.
6240 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6241   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6242   // Also, callers should have filtered out the invalid cases with
6243   // pointers.  Everything else should be possible.
6244 
6245   QualType SrcTy = Src.get()->getType();
6246   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6247     return CK_NoOp;
6248 
6249   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6250   case Type::STK_MemberPointer:
6251     llvm_unreachable("member pointer type in C");
6252 
6253   case Type::STK_CPointer:
6254   case Type::STK_BlockPointer:
6255   case Type::STK_ObjCObjectPointer:
6256     switch (DestTy->getScalarTypeKind()) {
6257     case Type::STK_CPointer: {
6258       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6259       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6260       if (SrcAS != DestAS)
6261         return CK_AddressSpaceConversion;
6262       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6263         return CK_NoOp;
6264       return CK_BitCast;
6265     }
6266     case Type::STK_BlockPointer:
6267       return (SrcKind == Type::STK_BlockPointer
6268                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6269     case Type::STK_ObjCObjectPointer:
6270       if (SrcKind == Type::STK_ObjCObjectPointer)
6271         return CK_BitCast;
6272       if (SrcKind == Type::STK_CPointer)
6273         return CK_CPointerToObjCPointerCast;
6274       maybeExtendBlockObject(Src);
6275       return CK_BlockPointerToObjCPointerCast;
6276     case Type::STK_Bool:
6277       return CK_PointerToBoolean;
6278     case Type::STK_Integral:
6279       return CK_PointerToIntegral;
6280     case Type::STK_Floating:
6281     case Type::STK_FloatingComplex:
6282     case Type::STK_IntegralComplex:
6283     case Type::STK_MemberPointer:
6284     case Type::STK_FixedPoint:
6285       llvm_unreachable("illegal cast from pointer");
6286     }
6287     llvm_unreachable("Should have returned before this");
6288 
6289   case Type::STK_FixedPoint:
6290     switch (DestTy->getScalarTypeKind()) {
6291     case Type::STK_FixedPoint:
6292       return CK_FixedPointCast;
6293     case Type::STK_Bool:
6294       return CK_FixedPointToBoolean;
6295     case Type::STK_Integral:
6296       return CK_FixedPointToIntegral;
6297     case Type::STK_Floating:
6298     case Type::STK_IntegralComplex:
6299     case Type::STK_FloatingComplex:
6300       Diag(Src.get()->getExprLoc(),
6301            diag::err_unimplemented_conversion_with_fixed_point_type)
6302           << DestTy;
6303       return CK_IntegralCast;
6304     case Type::STK_CPointer:
6305     case Type::STK_ObjCObjectPointer:
6306     case Type::STK_BlockPointer:
6307     case Type::STK_MemberPointer:
6308       llvm_unreachable("illegal cast to pointer type");
6309     }
6310     llvm_unreachable("Should have returned before this");
6311 
6312   case Type::STK_Bool: // casting from bool is like casting from an integer
6313   case Type::STK_Integral:
6314     switch (DestTy->getScalarTypeKind()) {
6315     case Type::STK_CPointer:
6316     case Type::STK_ObjCObjectPointer:
6317     case Type::STK_BlockPointer:
6318       if (Src.get()->isNullPointerConstant(Context,
6319                                            Expr::NPC_ValueDependentIsNull))
6320         return CK_NullToPointer;
6321       return CK_IntegralToPointer;
6322     case Type::STK_Bool:
6323       return CK_IntegralToBoolean;
6324     case Type::STK_Integral:
6325       return CK_IntegralCast;
6326     case Type::STK_Floating:
6327       return CK_IntegralToFloating;
6328     case Type::STK_IntegralComplex:
6329       Src = ImpCastExprToType(Src.get(),
6330                       DestTy->castAs<ComplexType>()->getElementType(),
6331                       CK_IntegralCast);
6332       return CK_IntegralRealToComplex;
6333     case Type::STK_FloatingComplex:
6334       Src = ImpCastExprToType(Src.get(),
6335                       DestTy->castAs<ComplexType>()->getElementType(),
6336                       CK_IntegralToFloating);
6337       return CK_FloatingRealToComplex;
6338     case Type::STK_MemberPointer:
6339       llvm_unreachable("member pointer type in C");
6340     case Type::STK_FixedPoint:
6341       return CK_IntegralToFixedPoint;
6342     }
6343     llvm_unreachable("Should have returned before this");
6344 
6345   case Type::STK_Floating:
6346     switch (DestTy->getScalarTypeKind()) {
6347     case Type::STK_Floating:
6348       return CK_FloatingCast;
6349     case Type::STK_Bool:
6350       return CK_FloatingToBoolean;
6351     case Type::STK_Integral:
6352       return CK_FloatingToIntegral;
6353     case Type::STK_FloatingComplex:
6354       Src = ImpCastExprToType(Src.get(),
6355                               DestTy->castAs<ComplexType>()->getElementType(),
6356                               CK_FloatingCast);
6357       return CK_FloatingRealToComplex;
6358     case Type::STK_IntegralComplex:
6359       Src = ImpCastExprToType(Src.get(),
6360                               DestTy->castAs<ComplexType>()->getElementType(),
6361                               CK_FloatingToIntegral);
6362       return CK_IntegralRealToComplex;
6363     case Type::STK_CPointer:
6364     case Type::STK_ObjCObjectPointer:
6365     case Type::STK_BlockPointer:
6366       llvm_unreachable("valid float->pointer cast?");
6367     case Type::STK_MemberPointer:
6368       llvm_unreachable("member pointer type in C");
6369     case Type::STK_FixedPoint:
6370       Diag(Src.get()->getExprLoc(),
6371            diag::err_unimplemented_conversion_with_fixed_point_type)
6372           << SrcTy;
6373       return CK_IntegralCast;
6374     }
6375     llvm_unreachable("Should have returned before this");
6376 
6377   case Type::STK_FloatingComplex:
6378     switch (DestTy->getScalarTypeKind()) {
6379     case Type::STK_FloatingComplex:
6380       return CK_FloatingComplexCast;
6381     case Type::STK_IntegralComplex:
6382       return CK_FloatingComplexToIntegralComplex;
6383     case Type::STK_Floating: {
6384       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6385       if (Context.hasSameType(ET, DestTy))
6386         return CK_FloatingComplexToReal;
6387       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6388       return CK_FloatingCast;
6389     }
6390     case Type::STK_Bool:
6391       return CK_FloatingComplexToBoolean;
6392     case Type::STK_Integral:
6393       Src = ImpCastExprToType(Src.get(),
6394                               SrcTy->castAs<ComplexType>()->getElementType(),
6395                               CK_FloatingComplexToReal);
6396       return CK_FloatingToIntegral;
6397     case Type::STK_CPointer:
6398     case Type::STK_ObjCObjectPointer:
6399     case Type::STK_BlockPointer:
6400       llvm_unreachable("valid complex float->pointer cast?");
6401     case Type::STK_MemberPointer:
6402       llvm_unreachable("member pointer type in C");
6403     case Type::STK_FixedPoint:
6404       Diag(Src.get()->getExprLoc(),
6405            diag::err_unimplemented_conversion_with_fixed_point_type)
6406           << SrcTy;
6407       return CK_IntegralCast;
6408     }
6409     llvm_unreachable("Should have returned before this");
6410 
6411   case Type::STK_IntegralComplex:
6412     switch (DestTy->getScalarTypeKind()) {
6413     case Type::STK_FloatingComplex:
6414       return CK_IntegralComplexToFloatingComplex;
6415     case Type::STK_IntegralComplex:
6416       return CK_IntegralComplexCast;
6417     case Type::STK_Integral: {
6418       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6419       if (Context.hasSameType(ET, DestTy))
6420         return CK_IntegralComplexToReal;
6421       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6422       return CK_IntegralCast;
6423     }
6424     case Type::STK_Bool:
6425       return CK_IntegralComplexToBoolean;
6426     case Type::STK_Floating:
6427       Src = ImpCastExprToType(Src.get(),
6428                               SrcTy->castAs<ComplexType>()->getElementType(),
6429                               CK_IntegralComplexToReal);
6430       return CK_IntegralToFloating;
6431     case Type::STK_CPointer:
6432     case Type::STK_ObjCObjectPointer:
6433     case Type::STK_BlockPointer:
6434       llvm_unreachable("valid complex int->pointer cast?");
6435     case Type::STK_MemberPointer:
6436       llvm_unreachable("member pointer type in C");
6437     case Type::STK_FixedPoint:
6438       Diag(Src.get()->getExprLoc(),
6439            diag::err_unimplemented_conversion_with_fixed_point_type)
6440           << SrcTy;
6441       return CK_IntegralCast;
6442     }
6443     llvm_unreachable("Should have returned before this");
6444   }
6445 
6446   llvm_unreachable("Unhandled scalar cast");
6447 }
6448 
6449 static bool breakDownVectorType(QualType type, uint64_t &len,
6450                                 QualType &eltType) {
6451   // Vectors are simple.
6452   if (const VectorType *vecType = type->getAs<VectorType>()) {
6453     len = vecType->getNumElements();
6454     eltType = vecType->getElementType();
6455     assert(eltType->isScalarType());
6456     return true;
6457   }
6458 
6459   // We allow lax conversion to and from non-vector types, but only if
6460   // they're real types (i.e. non-complex, non-pointer scalar types).
6461   if (!type->isRealType()) return false;
6462 
6463   len = 1;
6464   eltType = type;
6465   return true;
6466 }
6467 
6468 /// Are the two types lax-compatible vector types?  That is, given
6469 /// that one of them is a vector, do they have equal storage sizes,
6470 /// where the storage size is the number of elements times the element
6471 /// size?
6472 ///
6473 /// This will also return false if either of the types is neither a
6474 /// vector nor a real type.
6475 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6476   assert(destTy->isVectorType() || srcTy->isVectorType());
6477 
6478   // Disallow lax conversions between scalars and ExtVectors (these
6479   // conversions are allowed for other vector types because common headers
6480   // depend on them).  Most scalar OP ExtVector cases are handled by the
6481   // splat path anyway, which does what we want (convert, not bitcast).
6482   // What this rules out for ExtVectors is crazy things like char4*float.
6483   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6484   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6485 
6486   uint64_t srcLen, destLen;
6487   QualType srcEltTy, destEltTy;
6488   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6489   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6490 
6491   // ASTContext::getTypeSize will return the size rounded up to a
6492   // power of 2, so instead of using that, we need to use the raw
6493   // element size multiplied by the element count.
6494   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6495   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6496 
6497   return (srcLen * srcEltSize == destLen * destEltSize);
6498 }
6499 
6500 /// Is this a legal conversion between two types, one of which is
6501 /// known to be a vector type?
6502 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6503   assert(destTy->isVectorType() || srcTy->isVectorType());
6504 
6505   switch (Context.getLangOpts().getLaxVectorConversions()) {
6506   case LangOptions::LaxVectorConversionKind::None:
6507     return false;
6508 
6509   case LangOptions::LaxVectorConversionKind::Integer:
6510     if (!srcTy->isIntegralOrEnumerationType()) {
6511       auto *Vec = srcTy->getAs<VectorType>();
6512       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6513         return false;
6514     }
6515     if (!destTy->isIntegralOrEnumerationType()) {
6516       auto *Vec = destTy->getAs<VectorType>();
6517       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6518         return false;
6519     }
6520     // OK, integer (vector) -> integer (vector) bitcast.
6521     break;
6522 
6523     case LangOptions::LaxVectorConversionKind::All:
6524     break;
6525   }
6526 
6527   return areLaxCompatibleVectorTypes(srcTy, destTy);
6528 }
6529 
6530 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6531                            CastKind &Kind) {
6532   assert(VectorTy->isVectorType() && "Not a vector type!");
6533 
6534   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6535     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6536       return Diag(R.getBegin(),
6537                   Ty->isVectorType() ?
6538                   diag::err_invalid_conversion_between_vectors :
6539                   diag::err_invalid_conversion_between_vector_and_integer)
6540         << VectorTy << Ty << R;
6541   } else
6542     return Diag(R.getBegin(),
6543                 diag::err_invalid_conversion_between_vector_and_scalar)
6544       << VectorTy << Ty << R;
6545 
6546   Kind = CK_BitCast;
6547   return false;
6548 }
6549 
6550 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6551   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6552 
6553   if (DestElemTy == SplattedExpr->getType())
6554     return SplattedExpr;
6555 
6556   assert(DestElemTy->isFloatingType() ||
6557          DestElemTy->isIntegralOrEnumerationType());
6558 
6559   CastKind CK;
6560   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6561     // OpenCL requires that we convert `true` boolean expressions to -1, but
6562     // only when splatting vectors.
6563     if (DestElemTy->isFloatingType()) {
6564       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6565       // in two steps: boolean to signed integral, then to floating.
6566       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6567                                                  CK_BooleanToSignedIntegral);
6568       SplattedExpr = CastExprRes.get();
6569       CK = CK_IntegralToFloating;
6570     } else {
6571       CK = CK_BooleanToSignedIntegral;
6572     }
6573   } else {
6574     ExprResult CastExprRes = SplattedExpr;
6575     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6576     if (CastExprRes.isInvalid())
6577       return ExprError();
6578     SplattedExpr = CastExprRes.get();
6579   }
6580   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6581 }
6582 
6583 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6584                                     Expr *CastExpr, CastKind &Kind) {
6585   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6586 
6587   QualType SrcTy = CastExpr->getType();
6588 
6589   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6590   // an ExtVectorType.
6591   // In OpenCL, casts between vectors of different types are not allowed.
6592   // (See OpenCL 6.2).
6593   if (SrcTy->isVectorType()) {
6594     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6595         (getLangOpts().OpenCL &&
6596          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6597       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6598         << DestTy << SrcTy << R;
6599       return ExprError();
6600     }
6601     Kind = CK_BitCast;
6602     return CastExpr;
6603   }
6604 
6605   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6606   // conversion will take place first from scalar to elt type, and then
6607   // splat from elt type to vector.
6608   if (SrcTy->isPointerType())
6609     return Diag(R.getBegin(),
6610                 diag::err_invalid_conversion_between_vector_and_scalar)
6611       << DestTy << SrcTy << R;
6612 
6613   Kind = CK_VectorSplat;
6614   return prepareVectorSplat(DestTy, CastExpr);
6615 }
6616 
6617 ExprResult
6618 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6619                     Declarator &D, ParsedType &Ty,
6620                     SourceLocation RParenLoc, Expr *CastExpr) {
6621   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6622          "ActOnCastExpr(): missing type or expr");
6623 
6624   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6625   if (D.isInvalidType())
6626     return ExprError();
6627 
6628   if (getLangOpts().CPlusPlus) {
6629     // Check that there are no default arguments (C++ only).
6630     CheckExtraCXXDefaultArguments(D);
6631   } else {
6632     // Make sure any TypoExprs have been dealt with.
6633     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6634     if (!Res.isUsable())
6635       return ExprError();
6636     CastExpr = Res.get();
6637   }
6638 
6639   checkUnusedDeclAttributes(D);
6640 
6641   QualType castType = castTInfo->getType();
6642   Ty = CreateParsedType(castType, castTInfo);
6643 
6644   bool isVectorLiteral = false;
6645 
6646   // Check for an altivec or OpenCL literal,
6647   // i.e. all the elements are integer constants.
6648   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6649   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6650   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6651        && castType->isVectorType() && (PE || PLE)) {
6652     if (PLE && PLE->getNumExprs() == 0) {
6653       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6654       return ExprError();
6655     }
6656     if (PE || PLE->getNumExprs() == 1) {
6657       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6658       if (!E->getType()->isVectorType())
6659         isVectorLiteral = true;
6660     }
6661     else
6662       isVectorLiteral = true;
6663   }
6664 
6665   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6666   // then handle it as such.
6667   if (isVectorLiteral)
6668     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6669 
6670   // If the Expr being casted is a ParenListExpr, handle it specially.
6671   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6672   // sequence of BinOp comma operators.
6673   if (isa<ParenListExpr>(CastExpr)) {
6674     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6675     if (Result.isInvalid()) return ExprError();
6676     CastExpr = Result.get();
6677   }
6678 
6679   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6680       !getSourceManager().isInSystemMacro(LParenLoc))
6681     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6682 
6683   CheckTollFreeBridgeCast(castType, CastExpr);
6684 
6685   CheckObjCBridgeRelatedCast(castType, CastExpr);
6686 
6687   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6688 
6689   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6690 }
6691 
6692 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6693                                     SourceLocation RParenLoc, Expr *E,
6694                                     TypeSourceInfo *TInfo) {
6695   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6696          "Expected paren or paren list expression");
6697 
6698   Expr **exprs;
6699   unsigned numExprs;
6700   Expr *subExpr;
6701   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6702   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6703     LiteralLParenLoc = PE->getLParenLoc();
6704     LiteralRParenLoc = PE->getRParenLoc();
6705     exprs = PE->getExprs();
6706     numExprs = PE->getNumExprs();
6707   } else { // isa<ParenExpr> by assertion at function entrance
6708     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6709     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6710     subExpr = cast<ParenExpr>(E)->getSubExpr();
6711     exprs = &subExpr;
6712     numExprs = 1;
6713   }
6714 
6715   QualType Ty = TInfo->getType();
6716   assert(Ty->isVectorType() && "Expected vector type");
6717 
6718   SmallVector<Expr *, 8> initExprs;
6719   const VectorType *VTy = Ty->castAs<VectorType>();
6720   unsigned numElems = VTy->getNumElements();
6721 
6722   // '(...)' form of vector initialization in AltiVec: the number of
6723   // initializers must be one or must match the size of the vector.
6724   // If a single value is specified in the initializer then it will be
6725   // replicated to all the components of the vector
6726   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6727     // The number of initializers must be one or must match the size of the
6728     // vector. If a single value is specified in the initializer then it will
6729     // be replicated to all the components of the vector
6730     if (numExprs == 1) {
6731       QualType ElemTy = VTy->getElementType();
6732       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6733       if (Literal.isInvalid())
6734         return ExprError();
6735       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6736                                   PrepareScalarCast(Literal, ElemTy));
6737       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6738     }
6739     else if (numExprs < numElems) {
6740       Diag(E->getExprLoc(),
6741            diag::err_incorrect_number_of_vector_initializers);
6742       return ExprError();
6743     }
6744     else
6745       initExprs.append(exprs, exprs + numExprs);
6746   }
6747   else {
6748     // For OpenCL, when the number of initializers is a single value,
6749     // it will be replicated to all components of the vector.
6750     if (getLangOpts().OpenCL &&
6751         VTy->getVectorKind() == VectorType::GenericVector &&
6752         numExprs == 1) {
6753         QualType ElemTy = VTy->getElementType();
6754         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6755         if (Literal.isInvalid())
6756           return ExprError();
6757         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6758                                     PrepareScalarCast(Literal, ElemTy));
6759         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6760     }
6761 
6762     initExprs.append(exprs, exprs + numExprs);
6763   }
6764   // FIXME: This means that pretty-printing the final AST will produce curly
6765   // braces instead of the original commas.
6766   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6767                                                    initExprs, LiteralRParenLoc);
6768   initE->setType(Ty);
6769   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6770 }
6771 
6772 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6773 /// the ParenListExpr into a sequence of comma binary operators.
6774 ExprResult
6775 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6776   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6777   if (!E)
6778     return OrigExpr;
6779 
6780   ExprResult Result(E->getExpr(0));
6781 
6782   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6783     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6784                         E->getExpr(i));
6785 
6786   if (Result.isInvalid()) return ExprError();
6787 
6788   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6789 }
6790 
6791 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6792                                     SourceLocation R,
6793                                     MultiExprArg Val) {
6794   return ParenListExpr::Create(Context, L, Val, R);
6795 }
6796 
6797 /// Emit a specialized diagnostic when one expression is a null pointer
6798 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6799 /// emitted.
6800 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6801                                       SourceLocation QuestionLoc) {
6802   Expr *NullExpr = LHSExpr;
6803   Expr *NonPointerExpr = RHSExpr;
6804   Expr::NullPointerConstantKind NullKind =
6805       NullExpr->isNullPointerConstant(Context,
6806                                       Expr::NPC_ValueDependentIsNotNull);
6807 
6808   if (NullKind == Expr::NPCK_NotNull) {
6809     NullExpr = RHSExpr;
6810     NonPointerExpr = LHSExpr;
6811     NullKind =
6812         NullExpr->isNullPointerConstant(Context,
6813                                         Expr::NPC_ValueDependentIsNotNull);
6814   }
6815 
6816   if (NullKind == Expr::NPCK_NotNull)
6817     return false;
6818 
6819   if (NullKind == Expr::NPCK_ZeroExpression)
6820     return false;
6821 
6822   if (NullKind == Expr::NPCK_ZeroLiteral) {
6823     // In this case, check to make sure that we got here from a "NULL"
6824     // string in the source code.
6825     NullExpr = NullExpr->IgnoreParenImpCasts();
6826     SourceLocation loc = NullExpr->getExprLoc();
6827     if (!findMacroSpelling(loc, "NULL"))
6828       return false;
6829   }
6830 
6831   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6832   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6833       << NonPointerExpr->getType() << DiagType
6834       << NonPointerExpr->getSourceRange();
6835   return true;
6836 }
6837 
6838 /// Return false if the condition expression is valid, true otherwise.
6839 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6840   QualType CondTy = Cond->getType();
6841 
6842   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6843   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6844     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6845       << CondTy << Cond->getSourceRange();
6846     return true;
6847   }
6848 
6849   // C99 6.5.15p2
6850   if (CondTy->isScalarType()) return false;
6851 
6852   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6853     << CondTy << Cond->getSourceRange();
6854   return true;
6855 }
6856 
6857 /// Handle when one or both operands are void type.
6858 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6859                                          ExprResult &RHS) {
6860     Expr *LHSExpr = LHS.get();
6861     Expr *RHSExpr = RHS.get();
6862 
6863     if (!LHSExpr->getType()->isVoidType())
6864       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6865           << RHSExpr->getSourceRange();
6866     if (!RHSExpr->getType()->isVoidType())
6867       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6868           << LHSExpr->getSourceRange();
6869     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6870     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6871     return S.Context.VoidTy;
6872 }
6873 
6874 /// Return false if the NullExpr can be promoted to PointerTy,
6875 /// true otherwise.
6876 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6877                                         QualType PointerTy) {
6878   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6879       !NullExpr.get()->isNullPointerConstant(S.Context,
6880                                             Expr::NPC_ValueDependentIsNull))
6881     return true;
6882 
6883   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6884   return false;
6885 }
6886 
6887 /// Checks compatibility between two pointers and return the resulting
6888 /// type.
6889 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6890                                                      ExprResult &RHS,
6891                                                      SourceLocation Loc) {
6892   QualType LHSTy = LHS.get()->getType();
6893   QualType RHSTy = RHS.get()->getType();
6894 
6895   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6896     // Two identical pointers types are always compatible.
6897     return LHSTy;
6898   }
6899 
6900   QualType lhptee, rhptee;
6901 
6902   // Get the pointee types.
6903   bool IsBlockPointer = false;
6904   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6905     lhptee = LHSBTy->getPointeeType();
6906     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6907     IsBlockPointer = true;
6908   } else {
6909     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6910     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6911   }
6912 
6913   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6914   // differently qualified versions of compatible types, the result type is
6915   // a pointer to an appropriately qualified version of the composite
6916   // type.
6917 
6918   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6919   // clause doesn't make sense for our extensions. E.g. address space 2 should
6920   // be incompatible with address space 3: they may live on different devices or
6921   // anything.
6922   Qualifiers lhQual = lhptee.getQualifiers();
6923   Qualifiers rhQual = rhptee.getQualifiers();
6924 
6925   LangAS ResultAddrSpace = LangAS::Default;
6926   LangAS LAddrSpace = lhQual.getAddressSpace();
6927   LangAS RAddrSpace = rhQual.getAddressSpace();
6928 
6929   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6930   // spaces is disallowed.
6931   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6932     ResultAddrSpace = LAddrSpace;
6933   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6934     ResultAddrSpace = RAddrSpace;
6935   else {
6936     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6937         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6938         << RHS.get()->getSourceRange();
6939     return QualType();
6940   }
6941 
6942   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6943   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6944   lhQual.removeCVRQualifiers();
6945   rhQual.removeCVRQualifiers();
6946 
6947   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6948   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6949   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6950   // qual types are compatible iff
6951   //  * corresponded types are compatible
6952   //  * CVR qualifiers are equal
6953   //  * address spaces are equal
6954   // Thus for conditional operator we merge CVR and address space unqualified
6955   // pointees and if there is a composite type we return a pointer to it with
6956   // merged qualifiers.
6957   LHSCastKind =
6958       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6959   RHSCastKind =
6960       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6961   lhQual.removeAddressSpace();
6962   rhQual.removeAddressSpace();
6963 
6964   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6965   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6966 
6967   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6968 
6969   if (CompositeTy.isNull()) {
6970     // In this situation, we assume void* type. No especially good
6971     // reason, but this is what gcc does, and we do have to pick
6972     // to get a consistent AST.
6973     QualType incompatTy;
6974     incompatTy = S.Context.getPointerType(
6975         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6976     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6977     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6978 
6979     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6980     // for casts between types with incompatible address space qualifiers.
6981     // For the following code the compiler produces casts between global and
6982     // local address spaces of the corresponded innermost pointees:
6983     // local int *global *a;
6984     // global int *global *b;
6985     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6986     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6987         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6988         << RHS.get()->getSourceRange();
6989 
6990     return incompatTy;
6991   }
6992 
6993   // The pointer types are compatible.
6994   // In case of OpenCL ResultTy should have the address space qualifier
6995   // which is a superset of address spaces of both the 2nd and the 3rd
6996   // operands of the conditional operator.
6997   QualType ResultTy = [&, ResultAddrSpace]() {
6998     if (S.getLangOpts().OpenCL) {
6999       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7000       CompositeQuals.setAddressSpace(ResultAddrSpace);
7001       return S.Context
7002           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7003           .withCVRQualifiers(MergedCVRQual);
7004     }
7005     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7006   }();
7007   if (IsBlockPointer)
7008     ResultTy = S.Context.getBlockPointerType(ResultTy);
7009   else
7010     ResultTy = S.Context.getPointerType(ResultTy);
7011 
7012   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7013   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7014   return ResultTy;
7015 }
7016 
7017 /// Return the resulting type when the operands are both block pointers.
7018 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7019                                                           ExprResult &LHS,
7020                                                           ExprResult &RHS,
7021                                                           SourceLocation Loc) {
7022   QualType LHSTy = LHS.get()->getType();
7023   QualType RHSTy = RHS.get()->getType();
7024 
7025   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7026     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7027       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7028       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7029       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7030       return destType;
7031     }
7032     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7033       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7034       << RHS.get()->getSourceRange();
7035     return QualType();
7036   }
7037 
7038   // We have 2 block pointer types.
7039   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7040 }
7041 
7042 /// Return the resulting type when the operands are both pointers.
7043 static QualType
7044 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7045                                             ExprResult &RHS,
7046                                             SourceLocation Loc) {
7047   // get the pointer types
7048   QualType LHSTy = LHS.get()->getType();
7049   QualType RHSTy = RHS.get()->getType();
7050 
7051   // get the "pointed to" types
7052   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7053   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7054 
7055   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7056   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7057     // Figure out necessary qualifiers (C99 6.5.15p6)
7058     QualType destPointee
7059       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7060     QualType destType = S.Context.getPointerType(destPointee);
7061     // Add qualifiers if necessary.
7062     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7063     // Promote to void*.
7064     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7065     return destType;
7066   }
7067   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7068     QualType destPointee
7069       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7070     QualType destType = S.Context.getPointerType(destPointee);
7071     // Add qualifiers if necessary.
7072     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7073     // Promote to void*.
7074     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7075     return destType;
7076   }
7077 
7078   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7079 }
7080 
7081 /// Return false if the first expression is not an integer and the second
7082 /// expression is not a pointer, true otherwise.
7083 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7084                                         Expr* PointerExpr, SourceLocation Loc,
7085                                         bool IsIntFirstExpr) {
7086   if (!PointerExpr->getType()->isPointerType() ||
7087       !Int.get()->getType()->isIntegerType())
7088     return false;
7089 
7090   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7091   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7092 
7093   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7094     << Expr1->getType() << Expr2->getType()
7095     << Expr1->getSourceRange() << Expr2->getSourceRange();
7096   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7097                             CK_IntegralToPointer);
7098   return true;
7099 }
7100 
7101 /// Simple conversion between integer and floating point types.
7102 ///
7103 /// Used when handling the OpenCL conditional operator where the
7104 /// condition is a vector while the other operands are scalar.
7105 ///
7106 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7107 /// types are either integer or floating type. Between the two
7108 /// operands, the type with the higher rank is defined as the "result
7109 /// type". The other operand needs to be promoted to the same type. No
7110 /// other type promotion is allowed. We cannot use
7111 /// UsualArithmeticConversions() for this purpose, since it always
7112 /// promotes promotable types.
7113 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7114                                             ExprResult &RHS,
7115                                             SourceLocation QuestionLoc) {
7116   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7117   if (LHS.isInvalid())
7118     return QualType();
7119   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7120   if (RHS.isInvalid())
7121     return QualType();
7122 
7123   // For conversion purposes, we ignore any qualifiers.
7124   // For example, "const float" and "float" are equivalent.
7125   QualType LHSType =
7126     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7127   QualType RHSType =
7128     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7129 
7130   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7131     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7132       << LHSType << LHS.get()->getSourceRange();
7133     return QualType();
7134   }
7135 
7136   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7137     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7138       << RHSType << RHS.get()->getSourceRange();
7139     return QualType();
7140   }
7141 
7142   // If both types are identical, no conversion is needed.
7143   if (LHSType == RHSType)
7144     return LHSType;
7145 
7146   // Now handle "real" floating types (i.e. float, double, long double).
7147   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7148     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7149                                  /*IsCompAssign = */ false);
7150 
7151   // Finally, we have two differing integer types.
7152   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7153   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7154 }
7155 
7156 /// Convert scalar operands to a vector that matches the
7157 ///        condition in length.
7158 ///
7159 /// Used when handling the OpenCL conditional operator where the
7160 /// condition is a vector while the other operands are scalar.
7161 ///
7162 /// We first compute the "result type" for the scalar operands
7163 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7164 /// into a vector of that type where the length matches the condition
7165 /// vector type. s6.11.6 requires that the element types of the result
7166 /// and the condition must have the same number of bits.
7167 static QualType
7168 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7169                               QualType CondTy, SourceLocation QuestionLoc) {
7170   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7171   if (ResTy.isNull()) return QualType();
7172 
7173   const VectorType *CV = CondTy->getAs<VectorType>();
7174   assert(CV);
7175 
7176   // Determine the vector result type
7177   unsigned NumElements = CV->getNumElements();
7178   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7179 
7180   // Ensure that all types have the same number of bits
7181   if (S.Context.getTypeSize(CV->getElementType())
7182       != S.Context.getTypeSize(ResTy)) {
7183     // Since VectorTy is created internally, it does not pretty print
7184     // with an OpenCL name. Instead, we just print a description.
7185     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7186     SmallString<64> Str;
7187     llvm::raw_svector_ostream OS(Str);
7188     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7189     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7190       << CondTy << OS.str();
7191     return QualType();
7192   }
7193 
7194   // Convert operands to the vector result type
7195   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7196   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7197 
7198   return VectorTy;
7199 }
7200 
7201 /// Return false if this is a valid OpenCL condition vector
7202 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7203                                        SourceLocation QuestionLoc) {
7204   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7205   // integral type.
7206   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7207   assert(CondTy);
7208   QualType EleTy = CondTy->getElementType();
7209   if (EleTy->isIntegerType()) return false;
7210 
7211   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7212     << Cond->getType() << Cond->getSourceRange();
7213   return true;
7214 }
7215 
7216 /// Return false if the vector condition type and the vector
7217 ///        result type are compatible.
7218 ///
7219 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7220 /// number of elements, and their element types have the same number
7221 /// of bits.
7222 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7223                               SourceLocation QuestionLoc) {
7224   const VectorType *CV = CondTy->getAs<VectorType>();
7225   const VectorType *RV = VecResTy->getAs<VectorType>();
7226   assert(CV && RV);
7227 
7228   if (CV->getNumElements() != RV->getNumElements()) {
7229     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7230       << CondTy << VecResTy;
7231     return true;
7232   }
7233 
7234   QualType CVE = CV->getElementType();
7235   QualType RVE = RV->getElementType();
7236 
7237   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7238     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7239       << CondTy << VecResTy;
7240     return true;
7241   }
7242 
7243   return false;
7244 }
7245 
7246 /// Return the resulting type for the conditional operator in
7247 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7248 ///        s6.3.i) when the condition is a vector type.
7249 static QualType
7250 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7251                              ExprResult &LHS, ExprResult &RHS,
7252                              SourceLocation QuestionLoc) {
7253   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7254   if (Cond.isInvalid())
7255     return QualType();
7256   QualType CondTy = Cond.get()->getType();
7257 
7258   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7259     return QualType();
7260 
7261   // If either operand is a vector then find the vector type of the
7262   // result as specified in OpenCL v1.1 s6.3.i.
7263   if (LHS.get()->getType()->isVectorType() ||
7264       RHS.get()->getType()->isVectorType()) {
7265     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7266                                               /*isCompAssign*/false,
7267                                               /*AllowBothBool*/true,
7268                                               /*AllowBoolConversions*/false);
7269     if (VecResTy.isNull()) return QualType();
7270     // The result type must match the condition type as specified in
7271     // OpenCL v1.1 s6.11.6.
7272     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7273       return QualType();
7274     return VecResTy;
7275   }
7276 
7277   // Both operands are scalar.
7278   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7279 }
7280 
7281 /// Return true if the Expr is block type
7282 static bool checkBlockType(Sema &S, const Expr *E) {
7283   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7284     QualType Ty = CE->getCallee()->getType();
7285     if (Ty->isBlockPointerType()) {
7286       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7287       return true;
7288     }
7289   }
7290   return false;
7291 }
7292 
7293 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7294 /// In that case, LHS = cond.
7295 /// C99 6.5.15
7296 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7297                                         ExprResult &RHS, ExprValueKind &VK,
7298                                         ExprObjectKind &OK,
7299                                         SourceLocation QuestionLoc) {
7300 
7301   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7302   if (!LHSResult.isUsable()) return QualType();
7303   LHS = LHSResult;
7304 
7305   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7306   if (!RHSResult.isUsable()) return QualType();
7307   RHS = RHSResult;
7308 
7309   // C++ is sufficiently different to merit its own checker.
7310   if (getLangOpts().CPlusPlus)
7311     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7312 
7313   VK = VK_RValue;
7314   OK = OK_Ordinary;
7315 
7316   // The OpenCL operator with a vector condition is sufficiently
7317   // different to merit its own checker.
7318   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7319     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7320 
7321   // First, check the condition.
7322   Cond = UsualUnaryConversions(Cond.get());
7323   if (Cond.isInvalid())
7324     return QualType();
7325   if (checkCondition(*this, Cond.get(), QuestionLoc))
7326     return QualType();
7327 
7328   // Now check the two expressions.
7329   if (LHS.get()->getType()->isVectorType() ||
7330       RHS.get()->getType()->isVectorType())
7331     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7332                                /*AllowBothBool*/true,
7333                                /*AllowBoolConversions*/false);
7334 
7335   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7336   if (LHS.isInvalid() || RHS.isInvalid())
7337     return QualType();
7338 
7339   QualType LHSTy = LHS.get()->getType();
7340   QualType RHSTy = RHS.get()->getType();
7341 
7342   // Diagnose attempts to convert between __float128 and long double where
7343   // such conversions currently can't be handled.
7344   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7345     Diag(QuestionLoc,
7346          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7347       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7348     return QualType();
7349   }
7350 
7351   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7352   // selection operator (?:).
7353   if (getLangOpts().OpenCL &&
7354       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7355     return QualType();
7356   }
7357 
7358   // If both operands have arithmetic type, do the usual arithmetic conversions
7359   // to find a common type: C99 6.5.15p3,5.
7360   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7361     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7362     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7363 
7364     return ResTy;
7365   }
7366 
7367   // If both operands are the same structure or union type, the result is that
7368   // type.
7369   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7370     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7371       if (LHSRT->getDecl() == RHSRT->getDecl())
7372         // "If both the operands have structure or union type, the result has
7373         // that type."  This implies that CV qualifiers are dropped.
7374         return LHSTy.getUnqualifiedType();
7375     // FIXME: Type of conditional expression must be complete in C mode.
7376   }
7377 
7378   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7379   // The following || allows only one side to be void (a GCC-ism).
7380   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7381     return checkConditionalVoidType(*this, LHS, RHS);
7382   }
7383 
7384   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7385   // the type of the other operand."
7386   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7387   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7388 
7389   // All objective-c pointer type analysis is done here.
7390   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7391                                                         QuestionLoc);
7392   if (LHS.isInvalid() || RHS.isInvalid())
7393     return QualType();
7394   if (!compositeType.isNull())
7395     return compositeType;
7396 
7397 
7398   // Handle block pointer types.
7399   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7400     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7401                                                      QuestionLoc);
7402 
7403   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7404   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7405     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7406                                                        QuestionLoc);
7407 
7408   // GCC compatibility: soften pointer/integer mismatch.  Note that
7409   // null pointers have been filtered out by this point.
7410   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7411       /*IsIntFirstExpr=*/true))
7412     return RHSTy;
7413   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7414       /*IsIntFirstExpr=*/false))
7415     return LHSTy;
7416 
7417   // Emit a better diagnostic if one of the expressions is a null pointer
7418   // constant and the other is not a pointer type. In this case, the user most
7419   // likely forgot to take the address of the other expression.
7420   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7421     return QualType();
7422 
7423   // Otherwise, the operands are not compatible.
7424   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7425     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7426     << RHS.get()->getSourceRange();
7427   return QualType();
7428 }
7429 
7430 /// FindCompositeObjCPointerType - Helper method to find composite type of
7431 /// two objective-c pointer types of the two input expressions.
7432 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7433                                             SourceLocation QuestionLoc) {
7434   QualType LHSTy = LHS.get()->getType();
7435   QualType RHSTy = RHS.get()->getType();
7436 
7437   // Handle things like Class and struct objc_class*.  Here we case the result
7438   // to the pseudo-builtin, because that will be implicitly cast back to the
7439   // redefinition type if an attempt is made to access its fields.
7440   if (LHSTy->isObjCClassType() &&
7441       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7442     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7443     return LHSTy;
7444   }
7445   if (RHSTy->isObjCClassType() &&
7446       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7447     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7448     return RHSTy;
7449   }
7450   // And the same for struct objc_object* / id
7451   if (LHSTy->isObjCIdType() &&
7452       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7453     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7454     return LHSTy;
7455   }
7456   if (RHSTy->isObjCIdType() &&
7457       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7458     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7459     return RHSTy;
7460   }
7461   // And the same for struct objc_selector* / SEL
7462   if (Context.isObjCSelType(LHSTy) &&
7463       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7464     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7465     return LHSTy;
7466   }
7467   if (Context.isObjCSelType(RHSTy) &&
7468       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7469     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7470     return RHSTy;
7471   }
7472   // Check constraints for Objective-C object pointers types.
7473   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7474 
7475     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7476       // Two identical object pointer types are always compatible.
7477       return LHSTy;
7478     }
7479     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7480     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7481     QualType compositeType = LHSTy;
7482 
7483     // If both operands are interfaces and either operand can be
7484     // assigned to the other, use that type as the composite
7485     // type. This allows
7486     //   xxx ? (A*) a : (B*) b
7487     // where B is a subclass of A.
7488     //
7489     // Additionally, as for assignment, if either type is 'id'
7490     // allow silent coercion. Finally, if the types are
7491     // incompatible then make sure to use 'id' as the composite
7492     // type so the result is acceptable for sending messages to.
7493 
7494     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7495     // It could return the composite type.
7496     if (!(compositeType =
7497           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7498       // Nothing more to do.
7499     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7500       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7501     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7502       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7503     } else if ((LHSOPT->isObjCQualifiedIdType() ||
7504                 RHSOPT->isObjCQualifiedIdType()) &&
7505                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7506                                                          true)) {
7507       // Need to handle "id<xx>" explicitly.
7508       // GCC allows qualified id and any Objective-C type to devolve to
7509       // id. Currently localizing to here until clear this should be
7510       // part of ObjCQualifiedIdTypesAreCompatible.
7511       compositeType = Context.getObjCIdType();
7512     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7513       compositeType = Context.getObjCIdType();
7514     } else {
7515       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7516       << LHSTy << RHSTy
7517       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7518       QualType incompatTy = Context.getObjCIdType();
7519       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7520       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7521       return incompatTy;
7522     }
7523     // The object pointer types are compatible.
7524     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7525     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7526     return compositeType;
7527   }
7528   // Check Objective-C object pointer types and 'void *'
7529   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7530     if (getLangOpts().ObjCAutoRefCount) {
7531       // ARC forbids the implicit conversion of object pointers to 'void *',
7532       // so these types are not compatible.
7533       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7534           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7535       LHS = RHS = true;
7536       return QualType();
7537     }
7538     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7539     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7540     QualType destPointee
7541     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7542     QualType destType = Context.getPointerType(destPointee);
7543     // Add qualifiers if necessary.
7544     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7545     // Promote to void*.
7546     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7547     return destType;
7548   }
7549   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7550     if (getLangOpts().ObjCAutoRefCount) {
7551       // ARC forbids the implicit conversion of object pointers to 'void *',
7552       // so these types are not compatible.
7553       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7554           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7555       LHS = RHS = true;
7556       return QualType();
7557     }
7558     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7559     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7560     QualType destPointee
7561     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7562     QualType destType = Context.getPointerType(destPointee);
7563     // Add qualifiers if necessary.
7564     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7565     // Promote to void*.
7566     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7567     return destType;
7568   }
7569   return QualType();
7570 }
7571 
7572 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7573 /// ParenRange in parentheses.
7574 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7575                                const PartialDiagnostic &Note,
7576                                SourceRange ParenRange) {
7577   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7578   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7579       EndLoc.isValid()) {
7580     Self.Diag(Loc, Note)
7581       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7582       << FixItHint::CreateInsertion(EndLoc, ")");
7583   } else {
7584     // We can't display the parentheses, so just show the bare note.
7585     Self.Diag(Loc, Note) << ParenRange;
7586   }
7587 }
7588 
7589 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7590   return BinaryOperator::isAdditiveOp(Opc) ||
7591          BinaryOperator::isMultiplicativeOp(Opc) ||
7592          BinaryOperator::isShiftOp(Opc);
7593 }
7594 
7595 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7596 /// expression, either using a built-in or overloaded operator,
7597 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7598 /// expression.
7599 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7600                                    Expr **RHSExprs) {
7601   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7602   E = E->IgnoreImpCasts();
7603   E = E->IgnoreConversionOperator();
7604   E = E->IgnoreImpCasts();
7605   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7606     E = MTE->GetTemporaryExpr();
7607     E = E->IgnoreImpCasts();
7608   }
7609 
7610   // Built-in binary operator.
7611   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7612     if (IsArithmeticOp(OP->getOpcode())) {
7613       *Opcode = OP->getOpcode();
7614       *RHSExprs = OP->getRHS();
7615       return true;
7616     }
7617   }
7618 
7619   // Overloaded operator.
7620   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7621     if (Call->getNumArgs() != 2)
7622       return false;
7623 
7624     // Make sure this is really a binary operator that is safe to pass into
7625     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7626     OverloadedOperatorKind OO = Call->getOperator();
7627     if (OO < OO_Plus || OO > OO_Arrow ||
7628         OO == OO_PlusPlus || OO == OO_MinusMinus)
7629       return false;
7630 
7631     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7632     if (IsArithmeticOp(OpKind)) {
7633       *Opcode = OpKind;
7634       *RHSExprs = Call->getArg(1);
7635       return true;
7636     }
7637   }
7638 
7639   return false;
7640 }
7641 
7642 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7643 /// or is a logical expression such as (x==y) which has int type, but is
7644 /// commonly interpreted as boolean.
7645 static bool ExprLooksBoolean(Expr *E) {
7646   E = E->IgnoreParenImpCasts();
7647 
7648   if (E->getType()->isBooleanType())
7649     return true;
7650   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7651     return OP->isComparisonOp() || OP->isLogicalOp();
7652   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7653     return OP->getOpcode() == UO_LNot;
7654   if (E->getType()->isPointerType())
7655     return true;
7656   // FIXME: What about overloaded operator calls returning "unspecified boolean
7657   // type"s (commonly pointer-to-members)?
7658 
7659   return false;
7660 }
7661 
7662 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7663 /// and binary operator are mixed in a way that suggests the programmer assumed
7664 /// the conditional operator has higher precedence, for example:
7665 /// "int x = a + someBinaryCondition ? 1 : 2".
7666 static void DiagnoseConditionalPrecedence(Sema &Self,
7667                                           SourceLocation OpLoc,
7668                                           Expr *Condition,
7669                                           Expr *LHSExpr,
7670                                           Expr *RHSExpr) {
7671   BinaryOperatorKind CondOpcode;
7672   Expr *CondRHS;
7673 
7674   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7675     return;
7676   if (!ExprLooksBoolean(CondRHS))
7677     return;
7678 
7679   // The condition is an arithmetic binary expression, with a right-
7680   // hand side that looks boolean, so warn.
7681 
7682   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7683       << Condition->getSourceRange()
7684       << BinaryOperator::getOpcodeStr(CondOpcode);
7685 
7686   SuggestParentheses(
7687       Self, OpLoc,
7688       Self.PDiag(diag::note_precedence_silence)
7689           << BinaryOperator::getOpcodeStr(CondOpcode),
7690       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7691 
7692   SuggestParentheses(Self, OpLoc,
7693                      Self.PDiag(diag::note_precedence_conditional_first),
7694                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7695 }
7696 
7697 /// Compute the nullability of a conditional expression.
7698 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7699                                               QualType LHSTy, QualType RHSTy,
7700                                               ASTContext &Ctx) {
7701   if (!ResTy->isAnyPointerType())
7702     return ResTy;
7703 
7704   auto GetNullability = [&Ctx](QualType Ty) {
7705     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7706     if (Kind)
7707       return *Kind;
7708     return NullabilityKind::Unspecified;
7709   };
7710 
7711   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7712   NullabilityKind MergedKind;
7713 
7714   // Compute nullability of a binary conditional expression.
7715   if (IsBin) {
7716     if (LHSKind == NullabilityKind::NonNull)
7717       MergedKind = NullabilityKind::NonNull;
7718     else
7719       MergedKind = RHSKind;
7720   // Compute nullability of a normal conditional expression.
7721   } else {
7722     if (LHSKind == NullabilityKind::Nullable ||
7723         RHSKind == NullabilityKind::Nullable)
7724       MergedKind = NullabilityKind::Nullable;
7725     else if (LHSKind == NullabilityKind::NonNull)
7726       MergedKind = RHSKind;
7727     else if (RHSKind == NullabilityKind::NonNull)
7728       MergedKind = LHSKind;
7729     else
7730       MergedKind = NullabilityKind::Unspecified;
7731   }
7732 
7733   // Return if ResTy already has the correct nullability.
7734   if (GetNullability(ResTy) == MergedKind)
7735     return ResTy;
7736 
7737   // Strip all nullability from ResTy.
7738   while (ResTy->getNullability(Ctx))
7739     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7740 
7741   // Create a new AttributedType with the new nullability kind.
7742   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7743   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7744 }
7745 
7746 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7747 /// in the case of a the GNU conditional expr extension.
7748 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7749                                     SourceLocation ColonLoc,
7750                                     Expr *CondExpr, Expr *LHSExpr,
7751                                     Expr *RHSExpr) {
7752   if (!getLangOpts().CPlusPlus) {
7753     // C cannot handle TypoExpr nodes in the condition because it
7754     // doesn't handle dependent types properly, so make sure any TypoExprs have
7755     // been dealt with before checking the operands.
7756     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7757     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7758     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7759 
7760     if (!CondResult.isUsable())
7761       return ExprError();
7762 
7763     if (LHSExpr) {
7764       if (!LHSResult.isUsable())
7765         return ExprError();
7766     }
7767 
7768     if (!RHSResult.isUsable())
7769       return ExprError();
7770 
7771     CondExpr = CondResult.get();
7772     LHSExpr = LHSResult.get();
7773     RHSExpr = RHSResult.get();
7774   }
7775 
7776   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7777   // was the condition.
7778   OpaqueValueExpr *opaqueValue = nullptr;
7779   Expr *commonExpr = nullptr;
7780   if (!LHSExpr) {
7781     commonExpr = CondExpr;
7782     // Lower out placeholder types first.  This is important so that we don't
7783     // try to capture a placeholder. This happens in few cases in C++; such
7784     // as Objective-C++'s dictionary subscripting syntax.
7785     if (commonExpr->hasPlaceholderType()) {
7786       ExprResult result = CheckPlaceholderExpr(commonExpr);
7787       if (!result.isUsable()) return ExprError();
7788       commonExpr = result.get();
7789     }
7790     // We usually want to apply unary conversions *before* saving, except
7791     // in the special case of a C++ l-value conditional.
7792     if (!(getLangOpts().CPlusPlus
7793           && !commonExpr->isTypeDependent()
7794           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7795           && commonExpr->isGLValue()
7796           && commonExpr->isOrdinaryOrBitFieldObject()
7797           && RHSExpr->isOrdinaryOrBitFieldObject()
7798           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7799       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7800       if (commonRes.isInvalid())
7801         return ExprError();
7802       commonExpr = commonRes.get();
7803     }
7804 
7805     // If the common expression is a class or array prvalue, materialize it
7806     // so that we can safely refer to it multiple times.
7807     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7808                                    commonExpr->getType()->isArrayType())) {
7809       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7810       if (MatExpr.isInvalid())
7811         return ExprError();
7812       commonExpr = MatExpr.get();
7813     }
7814 
7815     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7816                                                 commonExpr->getType(),
7817                                                 commonExpr->getValueKind(),
7818                                                 commonExpr->getObjectKind(),
7819                                                 commonExpr);
7820     LHSExpr = CondExpr = opaqueValue;
7821   }
7822 
7823   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7824   ExprValueKind VK = VK_RValue;
7825   ExprObjectKind OK = OK_Ordinary;
7826   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7827   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7828                                              VK, OK, QuestionLoc);
7829   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7830       RHS.isInvalid())
7831     return ExprError();
7832 
7833   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7834                                 RHS.get());
7835 
7836   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7837 
7838   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7839                                          Context);
7840 
7841   if (!commonExpr)
7842     return new (Context)
7843         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7844                             RHS.get(), result, VK, OK);
7845 
7846   return new (Context) BinaryConditionalOperator(
7847       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7848       ColonLoc, result, VK, OK);
7849 }
7850 
7851 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7852 // being closely modeled after the C99 spec:-). The odd characteristic of this
7853 // routine is it effectively iqnores the qualifiers on the top level pointee.
7854 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7855 // FIXME: add a couple examples in this comment.
7856 static Sema::AssignConvertType
7857 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7858   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7859   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7860 
7861   // get the "pointed to" type (ignoring qualifiers at the top level)
7862   const Type *lhptee, *rhptee;
7863   Qualifiers lhq, rhq;
7864   std::tie(lhptee, lhq) =
7865       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7866   std::tie(rhptee, rhq) =
7867       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7868 
7869   Sema::AssignConvertType ConvTy = Sema::Compatible;
7870 
7871   // C99 6.5.16.1p1: This following citation is common to constraints
7872   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7873   // qualifiers of the type *pointed to* by the right;
7874 
7875   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7876   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7877       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7878     // Ignore lifetime for further calculation.
7879     lhq.removeObjCLifetime();
7880     rhq.removeObjCLifetime();
7881   }
7882 
7883   if (!lhq.compatiblyIncludes(rhq)) {
7884     // Treat address-space mismatches as fatal.
7885     if (!lhq.isAddressSpaceSupersetOf(rhq))
7886       return Sema::IncompatiblePointerDiscardsQualifiers;
7887 
7888     // It's okay to add or remove GC or lifetime qualifiers when converting to
7889     // and from void*.
7890     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7891                         .compatiblyIncludes(
7892                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7893              && (lhptee->isVoidType() || rhptee->isVoidType()))
7894       ; // keep old
7895 
7896     // Treat lifetime mismatches as fatal.
7897     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7898       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7899 
7900     // For GCC/MS compatibility, other qualifier mismatches are treated
7901     // as still compatible in C.
7902     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7903   }
7904 
7905   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7906   // incomplete type and the other is a pointer to a qualified or unqualified
7907   // version of void...
7908   if (lhptee->isVoidType()) {
7909     if (rhptee->isIncompleteOrObjectType())
7910       return ConvTy;
7911 
7912     // As an extension, we allow cast to/from void* to function pointer.
7913     assert(rhptee->isFunctionType());
7914     return Sema::FunctionVoidPointer;
7915   }
7916 
7917   if (rhptee->isVoidType()) {
7918     if (lhptee->isIncompleteOrObjectType())
7919       return ConvTy;
7920 
7921     // As an extension, we allow cast to/from void* to function pointer.
7922     assert(lhptee->isFunctionType());
7923     return Sema::FunctionVoidPointer;
7924   }
7925 
7926   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7927   // unqualified versions of compatible types, ...
7928   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7929   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7930     // Check if the pointee types are compatible ignoring the sign.
7931     // We explicitly check for char so that we catch "char" vs
7932     // "unsigned char" on systems where "char" is unsigned.
7933     if (lhptee->isCharType())
7934       ltrans = S.Context.UnsignedCharTy;
7935     else if (lhptee->hasSignedIntegerRepresentation())
7936       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7937 
7938     if (rhptee->isCharType())
7939       rtrans = S.Context.UnsignedCharTy;
7940     else if (rhptee->hasSignedIntegerRepresentation())
7941       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7942 
7943     if (ltrans == rtrans) {
7944       // Types are compatible ignoring the sign. Qualifier incompatibility
7945       // takes priority over sign incompatibility because the sign
7946       // warning can be disabled.
7947       if (ConvTy != Sema::Compatible)
7948         return ConvTy;
7949 
7950       return Sema::IncompatiblePointerSign;
7951     }
7952 
7953     // If we are a multi-level pointer, it's possible that our issue is simply
7954     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7955     // the eventual target type is the same and the pointers have the same
7956     // level of indirection, this must be the issue.
7957     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7958       do {
7959         std::tie(lhptee, lhq) =
7960           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7961         std::tie(rhptee, rhq) =
7962           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7963 
7964         // Inconsistent address spaces at this point is invalid, even if the
7965         // address spaces would be compatible.
7966         // FIXME: This doesn't catch address space mismatches for pointers of
7967         // different nesting levels, like:
7968         //   __local int *** a;
7969         //   int ** b = a;
7970         // It's not clear how to actually determine when such pointers are
7971         // invalidly incompatible.
7972         if (lhq.getAddressSpace() != rhq.getAddressSpace())
7973           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
7974 
7975       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7976 
7977       if (lhptee == rhptee)
7978         return Sema::IncompatibleNestedPointerQualifiers;
7979     }
7980 
7981     // General pointer incompatibility takes priority over qualifiers.
7982     return Sema::IncompatiblePointer;
7983   }
7984   if (!S.getLangOpts().CPlusPlus &&
7985       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7986     return Sema::IncompatiblePointer;
7987   return ConvTy;
7988 }
7989 
7990 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7991 /// block pointer types are compatible or whether a block and normal pointer
7992 /// are compatible. It is more restrict than comparing two function pointer
7993 // types.
7994 static Sema::AssignConvertType
7995 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7996                                     QualType RHSType) {
7997   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7998   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7999 
8000   QualType lhptee, rhptee;
8001 
8002   // get the "pointed to" type (ignoring qualifiers at the top level)
8003   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8004   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8005 
8006   // In C++, the types have to match exactly.
8007   if (S.getLangOpts().CPlusPlus)
8008     return Sema::IncompatibleBlockPointer;
8009 
8010   Sema::AssignConvertType ConvTy = Sema::Compatible;
8011 
8012   // For blocks we enforce that qualifiers are identical.
8013   Qualifiers LQuals = lhptee.getLocalQualifiers();
8014   Qualifiers RQuals = rhptee.getLocalQualifiers();
8015   if (S.getLangOpts().OpenCL) {
8016     LQuals.removeAddressSpace();
8017     RQuals.removeAddressSpace();
8018   }
8019   if (LQuals != RQuals)
8020     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8021 
8022   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8023   // assignment.
8024   // The current behavior is similar to C++ lambdas. A block might be
8025   // assigned to a variable iff its return type and parameters are compatible
8026   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8027   // an assignment. Presumably it should behave in way that a function pointer
8028   // assignment does in C, so for each parameter and return type:
8029   //  * CVR and address space of LHS should be a superset of CVR and address
8030   //  space of RHS.
8031   //  * unqualified types should be compatible.
8032   if (S.getLangOpts().OpenCL) {
8033     if (!S.Context.typesAreBlockPointerCompatible(
8034             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8035             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8036       return Sema::IncompatibleBlockPointer;
8037   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8038     return Sema::IncompatibleBlockPointer;
8039 
8040   return ConvTy;
8041 }
8042 
8043 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8044 /// for assignment compatibility.
8045 static Sema::AssignConvertType
8046 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8047                                    QualType RHSType) {
8048   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8049   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8050 
8051   if (LHSType->isObjCBuiltinType()) {
8052     // Class is not compatible with ObjC object pointers.
8053     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8054         !RHSType->isObjCQualifiedClassType())
8055       return Sema::IncompatiblePointer;
8056     return Sema::Compatible;
8057   }
8058   if (RHSType->isObjCBuiltinType()) {
8059     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8060         !LHSType->isObjCQualifiedClassType())
8061       return Sema::IncompatiblePointer;
8062     return Sema::Compatible;
8063   }
8064   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8065   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8066 
8067   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8068       // make an exception for id<P>
8069       !LHSType->isObjCQualifiedIdType())
8070     return Sema::CompatiblePointerDiscardsQualifiers;
8071 
8072   if (S.Context.typesAreCompatible(LHSType, RHSType))
8073     return Sema::Compatible;
8074   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8075     return Sema::IncompatibleObjCQualifiedId;
8076   return Sema::IncompatiblePointer;
8077 }
8078 
8079 Sema::AssignConvertType
8080 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8081                                  QualType LHSType, QualType RHSType) {
8082   // Fake up an opaque expression.  We don't actually care about what
8083   // cast operations are required, so if CheckAssignmentConstraints
8084   // adds casts to this they'll be wasted, but fortunately that doesn't
8085   // usually happen on valid code.
8086   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8087   ExprResult RHSPtr = &RHSExpr;
8088   CastKind K;
8089 
8090   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8091 }
8092 
8093 /// This helper function returns true if QT is a vector type that has element
8094 /// type ElementType.
8095 static bool isVector(QualType QT, QualType ElementType) {
8096   if (const VectorType *VT = QT->getAs<VectorType>())
8097     return VT->getElementType() == ElementType;
8098   return false;
8099 }
8100 
8101 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8102 /// has code to accommodate several GCC extensions when type checking
8103 /// pointers. Here are some objectionable examples that GCC considers warnings:
8104 ///
8105 ///  int a, *pint;
8106 ///  short *pshort;
8107 ///  struct foo *pfoo;
8108 ///
8109 ///  pint = pshort; // warning: assignment from incompatible pointer type
8110 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8111 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8112 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8113 ///
8114 /// As a result, the code for dealing with pointers is more complex than the
8115 /// C99 spec dictates.
8116 ///
8117 /// Sets 'Kind' for any result kind except Incompatible.
8118 Sema::AssignConvertType
8119 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8120                                  CastKind &Kind, bool ConvertRHS) {
8121   QualType RHSType = RHS.get()->getType();
8122   QualType OrigLHSType = LHSType;
8123 
8124   // Get canonical types.  We're not formatting these types, just comparing
8125   // them.
8126   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8127   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8128 
8129   // Common case: no conversion required.
8130   if (LHSType == RHSType) {
8131     Kind = CK_NoOp;
8132     return Compatible;
8133   }
8134 
8135   // If we have an atomic type, try a non-atomic assignment, then just add an
8136   // atomic qualification step.
8137   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8138     Sema::AssignConvertType result =
8139       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8140     if (result != Compatible)
8141       return result;
8142     if (Kind != CK_NoOp && ConvertRHS)
8143       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8144     Kind = CK_NonAtomicToAtomic;
8145     return Compatible;
8146   }
8147 
8148   // If the left-hand side is a reference type, then we are in a
8149   // (rare!) case where we've allowed the use of references in C,
8150   // e.g., as a parameter type in a built-in function. In this case,
8151   // just make sure that the type referenced is compatible with the
8152   // right-hand side type. The caller is responsible for adjusting
8153   // LHSType so that the resulting expression does not have reference
8154   // type.
8155   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8156     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8157       Kind = CK_LValueBitCast;
8158       return Compatible;
8159     }
8160     return Incompatible;
8161   }
8162 
8163   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8164   // to the same ExtVector type.
8165   if (LHSType->isExtVectorType()) {
8166     if (RHSType->isExtVectorType())
8167       return Incompatible;
8168     if (RHSType->isArithmeticType()) {
8169       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8170       if (ConvertRHS)
8171         RHS = prepareVectorSplat(LHSType, RHS.get());
8172       Kind = CK_VectorSplat;
8173       return Compatible;
8174     }
8175   }
8176 
8177   // Conversions to or from vector type.
8178   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8179     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8180       // Allow assignments of an AltiVec vector type to an equivalent GCC
8181       // vector type and vice versa
8182       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8183         Kind = CK_BitCast;
8184         return Compatible;
8185       }
8186 
8187       // If we are allowing lax vector conversions, and LHS and RHS are both
8188       // vectors, the total size only needs to be the same. This is a bitcast;
8189       // no bits are changed but the result type is different.
8190       if (isLaxVectorConversion(RHSType, LHSType)) {
8191         Kind = CK_BitCast;
8192         return IncompatibleVectors;
8193       }
8194     }
8195 
8196     // When the RHS comes from another lax conversion (e.g. binops between
8197     // scalars and vectors) the result is canonicalized as a vector. When the
8198     // LHS is also a vector, the lax is allowed by the condition above. Handle
8199     // the case where LHS is a scalar.
8200     if (LHSType->isScalarType()) {
8201       const VectorType *VecType = RHSType->getAs<VectorType>();
8202       if (VecType && VecType->getNumElements() == 1 &&
8203           isLaxVectorConversion(RHSType, LHSType)) {
8204         ExprResult *VecExpr = &RHS;
8205         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8206         Kind = CK_BitCast;
8207         return Compatible;
8208       }
8209     }
8210 
8211     return Incompatible;
8212   }
8213 
8214   // Diagnose attempts to convert between __float128 and long double where
8215   // such conversions currently can't be handled.
8216   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8217     return Incompatible;
8218 
8219   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8220   // discards the imaginary part.
8221   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8222       !LHSType->getAs<ComplexType>())
8223     return Incompatible;
8224 
8225   // Arithmetic conversions.
8226   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8227       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8228     if (ConvertRHS)
8229       Kind = PrepareScalarCast(RHS, LHSType);
8230     return Compatible;
8231   }
8232 
8233   // Conversions to normal pointers.
8234   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8235     // U* -> T*
8236     if (isa<PointerType>(RHSType)) {
8237       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8238       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8239       if (AddrSpaceL != AddrSpaceR)
8240         Kind = CK_AddressSpaceConversion;
8241       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8242         Kind = CK_NoOp;
8243       else
8244         Kind = CK_BitCast;
8245       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8246     }
8247 
8248     // int -> T*
8249     if (RHSType->isIntegerType()) {
8250       Kind = CK_IntegralToPointer; // FIXME: null?
8251       return IntToPointer;
8252     }
8253 
8254     // C pointers are not compatible with ObjC object pointers,
8255     // with two exceptions:
8256     if (isa<ObjCObjectPointerType>(RHSType)) {
8257       //  - conversions to void*
8258       if (LHSPointer->getPointeeType()->isVoidType()) {
8259         Kind = CK_BitCast;
8260         return Compatible;
8261       }
8262 
8263       //  - conversions from 'Class' to the redefinition type
8264       if (RHSType->isObjCClassType() &&
8265           Context.hasSameType(LHSType,
8266                               Context.getObjCClassRedefinitionType())) {
8267         Kind = CK_BitCast;
8268         return Compatible;
8269       }
8270 
8271       Kind = CK_BitCast;
8272       return IncompatiblePointer;
8273     }
8274 
8275     // U^ -> void*
8276     if (RHSType->getAs<BlockPointerType>()) {
8277       if (LHSPointer->getPointeeType()->isVoidType()) {
8278         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8279         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8280                                 ->getPointeeType()
8281                                 .getAddressSpace();
8282         Kind =
8283             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8284         return Compatible;
8285       }
8286     }
8287 
8288     return Incompatible;
8289   }
8290 
8291   // Conversions to block pointers.
8292   if (isa<BlockPointerType>(LHSType)) {
8293     // U^ -> T^
8294     if (RHSType->isBlockPointerType()) {
8295       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8296                               ->getPointeeType()
8297                               .getAddressSpace();
8298       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8299                               ->getPointeeType()
8300                               .getAddressSpace();
8301       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8302       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8303     }
8304 
8305     // int or null -> T^
8306     if (RHSType->isIntegerType()) {
8307       Kind = CK_IntegralToPointer; // FIXME: null
8308       return IntToBlockPointer;
8309     }
8310 
8311     // id -> T^
8312     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8313       Kind = CK_AnyPointerToBlockPointerCast;
8314       return Compatible;
8315     }
8316 
8317     // void* -> T^
8318     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8319       if (RHSPT->getPointeeType()->isVoidType()) {
8320         Kind = CK_AnyPointerToBlockPointerCast;
8321         return Compatible;
8322       }
8323 
8324     return Incompatible;
8325   }
8326 
8327   // Conversions to Objective-C pointers.
8328   if (isa<ObjCObjectPointerType>(LHSType)) {
8329     // A* -> B*
8330     if (RHSType->isObjCObjectPointerType()) {
8331       Kind = CK_BitCast;
8332       Sema::AssignConvertType result =
8333         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8334       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8335           result == Compatible &&
8336           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8337         result = IncompatibleObjCWeakRef;
8338       return result;
8339     }
8340 
8341     // int or null -> A*
8342     if (RHSType->isIntegerType()) {
8343       Kind = CK_IntegralToPointer; // FIXME: null
8344       return IntToPointer;
8345     }
8346 
8347     // In general, C pointers are not compatible with ObjC object pointers,
8348     // with two exceptions:
8349     if (isa<PointerType>(RHSType)) {
8350       Kind = CK_CPointerToObjCPointerCast;
8351 
8352       //  - conversions from 'void*'
8353       if (RHSType->isVoidPointerType()) {
8354         return Compatible;
8355       }
8356 
8357       //  - conversions to 'Class' from its redefinition type
8358       if (LHSType->isObjCClassType() &&
8359           Context.hasSameType(RHSType,
8360                               Context.getObjCClassRedefinitionType())) {
8361         return Compatible;
8362       }
8363 
8364       return IncompatiblePointer;
8365     }
8366 
8367     // Only under strict condition T^ is compatible with an Objective-C pointer.
8368     if (RHSType->isBlockPointerType() &&
8369         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8370       if (ConvertRHS)
8371         maybeExtendBlockObject(RHS);
8372       Kind = CK_BlockPointerToObjCPointerCast;
8373       return Compatible;
8374     }
8375 
8376     return Incompatible;
8377   }
8378 
8379   // Conversions from pointers that are not covered by the above.
8380   if (isa<PointerType>(RHSType)) {
8381     // T* -> _Bool
8382     if (LHSType == Context.BoolTy) {
8383       Kind = CK_PointerToBoolean;
8384       return Compatible;
8385     }
8386 
8387     // T* -> int
8388     if (LHSType->isIntegerType()) {
8389       Kind = CK_PointerToIntegral;
8390       return PointerToInt;
8391     }
8392 
8393     return Incompatible;
8394   }
8395 
8396   // Conversions from Objective-C pointers that are not covered by the above.
8397   if (isa<ObjCObjectPointerType>(RHSType)) {
8398     // T* -> _Bool
8399     if (LHSType == Context.BoolTy) {
8400       Kind = CK_PointerToBoolean;
8401       return Compatible;
8402     }
8403 
8404     // T* -> int
8405     if (LHSType->isIntegerType()) {
8406       Kind = CK_PointerToIntegral;
8407       return PointerToInt;
8408     }
8409 
8410     return Incompatible;
8411   }
8412 
8413   // struct A -> struct B
8414   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8415     if (Context.typesAreCompatible(LHSType, RHSType)) {
8416       Kind = CK_NoOp;
8417       return Compatible;
8418     }
8419   }
8420 
8421   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8422     Kind = CK_IntToOCLSampler;
8423     return Compatible;
8424   }
8425 
8426   return Incompatible;
8427 }
8428 
8429 /// Constructs a transparent union from an expression that is
8430 /// used to initialize the transparent union.
8431 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8432                                       ExprResult &EResult, QualType UnionType,
8433                                       FieldDecl *Field) {
8434   // Build an initializer list that designates the appropriate member
8435   // of the transparent union.
8436   Expr *E = EResult.get();
8437   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8438                                                    E, SourceLocation());
8439   Initializer->setType(UnionType);
8440   Initializer->setInitializedFieldInUnion(Field);
8441 
8442   // Build a compound literal constructing a value of the transparent
8443   // union type from this initializer list.
8444   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8445   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8446                                         VK_RValue, Initializer, false);
8447 }
8448 
8449 Sema::AssignConvertType
8450 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8451                                                ExprResult &RHS) {
8452   QualType RHSType = RHS.get()->getType();
8453 
8454   // If the ArgType is a Union type, we want to handle a potential
8455   // transparent_union GCC extension.
8456   const RecordType *UT = ArgType->getAsUnionType();
8457   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8458     return Incompatible;
8459 
8460   // The field to initialize within the transparent union.
8461   RecordDecl *UD = UT->getDecl();
8462   FieldDecl *InitField = nullptr;
8463   // It's compatible if the expression matches any of the fields.
8464   for (auto *it : UD->fields()) {
8465     if (it->getType()->isPointerType()) {
8466       // If the transparent union contains a pointer type, we allow:
8467       // 1) void pointer
8468       // 2) null pointer constant
8469       if (RHSType->isPointerType())
8470         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8471           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8472           InitField = it;
8473           break;
8474         }
8475 
8476       if (RHS.get()->isNullPointerConstant(Context,
8477                                            Expr::NPC_ValueDependentIsNull)) {
8478         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8479                                 CK_NullToPointer);
8480         InitField = it;
8481         break;
8482       }
8483     }
8484 
8485     CastKind Kind;
8486     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8487           == Compatible) {
8488       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8489       InitField = it;
8490       break;
8491     }
8492   }
8493 
8494   if (!InitField)
8495     return Incompatible;
8496 
8497   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8498   return Compatible;
8499 }
8500 
8501 Sema::AssignConvertType
8502 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8503                                        bool Diagnose,
8504                                        bool DiagnoseCFAudited,
8505                                        bool ConvertRHS) {
8506   // We need to be able to tell the caller whether we diagnosed a problem, if
8507   // they ask us to issue diagnostics.
8508   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8509 
8510   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8511   // we can't avoid *all* modifications at the moment, so we need some somewhere
8512   // to put the updated value.
8513   ExprResult LocalRHS = CallerRHS;
8514   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8515 
8516   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8517     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8518       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8519           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8520         Diag(RHS.get()->getExprLoc(),
8521              diag::warn_noderef_to_dereferenceable_pointer)
8522             << RHS.get()->getSourceRange();
8523       }
8524     }
8525   }
8526 
8527   if (getLangOpts().CPlusPlus) {
8528     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8529       // C++ 5.17p3: If the left operand is not of class type, the
8530       // expression is implicitly converted (C++ 4) to the
8531       // cv-unqualified type of the left operand.
8532       QualType RHSType = RHS.get()->getType();
8533       if (Diagnose) {
8534         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8535                                         AA_Assigning);
8536       } else {
8537         ImplicitConversionSequence ICS =
8538             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8539                                   /*SuppressUserConversions=*/false,
8540                                   /*AllowExplicit=*/false,
8541                                   /*InOverloadResolution=*/false,
8542                                   /*CStyle=*/false,
8543                                   /*AllowObjCWritebackConversion=*/false);
8544         if (ICS.isFailure())
8545           return Incompatible;
8546         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8547                                         ICS, AA_Assigning);
8548       }
8549       if (RHS.isInvalid())
8550         return Incompatible;
8551       Sema::AssignConvertType result = Compatible;
8552       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8553           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8554         result = IncompatibleObjCWeakRef;
8555       return result;
8556     }
8557 
8558     // FIXME: Currently, we fall through and treat C++ classes like C
8559     // structures.
8560     // FIXME: We also fall through for atomics; not sure what should
8561     // happen there, though.
8562   } else if (RHS.get()->getType() == Context.OverloadTy) {
8563     // As a set of extensions to C, we support overloading on functions. These
8564     // functions need to be resolved here.
8565     DeclAccessPair DAP;
8566     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8567             RHS.get(), LHSType, /*Complain=*/false, DAP))
8568       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8569     else
8570       return Incompatible;
8571   }
8572 
8573   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8574   // a null pointer constant.
8575   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8576        LHSType->isBlockPointerType()) &&
8577       RHS.get()->isNullPointerConstant(Context,
8578                                        Expr::NPC_ValueDependentIsNull)) {
8579     if (Diagnose || ConvertRHS) {
8580       CastKind Kind;
8581       CXXCastPath Path;
8582       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8583                              /*IgnoreBaseAccess=*/false, Diagnose);
8584       if (ConvertRHS)
8585         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8586     }
8587     return Compatible;
8588   }
8589 
8590   // OpenCL queue_t type assignment.
8591   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8592                                  Context, Expr::NPC_ValueDependentIsNull)) {
8593     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8594     return Compatible;
8595   }
8596 
8597   // This check seems unnatural, however it is necessary to ensure the proper
8598   // conversion of functions/arrays. If the conversion were done for all
8599   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8600   // expressions that suppress this implicit conversion (&, sizeof).
8601   //
8602   // Suppress this for references: C++ 8.5.3p5.
8603   if (!LHSType->isReferenceType()) {
8604     // FIXME: We potentially allocate here even if ConvertRHS is false.
8605     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8606     if (RHS.isInvalid())
8607       return Incompatible;
8608   }
8609   CastKind Kind;
8610   Sema::AssignConvertType result =
8611     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8612 
8613   // C99 6.5.16.1p2: The value of the right operand is converted to the
8614   // type of the assignment expression.
8615   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8616   // so that we can use references in built-in functions even in C.
8617   // The getNonReferenceType() call makes sure that the resulting expression
8618   // does not have reference type.
8619   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8620     QualType Ty = LHSType.getNonLValueExprType(Context);
8621     Expr *E = RHS.get();
8622 
8623     // Check for various Objective-C errors. If we are not reporting
8624     // diagnostics and just checking for errors, e.g., during overload
8625     // resolution, return Incompatible to indicate the failure.
8626     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8627         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8628                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8629       if (!Diagnose)
8630         return Incompatible;
8631     }
8632     if (getLangOpts().ObjC &&
8633         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8634                                            E->getType(), E, Diagnose) ||
8635          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8636       if (!Diagnose)
8637         return Incompatible;
8638       // Replace the expression with a corrected version and continue so we
8639       // can find further errors.
8640       RHS = E;
8641       return Compatible;
8642     }
8643 
8644     if (ConvertRHS)
8645       RHS = ImpCastExprToType(E, Ty, Kind);
8646   }
8647 
8648   return result;
8649 }
8650 
8651 namespace {
8652 /// The original operand to an operator, prior to the application of the usual
8653 /// arithmetic conversions and converting the arguments of a builtin operator
8654 /// candidate.
8655 struct OriginalOperand {
8656   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8657     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8658       Op = MTE->GetTemporaryExpr();
8659     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8660       Op = BTE->getSubExpr();
8661     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8662       Orig = ICE->getSubExprAsWritten();
8663       Conversion = ICE->getConversionFunction();
8664     }
8665   }
8666 
8667   QualType getType() const { return Orig->getType(); }
8668 
8669   Expr *Orig;
8670   NamedDecl *Conversion;
8671 };
8672 }
8673 
8674 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8675                                ExprResult &RHS) {
8676   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8677 
8678   Diag(Loc, diag::err_typecheck_invalid_operands)
8679     << OrigLHS.getType() << OrigRHS.getType()
8680     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8681 
8682   // If a user-defined conversion was applied to either of the operands prior
8683   // to applying the built-in operator rules, tell the user about it.
8684   if (OrigLHS.Conversion) {
8685     Diag(OrigLHS.Conversion->getLocation(),
8686          diag::note_typecheck_invalid_operands_converted)
8687       << 0 << LHS.get()->getType();
8688   }
8689   if (OrigRHS.Conversion) {
8690     Diag(OrigRHS.Conversion->getLocation(),
8691          diag::note_typecheck_invalid_operands_converted)
8692       << 1 << RHS.get()->getType();
8693   }
8694 
8695   return QualType();
8696 }
8697 
8698 // Diagnose cases where a scalar was implicitly converted to a vector and
8699 // diagnose the underlying types. Otherwise, diagnose the error
8700 // as invalid vector logical operands for non-C++ cases.
8701 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8702                                             ExprResult &RHS) {
8703   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8704   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8705 
8706   bool LHSNatVec = LHSType->isVectorType();
8707   bool RHSNatVec = RHSType->isVectorType();
8708 
8709   if (!(LHSNatVec && RHSNatVec)) {
8710     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8711     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8712     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8713         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8714         << Vector->getSourceRange();
8715     return QualType();
8716   }
8717 
8718   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8719       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8720       << RHS.get()->getSourceRange();
8721 
8722   return QualType();
8723 }
8724 
8725 /// Try to convert a value of non-vector type to a vector type by converting
8726 /// the type to the element type of the vector and then performing a splat.
8727 /// If the language is OpenCL, we only use conversions that promote scalar
8728 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8729 /// for float->int.
8730 ///
8731 /// OpenCL V2.0 6.2.6.p2:
8732 /// An error shall occur if any scalar operand type has greater rank
8733 /// than the type of the vector element.
8734 ///
8735 /// \param scalar - if non-null, actually perform the conversions
8736 /// \return true if the operation fails (but without diagnosing the failure)
8737 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8738                                      QualType scalarTy,
8739                                      QualType vectorEltTy,
8740                                      QualType vectorTy,
8741                                      unsigned &DiagID) {
8742   // The conversion to apply to the scalar before splatting it,
8743   // if necessary.
8744   CastKind scalarCast = CK_NoOp;
8745 
8746   if (vectorEltTy->isIntegralType(S.Context)) {
8747     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8748         (scalarTy->isIntegerType() &&
8749          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8750       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8751       return true;
8752     }
8753     if (!scalarTy->isIntegralType(S.Context))
8754       return true;
8755     scalarCast = CK_IntegralCast;
8756   } else if (vectorEltTy->isRealFloatingType()) {
8757     if (scalarTy->isRealFloatingType()) {
8758       if (S.getLangOpts().OpenCL &&
8759           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8760         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8761         return true;
8762       }
8763       scalarCast = CK_FloatingCast;
8764     }
8765     else if (scalarTy->isIntegralType(S.Context))
8766       scalarCast = CK_IntegralToFloating;
8767     else
8768       return true;
8769   } else {
8770     return true;
8771   }
8772 
8773   // Adjust scalar if desired.
8774   if (scalar) {
8775     if (scalarCast != CK_NoOp)
8776       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8777     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8778   }
8779   return false;
8780 }
8781 
8782 /// Convert vector E to a vector with the same number of elements but different
8783 /// element type.
8784 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8785   const auto *VecTy = E->getType()->getAs<VectorType>();
8786   assert(VecTy && "Expression E must be a vector");
8787   QualType NewVecTy = S.Context.getVectorType(ElementType,
8788                                               VecTy->getNumElements(),
8789                                               VecTy->getVectorKind());
8790 
8791   // Look through the implicit cast. Return the subexpression if its type is
8792   // NewVecTy.
8793   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8794     if (ICE->getSubExpr()->getType() == NewVecTy)
8795       return ICE->getSubExpr();
8796 
8797   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8798   return S.ImpCastExprToType(E, NewVecTy, Cast);
8799 }
8800 
8801 /// Test if a (constant) integer Int can be casted to another integer type
8802 /// IntTy without losing precision.
8803 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8804                                       QualType OtherIntTy) {
8805   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8806 
8807   // Reject cases where the value of the Int is unknown as that would
8808   // possibly cause truncation, but accept cases where the scalar can be
8809   // demoted without loss of precision.
8810   Expr::EvalResult EVResult;
8811   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8812   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8813   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8814   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8815 
8816   if (CstInt) {
8817     // If the scalar is constant and is of a higher order and has more active
8818     // bits that the vector element type, reject it.
8819     llvm::APSInt Result = EVResult.Val.getInt();
8820     unsigned NumBits = IntSigned
8821                            ? (Result.isNegative() ? Result.getMinSignedBits()
8822                                                   : Result.getActiveBits())
8823                            : Result.getActiveBits();
8824     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8825       return true;
8826 
8827     // If the signedness of the scalar type and the vector element type
8828     // differs and the number of bits is greater than that of the vector
8829     // element reject it.
8830     return (IntSigned != OtherIntSigned &&
8831             NumBits > S.Context.getIntWidth(OtherIntTy));
8832   }
8833 
8834   // Reject cases where the value of the scalar is not constant and it's
8835   // order is greater than that of the vector element type.
8836   return (Order < 0);
8837 }
8838 
8839 /// Test if a (constant) integer Int can be casted to floating point type
8840 /// FloatTy without losing precision.
8841 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8842                                      QualType FloatTy) {
8843   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8844 
8845   // Determine if the integer constant can be expressed as a floating point
8846   // number of the appropriate type.
8847   Expr::EvalResult EVResult;
8848   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8849 
8850   uint64_t Bits = 0;
8851   if (CstInt) {
8852     // Reject constants that would be truncated if they were converted to
8853     // the floating point type. Test by simple to/from conversion.
8854     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8855     //        could be avoided if there was a convertFromAPInt method
8856     //        which could signal back if implicit truncation occurred.
8857     llvm::APSInt Result = EVResult.Val.getInt();
8858     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8859     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8860                            llvm::APFloat::rmTowardZero);
8861     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8862                              !IntTy->hasSignedIntegerRepresentation());
8863     bool Ignored = false;
8864     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8865                            &Ignored);
8866     if (Result != ConvertBack)
8867       return true;
8868   } else {
8869     // Reject types that cannot be fully encoded into the mantissa of
8870     // the float.
8871     Bits = S.Context.getTypeSize(IntTy);
8872     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8873         S.Context.getFloatTypeSemantics(FloatTy));
8874     if (Bits > FloatPrec)
8875       return true;
8876   }
8877 
8878   return false;
8879 }
8880 
8881 /// Attempt to convert and splat Scalar into a vector whose types matches
8882 /// Vector following GCC conversion rules. The rule is that implicit
8883 /// conversion can occur when Scalar can be casted to match Vector's element
8884 /// type without causing truncation of Scalar.
8885 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8886                                         ExprResult *Vector) {
8887   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8888   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8889   const VectorType *VT = VectorTy->getAs<VectorType>();
8890 
8891   assert(!isa<ExtVectorType>(VT) &&
8892          "ExtVectorTypes should not be handled here!");
8893 
8894   QualType VectorEltTy = VT->getElementType();
8895 
8896   // Reject cases where the vector element type or the scalar element type are
8897   // not integral or floating point types.
8898   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8899     return true;
8900 
8901   // The conversion to apply to the scalar before splatting it,
8902   // if necessary.
8903   CastKind ScalarCast = CK_NoOp;
8904 
8905   // Accept cases where the vector elements are integers and the scalar is
8906   // an integer.
8907   // FIXME: Notionally if the scalar was a floating point value with a precise
8908   //        integral representation, we could cast it to an appropriate integer
8909   //        type and then perform the rest of the checks here. GCC will perform
8910   //        this conversion in some cases as determined by the input language.
8911   //        We should accept it on a language independent basis.
8912   if (VectorEltTy->isIntegralType(S.Context) &&
8913       ScalarTy->isIntegralType(S.Context) &&
8914       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8915 
8916     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8917       return true;
8918 
8919     ScalarCast = CK_IntegralCast;
8920   } else if (VectorEltTy->isRealFloatingType()) {
8921     if (ScalarTy->isRealFloatingType()) {
8922 
8923       // Reject cases where the scalar type is not a constant and has a higher
8924       // Order than the vector element type.
8925       llvm::APFloat Result(0.0);
8926       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8927       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8928       if (!CstScalar && Order < 0)
8929         return true;
8930 
8931       // If the scalar cannot be safely casted to the vector element type,
8932       // reject it.
8933       if (CstScalar) {
8934         bool Truncated = false;
8935         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8936                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8937         if (Truncated)
8938           return true;
8939       }
8940 
8941       ScalarCast = CK_FloatingCast;
8942     } else if (ScalarTy->isIntegralType(S.Context)) {
8943       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8944         return true;
8945 
8946       ScalarCast = CK_IntegralToFloating;
8947     } else
8948       return true;
8949   }
8950 
8951   // Adjust scalar if desired.
8952   if (Scalar) {
8953     if (ScalarCast != CK_NoOp)
8954       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8955     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8956   }
8957   return false;
8958 }
8959 
8960 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8961                                    SourceLocation Loc, bool IsCompAssign,
8962                                    bool AllowBothBool,
8963                                    bool AllowBoolConversions) {
8964   if (!IsCompAssign) {
8965     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8966     if (LHS.isInvalid())
8967       return QualType();
8968   }
8969   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8970   if (RHS.isInvalid())
8971     return QualType();
8972 
8973   // For conversion purposes, we ignore any qualifiers.
8974   // For example, "const float" and "float" are equivalent.
8975   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8976   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8977 
8978   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8979   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8980   assert(LHSVecType || RHSVecType);
8981 
8982   // AltiVec-style "vector bool op vector bool" combinations are allowed
8983   // for some operators but not others.
8984   if (!AllowBothBool &&
8985       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8986       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8987     return InvalidOperands(Loc, LHS, RHS);
8988 
8989   // If the vector types are identical, return.
8990   if (Context.hasSameType(LHSType, RHSType))
8991     return LHSType;
8992 
8993   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8994   if (LHSVecType && RHSVecType &&
8995       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8996     if (isa<ExtVectorType>(LHSVecType)) {
8997       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8998       return LHSType;
8999     }
9000 
9001     if (!IsCompAssign)
9002       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9003     return RHSType;
9004   }
9005 
9006   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9007   // can be mixed, with the result being the non-bool type.  The non-bool
9008   // operand must have integer element type.
9009   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9010       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9011       (Context.getTypeSize(LHSVecType->getElementType()) ==
9012        Context.getTypeSize(RHSVecType->getElementType()))) {
9013     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9014         LHSVecType->getElementType()->isIntegerType() &&
9015         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9016       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9017       return LHSType;
9018     }
9019     if (!IsCompAssign &&
9020         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9021         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9022         RHSVecType->getElementType()->isIntegerType()) {
9023       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9024       return RHSType;
9025     }
9026   }
9027 
9028   // If there's a vector type and a scalar, try to convert the scalar to
9029   // the vector element type and splat.
9030   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9031   if (!RHSVecType) {
9032     if (isa<ExtVectorType>(LHSVecType)) {
9033       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9034                                     LHSVecType->getElementType(), LHSType,
9035                                     DiagID))
9036         return LHSType;
9037     } else {
9038       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9039         return LHSType;
9040     }
9041   }
9042   if (!LHSVecType) {
9043     if (isa<ExtVectorType>(RHSVecType)) {
9044       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9045                                     LHSType, RHSVecType->getElementType(),
9046                                     RHSType, DiagID))
9047         return RHSType;
9048     } else {
9049       if (LHS.get()->getValueKind() == VK_LValue ||
9050           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9051         return RHSType;
9052     }
9053   }
9054 
9055   // FIXME: The code below also handles conversion between vectors and
9056   // non-scalars, we should break this down into fine grained specific checks
9057   // and emit proper diagnostics.
9058   QualType VecType = LHSVecType ? LHSType : RHSType;
9059   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9060   QualType OtherType = LHSVecType ? RHSType : LHSType;
9061   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9062   if (isLaxVectorConversion(OtherType, VecType)) {
9063     // If we're allowing lax vector conversions, only the total (data) size
9064     // needs to be the same. For non compound assignment, if one of the types is
9065     // scalar, the result is always the vector type.
9066     if (!IsCompAssign) {
9067       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9068       return VecType;
9069     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9070     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9071     // type. Note that this is already done by non-compound assignments in
9072     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9073     // <1 x T> -> T. The result is also a vector type.
9074     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9075                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9076       ExprResult *RHSExpr = &RHS;
9077       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9078       return VecType;
9079     }
9080   }
9081 
9082   // Okay, the expression is invalid.
9083 
9084   // If there's a non-vector, non-real operand, diagnose that.
9085   if ((!RHSVecType && !RHSType->isRealType()) ||
9086       (!LHSVecType && !LHSType->isRealType())) {
9087     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9088       << LHSType << RHSType
9089       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9090     return QualType();
9091   }
9092 
9093   // OpenCL V1.1 6.2.6.p1:
9094   // If the operands are of more than one vector type, then an error shall
9095   // occur. Implicit conversions between vector types are not permitted, per
9096   // section 6.2.1.
9097   if (getLangOpts().OpenCL &&
9098       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9099       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9100     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9101                                                            << RHSType;
9102     return QualType();
9103   }
9104 
9105 
9106   // If there is a vector type that is not a ExtVector and a scalar, we reach
9107   // this point if scalar could not be converted to the vector's element type
9108   // without truncation.
9109   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9110       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9111     QualType Scalar = LHSVecType ? RHSType : LHSType;
9112     QualType Vector = LHSVecType ? LHSType : RHSType;
9113     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9114     Diag(Loc,
9115          diag::err_typecheck_vector_not_convertable_implict_truncation)
9116         << ScalarOrVector << Scalar << Vector;
9117 
9118     return QualType();
9119   }
9120 
9121   // Otherwise, use the generic diagnostic.
9122   Diag(Loc, DiagID)
9123     << LHSType << RHSType
9124     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9125   return QualType();
9126 }
9127 
9128 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9129 // expression.  These are mainly cases where the null pointer is used as an
9130 // integer instead of a pointer.
9131 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9132                                 SourceLocation Loc, bool IsCompare) {
9133   // The canonical way to check for a GNU null is with isNullPointerConstant,
9134   // but we use a bit of a hack here for speed; this is a relatively
9135   // hot path, and isNullPointerConstant is slow.
9136   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9137   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9138 
9139   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9140 
9141   // Avoid analyzing cases where the result will either be invalid (and
9142   // diagnosed as such) or entirely valid and not something to warn about.
9143   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9144       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9145     return;
9146 
9147   // Comparison operations would not make sense with a null pointer no matter
9148   // what the other expression is.
9149   if (!IsCompare) {
9150     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9151         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9152         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9153     return;
9154   }
9155 
9156   // The rest of the operations only make sense with a null pointer
9157   // if the other expression is a pointer.
9158   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9159       NonNullType->canDecayToPointerType())
9160     return;
9161 
9162   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9163       << LHSNull /* LHS is NULL */ << NonNullType
9164       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9165 }
9166 
9167 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9168                                           SourceLocation Loc) {
9169   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9170   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9171   if (!LUE || !RUE)
9172     return;
9173   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9174       RUE->getKind() != UETT_SizeOf)
9175     return;
9176 
9177   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9178   QualType LHSTy = LHSArg->getType();
9179   QualType RHSTy;
9180 
9181   if (RUE->isArgumentType())
9182     RHSTy = RUE->getArgumentType();
9183   else
9184     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9185 
9186   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9187     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9188       return;
9189 
9190     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9191     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9192       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9193         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9194             << LHSArgDecl;
9195     }
9196   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9197     QualType ArrayElemTy = ArrayTy->getElementType();
9198     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9199         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9200         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9201       return;
9202     S.Diag(Loc, diag::warn_division_sizeof_array)
9203         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9204     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9205       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9206         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9207             << LHSArgDecl;
9208     }
9209 
9210     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9211   }
9212 }
9213 
9214 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9215                                                ExprResult &RHS,
9216                                                SourceLocation Loc, bool IsDiv) {
9217   // Check for division/remainder by zero.
9218   Expr::EvalResult RHSValue;
9219   if (!RHS.get()->isValueDependent() &&
9220       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9221       RHSValue.Val.getInt() == 0)
9222     S.DiagRuntimeBehavior(Loc, RHS.get(),
9223                           S.PDiag(diag::warn_remainder_division_by_zero)
9224                             << IsDiv << RHS.get()->getSourceRange());
9225 }
9226 
9227 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9228                                            SourceLocation Loc,
9229                                            bool IsCompAssign, bool IsDiv) {
9230   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9231 
9232   if (LHS.get()->getType()->isVectorType() ||
9233       RHS.get()->getType()->isVectorType())
9234     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9235                                /*AllowBothBool*/getLangOpts().AltiVec,
9236                                /*AllowBoolConversions*/false);
9237 
9238   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9239   if (LHS.isInvalid() || RHS.isInvalid())
9240     return QualType();
9241 
9242 
9243   if (compType.isNull() || !compType->isArithmeticType())
9244     return InvalidOperands(Loc, LHS, RHS);
9245   if (IsDiv) {
9246     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9247     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9248   }
9249   return compType;
9250 }
9251 
9252 QualType Sema::CheckRemainderOperands(
9253   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9254   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9255 
9256   if (LHS.get()->getType()->isVectorType() ||
9257       RHS.get()->getType()->isVectorType()) {
9258     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9259         RHS.get()->getType()->hasIntegerRepresentation())
9260       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9261                                  /*AllowBothBool*/getLangOpts().AltiVec,
9262                                  /*AllowBoolConversions*/false);
9263     return InvalidOperands(Loc, LHS, RHS);
9264   }
9265 
9266   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9267   if (LHS.isInvalid() || RHS.isInvalid())
9268     return QualType();
9269 
9270   if (compType.isNull() || !compType->isIntegerType())
9271     return InvalidOperands(Loc, LHS, RHS);
9272   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9273   return compType;
9274 }
9275 
9276 /// Diagnose invalid arithmetic on two void pointers.
9277 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9278                                                 Expr *LHSExpr, Expr *RHSExpr) {
9279   S.Diag(Loc, S.getLangOpts().CPlusPlus
9280                 ? diag::err_typecheck_pointer_arith_void_type
9281                 : diag::ext_gnu_void_ptr)
9282     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9283                             << RHSExpr->getSourceRange();
9284 }
9285 
9286 /// Diagnose invalid arithmetic on a void pointer.
9287 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9288                                             Expr *Pointer) {
9289   S.Diag(Loc, S.getLangOpts().CPlusPlus
9290                 ? diag::err_typecheck_pointer_arith_void_type
9291                 : diag::ext_gnu_void_ptr)
9292     << 0 /* one pointer */ << Pointer->getSourceRange();
9293 }
9294 
9295 /// Diagnose invalid arithmetic on a null pointer.
9296 ///
9297 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9298 /// idiom, which we recognize as a GNU extension.
9299 ///
9300 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9301                                             Expr *Pointer, bool IsGNUIdiom) {
9302   if (IsGNUIdiom)
9303     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9304       << Pointer->getSourceRange();
9305   else
9306     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9307       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9308 }
9309 
9310 /// Diagnose invalid arithmetic on two function pointers.
9311 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9312                                                     Expr *LHS, Expr *RHS) {
9313   assert(LHS->getType()->isAnyPointerType());
9314   assert(RHS->getType()->isAnyPointerType());
9315   S.Diag(Loc, S.getLangOpts().CPlusPlus
9316                 ? diag::err_typecheck_pointer_arith_function_type
9317                 : diag::ext_gnu_ptr_func_arith)
9318     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9319     // We only show the second type if it differs from the first.
9320     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9321                                                    RHS->getType())
9322     << RHS->getType()->getPointeeType()
9323     << LHS->getSourceRange() << RHS->getSourceRange();
9324 }
9325 
9326 /// Diagnose invalid arithmetic on a function pointer.
9327 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9328                                                 Expr *Pointer) {
9329   assert(Pointer->getType()->isAnyPointerType());
9330   S.Diag(Loc, S.getLangOpts().CPlusPlus
9331                 ? diag::err_typecheck_pointer_arith_function_type
9332                 : diag::ext_gnu_ptr_func_arith)
9333     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9334     << 0 /* one pointer, so only one type */
9335     << Pointer->getSourceRange();
9336 }
9337 
9338 /// Emit error if Operand is incomplete pointer type
9339 ///
9340 /// \returns True if pointer has incomplete type
9341 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9342                                                  Expr *Operand) {
9343   QualType ResType = Operand->getType();
9344   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9345     ResType = ResAtomicType->getValueType();
9346 
9347   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9348   QualType PointeeTy = ResType->getPointeeType();
9349   return S.RequireCompleteType(Loc, PointeeTy,
9350                                diag::err_typecheck_arithmetic_incomplete_type,
9351                                PointeeTy, Operand->getSourceRange());
9352 }
9353 
9354 /// Check the validity of an arithmetic pointer operand.
9355 ///
9356 /// If the operand has pointer type, this code will check for pointer types
9357 /// which are invalid in arithmetic operations. These will be diagnosed
9358 /// appropriately, including whether or not the use is supported as an
9359 /// extension.
9360 ///
9361 /// \returns True when the operand is valid to use (even if as an extension).
9362 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9363                                             Expr *Operand) {
9364   QualType ResType = Operand->getType();
9365   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9366     ResType = ResAtomicType->getValueType();
9367 
9368   if (!ResType->isAnyPointerType()) return true;
9369 
9370   QualType PointeeTy = ResType->getPointeeType();
9371   if (PointeeTy->isVoidType()) {
9372     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9373     return !S.getLangOpts().CPlusPlus;
9374   }
9375   if (PointeeTy->isFunctionType()) {
9376     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9377     return !S.getLangOpts().CPlusPlus;
9378   }
9379 
9380   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9381 
9382   return true;
9383 }
9384 
9385 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9386 /// operands.
9387 ///
9388 /// This routine will diagnose any invalid arithmetic on pointer operands much
9389 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9390 /// for emitting a single diagnostic even for operations where both LHS and RHS
9391 /// are (potentially problematic) pointers.
9392 ///
9393 /// \returns True when the operand is valid to use (even if as an extension).
9394 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9395                                                 Expr *LHSExpr, Expr *RHSExpr) {
9396   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9397   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9398   if (!isLHSPointer && !isRHSPointer) return true;
9399 
9400   QualType LHSPointeeTy, RHSPointeeTy;
9401   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9402   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9403 
9404   // if both are pointers check if operation is valid wrt address spaces
9405   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9406     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9407     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9408     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9409       S.Diag(Loc,
9410              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9411           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9412           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9413       return false;
9414     }
9415   }
9416 
9417   // Check for arithmetic on pointers to incomplete types.
9418   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9419   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9420   if (isLHSVoidPtr || isRHSVoidPtr) {
9421     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9422     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9423     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9424 
9425     return !S.getLangOpts().CPlusPlus;
9426   }
9427 
9428   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9429   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9430   if (isLHSFuncPtr || isRHSFuncPtr) {
9431     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9432     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9433                                                                 RHSExpr);
9434     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9435 
9436     return !S.getLangOpts().CPlusPlus;
9437   }
9438 
9439   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9440     return false;
9441   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9442     return false;
9443 
9444   return true;
9445 }
9446 
9447 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9448 /// literal.
9449 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9450                                   Expr *LHSExpr, Expr *RHSExpr) {
9451   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9452   Expr* IndexExpr = RHSExpr;
9453   if (!StrExpr) {
9454     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9455     IndexExpr = LHSExpr;
9456   }
9457 
9458   bool IsStringPlusInt = StrExpr &&
9459       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9460   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9461     return;
9462 
9463   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9464   Self.Diag(OpLoc, diag::warn_string_plus_int)
9465       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9466 
9467   // Only print a fixit for "str" + int, not for int + "str".
9468   if (IndexExpr == RHSExpr) {
9469     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9470     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9471         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9472         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9473         << FixItHint::CreateInsertion(EndLoc, "]");
9474   } else
9475     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9476 }
9477 
9478 /// Emit a warning when adding a char literal to a string.
9479 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9480                                    Expr *LHSExpr, Expr *RHSExpr) {
9481   const Expr *StringRefExpr = LHSExpr;
9482   const CharacterLiteral *CharExpr =
9483       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9484 
9485   if (!CharExpr) {
9486     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9487     StringRefExpr = RHSExpr;
9488   }
9489 
9490   if (!CharExpr || !StringRefExpr)
9491     return;
9492 
9493   const QualType StringType = StringRefExpr->getType();
9494 
9495   // Return if not a PointerType.
9496   if (!StringType->isAnyPointerType())
9497     return;
9498 
9499   // Return if not a CharacterType.
9500   if (!StringType->getPointeeType()->isAnyCharacterType())
9501     return;
9502 
9503   ASTContext &Ctx = Self.getASTContext();
9504   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9505 
9506   const QualType CharType = CharExpr->getType();
9507   if (!CharType->isAnyCharacterType() &&
9508       CharType->isIntegerType() &&
9509       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9510     Self.Diag(OpLoc, diag::warn_string_plus_char)
9511         << DiagRange << Ctx.CharTy;
9512   } else {
9513     Self.Diag(OpLoc, diag::warn_string_plus_char)
9514         << DiagRange << CharExpr->getType();
9515   }
9516 
9517   // Only print a fixit for str + char, not for char + str.
9518   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9519     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9520     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9521         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9522         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9523         << FixItHint::CreateInsertion(EndLoc, "]");
9524   } else {
9525     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9526   }
9527 }
9528 
9529 /// Emit error when two pointers are incompatible.
9530 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9531                                            Expr *LHSExpr, Expr *RHSExpr) {
9532   assert(LHSExpr->getType()->isAnyPointerType());
9533   assert(RHSExpr->getType()->isAnyPointerType());
9534   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9535     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9536     << RHSExpr->getSourceRange();
9537 }
9538 
9539 // C99 6.5.6
9540 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9541                                      SourceLocation Loc, BinaryOperatorKind Opc,
9542                                      QualType* CompLHSTy) {
9543   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9544 
9545   if (LHS.get()->getType()->isVectorType() ||
9546       RHS.get()->getType()->isVectorType()) {
9547     QualType compType = CheckVectorOperands(
9548         LHS, RHS, Loc, CompLHSTy,
9549         /*AllowBothBool*/getLangOpts().AltiVec,
9550         /*AllowBoolConversions*/getLangOpts().ZVector);
9551     if (CompLHSTy) *CompLHSTy = compType;
9552     return compType;
9553   }
9554 
9555   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9556   if (LHS.isInvalid() || RHS.isInvalid())
9557     return QualType();
9558 
9559   // Diagnose "string literal" '+' int and string '+' "char literal".
9560   if (Opc == BO_Add) {
9561     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9562     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9563   }
9564 
9565   // handle the common case first (both operands are arithmetic).
9566   if (!compType.isNull() && compType->isArithmeticType()) {
9567     if (CompLHSTy) *CompLHSTy = compType;
9568     return compType;
9569   }
9570 
9571   // Type-checking.  Ultimately the pointer's going to be in PExp;
9572   // note that we bias towards the LHS being the pointer.
9573   Expr *PExp = LHS.get(), *IExp = RHS.get();
9574 
9575   bool isObjCPointer;
9576   if (PExp->getType()->isPointerType()) {
9577     isObjCPointer = false;
9578   } else if (PExp->getType()->isObjCObjectPointerType()) {
9579     isObjCPointer = true;
9580   } else {
9581     std::swap(PExp, IExp);
9582     if (PExp->getType()->isPointerType()) {
9583       isObjCPointer = false;
9584     } else if (PExp->getType()->isObjCObjectPointerType()) {
9585       isObjCPointer = true;
9586     } else {
9587       return InvalidOperands(Loc, LHS, RHS);
9588     }
9589   }
9590   assert(PExp->getType()->isAnyPointerType());
9591 
9592   if (!IExp->getType()->isIntegerType())
9593     return InvalidOperands(Loc, LHS, RHS);
9594 
9595   // Adding to a null pointer results in undefined behavior.
9596   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9597           Context, Expr::NPC_ValueDependentIsNotNull)) {
9598     // In C++ adding zero to a null pointer is defined.
9599     Expr::EvalResult KnownVal;
9600     if (!getLangOpts().CPlusPlus ||
9601         (!IExp->isValueDependent() &&
9602          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9603           KnownVal.Val.getInt() != 0))) {
9604       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9605       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9606           Context, BO_Add, PExp, IExp);
9607       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9608     }
9609   }
9610 
9611   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9612     return QualType();
9613 
9614   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9615     return QualType();
9616 
9617   // Check array bounds for pointer arithemtic
9618   CheckArrayAccess(PExp, IExp);
9619 
9620   if (CompLHSTy) {
9621     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9622     if (LHSTy.isNull()) {
9623       LHSTy = LHS.get()->getType();
9624       if (LHSTy->isPromotableIntegerType())
9625         LHSTy = Context.getPromotedIntegerType(LHSTy);
9626     }
9627     *CompLHSTy = LHSTy;
9628   }
9629 
9630   return PExp->getType();
9631 }
9632 
9633 // C99 6.5.6
9634 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9635                                         SourceLocation Loc,
9636                                         QualType* CompLHSTy) {
9637   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9638 
9639   if (LHS.get()->getType()->isVectorType() ||
9640       RHS.get()->getType()->isVectorType()) {
9641     QualType compType = CheckVectorOperands(
9642         LHS, RHS, Loc, CompLHSTy,
9643         /*AllowBothBool*/getLangOpts().AltiVec,
9644         /*AllowBoolConversions*/getLangOpts().ZVector);
9645     if (CompLHSTy) *CompLHSTy = compType;
9646     return compType;
9647   }
9648 
9649   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9650   if (LHS.isInvalid() || RHS.isInvalid())
9651     return QualType();
9652 
9653   // Enforce type constraints: C99 6.5.6p3.
9654 
9655   // Handle the common case first (both operands are arithmetic).
9656   if (!compType.isNull() && compType->isArithmeticType()) {
9657     if (CompLHSTy) *CompLHSTy = compType;
9658     return compType;
9659   }
9660 
9661   // Either ptr - int   or   ptr - ptr.
9662   if (LHS.get()->getType()->isAnyPointerType()) {
9663     QualType lpointee = LHS.get()->getType()->getPointeeType();
9664 
9665     // Diagnose bad cases where we step over interface counts.
9666     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9667         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9668       return QualType();
9669 
9670     // The result type of a pointer-int computation is the pointer type.
9671     if (RHS.get()->getType()->isIntegerType()) {
9672       // Subtracting from a null pointer should produce a warning.
9673       // The last argument to the diagnose call says this doesn't match the
9674       // GNU int-to-pointer idiom.
9675       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9676                                            Expr::NPC_ValueDependentIsNotNull)) {
9677         // In C++ adding zero to a null pointer is defined.
9678         Expr::EvalResult KnownVal;
9679         if (!getLangOpts().CPlusPlus ||
9680             (!RHS.get()->isValueDependent() &&
9681              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9682               KnownVal.Val.getInt() != 0))) {
9683           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9684         }
9685       }
9686 
9687       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9688         return QualType();
9689 
9690       // Check array bounds for pointer arithemtic
9691       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9692                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9693 
9694       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9695       return LHS.get()->getType();
9696     }
9697 
9698     // Handle pointer-pointer subtractions.
9699     if (const PointerType *RHSPTy
9700           = RHS.get()->getType()->getAs<PointerType>()) {
9701       QualType rpointee = RHSPTy->getPointeeType();
9702 
9703       if (getLangOpts().CPlusPlus) {
9704         // Pointee types must be the same: C++ [expr.add]
9705         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9706           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9707         }
9708       } else {
9709         // Pointee types must be compatible C99 6.5.6p3
9710         if (!Context.typesAreCompatible(
9711                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9712                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9713           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9714           return QualType();
9715         }
9716       }
9717 
9718       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9719                                                LHS.get(), RHS.get()))
9720         return QualType();
9721 
9722       // FIXME: Add warnings for nullptr - ptr.
9723 
9724       // The pointee type may have zero size.  As an extension, a structure or
9725       // union may have zero size or an array may have zero length.  In this
9726       // case subtraction does not make sense.
9727       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9728         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9729         if (ElementSize.isZero()) {
9730           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9731             << rpointee.getUnqualifiedType()
9732             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9733         }
9734       }
9735 
9736       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9737       return Context.getPointerDiffType();
9738     }
9739   }
9740 
9741   return InvalidOperands(Loc, LHS, RHS);
9742 }
9743 
9744 static bool isScopedEnumerationType(QualType T) {
9745   if (const EnumType *ET = T->getAs<EnumType>())
9746     return ET->getDecl()->isScoped();
9747   return false;
9748 }
9749 
9750 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9751                                    SourceLocation Loc, BinaryOperatorKind Opc,
9752                                    QualType LHSType) {
9753   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9754   // so skip remaining warnings as we don't want to modify values within Sema.
9755   if (S.getLangOpts().OpenCL)
9756     return;
9757 
9758   // Check right/shifter operand
9759   Expr::EvalResult RHSResult;
9760   if (RHS.get()->isValueDependent() ||
9761       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9762     return;
9763   llvm::APSInt Right = RHSResult.Val.getInt();
9764 
9765   if (Right.isNegative()) {
9766     S.DiagRuntimeBehavior(Loc, RHS.get(),
9767                           S.PDiag(diag::warn_shift_negative)
9768                             << RHS.get()->getSourceRange());
9769     return;
9770   }
9771   llvm::APInt LeftBits(Right.getBitWidth(),
9772                        S.Context.getTypeSize(LHS.get()->getType()));
9773   if (Right.uge(LeftBits)) {
9774     S.DiagRuntimeBehavior(Loc, RHS.get(),
9775                           S.PDiag(diag::warn_shift_gt_typewidth)
9776                             << RHS.get()->getSourceRange());
9777     return;
9778   }
9779   if (Opc != BO_Shl)
9780     return;
9781 
9782   // When left shifting an ICE which is signed, we can check for overflow which
9783   // according to C++ standards prior to C++2a has undefined behavior
9784   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9785   // more than the maximum value representable in the result type, so never
9786   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9787   // expression is still probably a bug.)
9788   Expr::EvalResult LHSResult;
9789   if (LHS.get()->isValueDependent() ||
9790       LHSType->hasUnsignedIntegerRepresentation() ||
9791       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9792     return;
9793   llvm::APSInt Left = LHSResult.Val.getInt();
9794 
9795   // If LHS does not have a signed type and non-negative value
9796   // then, the behavior is undefined before C++2a. Warn about it.
9797   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9798       !S.getLangOpts().CPlusPlus2a) {
9799     S.DiagRuntimeBehavior(Loc, LHS.get(),
9800                           S.PDiag(diag::warn_shift_lhs_negative)
9801                             << LHS.get()->getSourceRange());
9802     return;
9803   }
9804 
9805   llvm::APInt ResultBits =
9806       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9807   if (LeftBits.uge(ResultBits))
9808     return;
9809   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9810   Result = Result.shl(Right);
9811 
9812   // Print the bit representation of the signed integer as an unsigned
9813   // hexadecimal number.
9814   SmallString<40> HexResult;
9815   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9816 
9817   // If we are only missing a sign bit, this is less likely to result in actual
9818   // bugs -- if the result is cast back to an unsigned type, it will have the
9819   // expected value. Thus we place this behind a different warning that can be
9820   // turned off separately if needed.
9821   if (LeftBits == ResultBits - 1) {
9822     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9823         << HexResult << LHSType
9824         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9825     return;
9826   }
9827 
9828   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9829     << HexResult.str() << Result.getMinSignedBits() << LHSType
9830     << Left.getBitWidth() << LHS.get()->getSourceRange()
9831     << RHS.get()->getSourceRange();
9832 }
9833 
9834 /// Return the resulting type when a vector is shifted
9835 ///        by a scalar or vector shift amount.
9836 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9837                                  SourceLocation Loc, bool IsCompAssign) {
9838   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9839   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9840       !LHS.get()->getType()->isVectorType()) {
9841     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9842       << RHS.get()->getType() << LHS.get()->getType()
9843       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9844     return QualType();
9845   }
9846 
9847   if (!IsCompAssign) {
9848     LHS = S.UsualUnaryConversions(LHS.get());
9849     if (LHS.isInvalid()) return QualType();
9850   }
9851 
9852   RHS = S.UsualUnaryConversions(RHS.get());
9853   if (RHS.isInvalid()) return QualType();
9854 
9855   QualType LHSType = LHS.get()->getType();
9856   // Note that LHS might be a scalar because the routine calls not only in
9857   // OpenCL case.
9858   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9859   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9860 
9861   // Note that RHS might not be a vector.
9862   QualType RHSType = RHS.get()->getType();
9863   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9864   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9865 
9866   // The operands need to be integers.
9867   if (!LHSEleType->isIntegerType()) {
9868     S.Diag(Loc, diag::err_typecheck_expect_int)
9869       << LHS.get()->getType() << LHS.get()->getSourceRange();
9870     return QualType();
9871   }
9872 
9873   if (!RHSEleType->isIntegerType()) {
9874     S.Diag(Loc, diag::err_typecheck_expect_int)
9875       << RHS.get()->getType() << RHS.get()->getSourceRange();
9876     return QualType();
9877   }
9878 
9879   if (!LHSVecTy) {
9880     assert(RHSVecTy);
9881     if (IsCompAssign)
9882       return RHSType;
9883     if (LHSEleType != RHSEleType) {
9884       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9885       LHSEleType = RHSEleType;
9886     }
9887     QualType VecTy =
9888         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9889     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9890     LHSType = VecTy;
9891   } else if (RHSVecTy) {
9892     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9893     // are applied component-wise. So if RHS is a vector, then ensure
9894     // that the number of elements is the same as LHS...
9895     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9896       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9897         << LHS.get()->getType() << RHS.get()->getType()
9898         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9899       return QualType();
9900     }
9901     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9902       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9903       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9904       if (LHSBT != RHSBT &&
9905           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9906         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9907             << LHS.get()->getType() << RHS.get()->getType()
9908             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9909       }
9910     }
9911   } else {
9912     // ...else expand RHS to match the number of elements in LHS.
9913     QualType VecTy =
9914       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9915     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9916   }
9917 
9918   return LHSType;
9919 }
9920 
9921 // C99 6.5.7
9922 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9923                                   SourceLocation Loc, BinaryOperatorKind Opc,
9924                                   bool IsCompAssign) {
9925   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9926 
9927   // Vector shifts promote their scalar inputs to vector type.
9928   if (LHS.get()->getType()->isVectorType() ||
9929       RHS.get()->getType()->isVectorType()) {
9930     if (LangOpts.ZVector) {
9931       // The shift operators for the z vector extensions work basically
9932       // like general shifts, except that neither the LHS nor the RHS is
9933       // allowed to be a "vector bool".
9934       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9935         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9936           return InvalidOperands(Loc, LHS, RHS);
9937       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9938         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9939           return InvalidOperands(Loc, LHS, RHS);
9940     }
9941     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9942   }
9943 
9944   // Shifts don't perform usual arithmetic conversions, they just do integer
9945   // promotions on each operand. C99 6.5.7p3
9946 
9947   // For the LHS, do usual unary conversions, but then reset them away
9948   // if this is a compound assignment.
9949   ExprResult OldLHS = LHS;
9950   LHS = UsualUnaryConversions(LHS.get());
9951   if (LHS.isInvalid())
9952     return QualType();
9953   QualType LHSType = LHS.get()->getType();
9954   if (IsCompAssign) LHS = OldLHS;
9955 
9956   // The RHS is simpler.
9957   RHS = UsualUnaryConversions(RHS.get());
9958   if (RHS.isInvalid())
9959     return QualType();
9960   QualType RHSType = RHS.get()->getType();
9961 
9962   // C99 6.5.7p2: Each of the operands shall have integer type.
9963   if (!LHSType->hasIntegerRepresentation() ||
9964       !RHSType->hasIntegerRepresentation())
9965     return InvalidOperands(Loc, LHS, RHS);
9966 
9967   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9968   // hasIntegerRepresentation() above instead of this.
9969   if (isScopedEnumerationType(LHSType) ||
9970       isScopedEnumerationType(RHSType)) {
9971     return InvalidOperands(Loc, LHS, RHS);
9972   }
9973   // Sanity-check shift operands
9974   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9975 
9976   // "The type of the result is that of the promoted left operand."
9977   return LHSType;
9978 }
9979 
9980 /// If two different enums are compared, raise a warning.
9981 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9982                                 Expr *RHS) {
9983   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9984   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9985 
9986   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9987   if (!LHSEnumType)
9988     return;
9989   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9990   if (!RHSEnumType)
9991     return;
9992 
9993   // Ignore anonymous enums.
9994   if (!LHSEnumType->getDecl()->getIdentifier() &&
9995       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9996     return;
9997   if (!RHSEnumType->getDecl()->getIdentifier() &&
9998       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9999     return;
10000 
10001   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
10002     return;
10003 
10004   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
10005       << LHSStrippedType << RHSStrippedType
10006       << LHS->getSourceRange() << RHS->getSourceRange();
10007 }
10008 
10009 /// Diagnose bad pointer comparisons.
10010 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10011                                               ExprResult &LHS, ExprResult &RHS,
10012                                               bool IsError) {
10013   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10014                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10015     << LHS.get()->getType() << RHS.get()->getType()
10016     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10017 }
10018 
10019 /// Returns false if the pointers are converted to a composite type,
10020 /// true otherwise.
10021 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10022                                            ExprResult &LHS, ExprResult &RHS) {
10023   // C++ [expr.rel]p2:
10024   //   [...] Pointer conversions (4.10) and qualification
10025   //   conversions (4.4) are performed on pointer operands (or on
10026   //   a pointer operand and a null pointer constant) to bring
10027   //   them to their composite pointer type. [...]
10028   //
10029   // C++ [expr.eq]p1 uses the same notion for (in)equality
10030   // comparisons of pointers.
10031 
10032   QualType LHSType = LHS.get()->getType();
10033   QualType RHSType = RHS.get()->getType();
10034   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10035          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10036 
10037   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10038   if (T.isNull()) {
10039     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
10040         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
10041       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10042     else
10043       S.InvalidOperands(Loc, LHS, RHS);
10044     return true;
10045   }
10046 
10047   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
10048   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
10049   return false;
10050 }
10051 
10052 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10053                                                     ExprResult &LHS,
10054                                                     ExprResult &RHS,
10055                                                     bool IsError) {
10056   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10057                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10058     << LHS.get()->getType() << RHS.get()->getType()
10059     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10060 }
10061 
10062 static bool isObjCObjectLiteral(ExprResult &E) {
10063   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10064   case Stmt::ObjCArrayLiteralClass:
10065   case Stmt::ObjCDictionaryLiteralClass:
10066   case Stmt::ObjCStringLiteralClass:
10067   case Stmt::ObjCBoxedExprClass:
10068     return true;
10069   default:
10070     // Note that ObjCBoolLiteral is NOT an object literal!
10071     return false;
10072   }
10073 }
10074 
10075 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10076   const ObjCObjectPointerType *Type =
10077     LHS->getType()->getAs<ObjCObjectPointerType>();
10078 
10079   // If this is not actually an Objective-C object, bail out.
10080   if (!Type)
10081     return false;
10082 
10083   // Get the LHS object's interface type.
10084   QualType InterfaceType = Type->getPointeeType();
10085 
10086   // If the RHS isn't an Objective-C object, bail out.
10087   if (!RHS->getType()->isObjCObjectPointerType())
10088     return false;
10089 
10090   // Try to find the -isEqual: method.
10091   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10092   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10093                                                       InterfaceType,
10094                                                       /*IsInstance=*/true);
10095   if (!Method) {
10096     if (Type->isObjCIdType()) {
10097       // For 'id', just check the global pool.
10098       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10099                                                   /*receiverId=*/true);
10100     } else {
10101       // Check protocols.
10102       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10103                                              /*IsInstance=*/true);
10104     }
10105   }
10106 
10107   if (!Method)
10108     return false;
10109 
10110   QualType T = Method->parameters()[0]->getType();
10111   if (!T->isObjCObjectPointerType())
10112     return false;
10113 
10114   QualType R = Method->getReturnType();
10115   if (!R->isScalarType())
10116     return false;
10117 
10118   return true;
10119 }
10120 
10121 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10122   FromE = FromE->IgnoreParenImpCasts();
10123   switch (FromE->getStmtClass()) {
10124     default:
10125       break;
10126     case Stmt::ObjCStringLiteralClass:
10127       // "string literal"
10128       return LK_String;
10129     case Stmt::ObjCArrayLiteralClass:
10130       // "array literal"
10131       return LK_Array;
10132     case Stmt::ObjCDictionaryLiteralClass:
10133       // "dictionary literal"
10134       return LK_Dictionary;
10135     case Stmt::BlockExprClass:
10136       return LK_Block;
10137     case Stmt::ObjCBoxedExprClass: {
10138       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10139       switch (Inner->getStmtClass()) {
10140         case Stmt::IntegerLiteralClass:
10141         case Stmt::FloatingLiteralClass:
10142         case Stmt::CharacterLiteralClass:
10143         case Stmt::ObjCBoolLiteralExprClass:
10144         case Stmt::CXXBoolLiteralExprClass:
10145           // "numeric literal"
10146           return LK_Numeric;
10147         case Stmt::ImplicitCastExprClass: {
10148           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10149           // Boolean literals can be represented by implicit casts.
10150           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10151             return LK_Numeric;
10152           break;
10153         }
10154         default:
10155           break;
10156       }
10157       return LK_Boxed;
10158     }
10159   }
10160   return LK_None;
10161 }
10162 
10163 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10164                                           ExprResult &LHS, ExprResult &RHS,
10165                                           BinaryOperator::Opcode Opc){
10166   Expr *Literal;
10167   Expr *Other;
10168   if (isObjCObjectLiteral(LHS)) {
10169     Literal = LHS.get();
10170     Other = RHS.get();
10171   } else {
10172     Literal = RHS.get();
10173     Other = LHS.get();
10174   }
10175 
10176   // Don't warn on comparisons against nil.
10177   Other = Other->IgnoreParenCasts();
10178   if (Other->isNullPointerConstant(S.getASTContext(),
10179                                    Expr::NPC_ValueDependentIsNotNull))
10180     return;
10181 
10182   // This should be kept in sync with warn_objc_literal_comparison.
10183   // LK_String should always be after the other literals, since it has its own
10184   // warning flag.
10185   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10186   assert(LiteralKind != Sema::LK_Block);
10187   if (LiteralKind == Sema::LK_None) {
10188     llvm_unreachable("Unknown Objective-C object literal kind");
10189   }
10190 
10191   if (LiteralKind == Sema::LK_String)
10192     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10193       << Literal->getSourceRange();
10194   else
10195     S.Diag(Loc, diag::warn_objc_literal_comparison)
10196       << LiteralKind << Literal->getSourceRange();
10197 
10198   if (BinaryOperator::isEqualityOp(Opc) &&
10199       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10200     SourceLocation Start = LHS.get()->getBeginLoc();
10201     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10202     CharSourceRange OpRange =
10203       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10204 
10205     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10206       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10207       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10208       << FixItHint::CreateInsertion(End, "]");
10209   }
10210 }
10211 
10212 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10213 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10214                                            ExprResult &RHS, SourceLocation Loc,
10215                                            BinaryOperatorKind Opc) {
10216   // Check that left hand side is !something.
10217   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10218   if (!UO || UO->getOpcode() != UO_LNot) return;
10219 
10220   // Only check if the right hand side is non-bool arithmetic type.
10221   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10222 
10223   // Make sure that the something in !something is not bool.
10224   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10225   if (SubExpr->isKnownToHaveBooleanValue()) return;
10226 
10227   // Emit warning.
10228   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10229   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10230       << Loc << IsBitwiseOp;
10231 
10232   // First note suggest !(x < y)
10233   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10234   SourceLocation FirstClose = RHS.get()->getEndLoc();
10235   FirstClose = S.getLocForEndOfToken(FirstClose);
10236   if (FirstClose.isInvalid())
10237     FirstOpen = SourceLocation();
10238   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10239       << IsBitwiseOp
10240       << FixItHint::CreateInsertion(FirstOpen, "(")
10241       << FixItHint::CreateInsertion(FirstClose, ")");
10242 
10243   // Second note suggests (!x) < y
10244   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10245   SourceLocation SecondClose = LHS.get()->getEndLoc();
10246   SecondClose = S.getLocForEndOfToken(SecondClose);
10247   if (SecondClose.isInvalid())
10248     SecondOpen = SourceLocation();
10249   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10250       << FixItHint::CreateInsertion(SecondOpen, "(")
10251       << FixItHint::CreateInsertion(SecondClose, ")");
10252 }
10253 
10254 // Returns true if E refers to a non-weak array.
10255 static bool checkForArray(const Expr *E) {
10256   const ValueDecl *D = nullptr;
10257   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10258     D = DR->getDecl();
10259   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10260     if (Mem->isImplicitAccess())
10261       D = Mem->getMemberDecl();
10262   }
10263   if (!D)
10264     return false;
10265   return D->getType()->isArrayType() && !D->isWeak();
10266 }
10267 
10268 /// Diagnose some forms of syntactically-obvious tautological comparison.
10269 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10270                                            Expr *LHS, Expr *RHS,
10271                                            BinaryOperatorKind Opc) {
10272   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10273   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10274 
10275   QualType LHSType = LHS->getType();
10276   QualType RHSType = RHS->getType();
10277   if (LHSType->hasFloatingRepresentation() ||
10278       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10279       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10280       S.inTemplateInstantiation())
10281     return;
10282 
10283   // Comparisons between two array types are ill-formed for operator<=>, so
10284   // we shouldn't emit any additional warnings about it.
10285   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10286     return;
10287 
10288   // For non-floating point types, check for self-comparisons of the form
10289   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10290   // often indicate logic errors in the program.
10291   //
10292   // NOTE: Don't warn about comparison expressions resulting from macro
10293   // expansion. Also don't warn about comparisons which are only self
10294   // comparisons within a template instantiation. The warnings should catch
10295   // obvious cases in the definition of the template anyways. The idea is to
10296   // warn when the typed comparison operator will always evaluate to the same
10297   // result.
10298 
10299   // Used for indexing into %select in warn_comparison_always
10300   enum {
10301     AlwaysConstant,
10302     AlwaysTrue,
10303     AlwaysFalse,
10304     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10305   };
10306 
10307   if (Expr::isSameComparisonOperand(LHS, RHS)) {
10308     unsigned Result;
10309     switch (Opc) {
10310     case BO_EQ: case BO_LE: case BO_GE:
10311       Result = AlwaysTrue;
10312       break;
10313     case BO_NE: case BO_LT: case BO_GT:
10314       Result = AlwaysFalse;
10315       break;
10316     case BO_Cmp:
10317       Result = AlwaysEqual;
10318       break;
10319     default:
10320       Result = AlwaysConstant;
10321       break;
10322     }
10323     S.DiagRuntimeBehavior(Loc, nullptr,
10324                           S.PDiag(diag::warn_comparison_always)
10325                               << 0 /*self-comparison*/
10326                               << Result);
10327   } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10328     // What is it always going to evaluate to?
10329     unsigned Result;
10330     switch(Opc) {
10331     case BO_EQ: // e.g. array1 == array2
10332       Result = AlwaysFalse;
10333       break;
10334     case BO_NE: // e.g. array1 != array2
10335       Result = AlwaysTrue;
10336       break;
10337     default: // e.g. array1 <= array2
10338       // The best we can say is 'a constant'
10339       Result = AlwaysConstant;
10340       break;
10341     }
10342     S.DiagRuntimeBehavior(Loc, nullptr,
10343                           S.PDiag(diag::warn_comparison_always)
10344                               << 1 /*array comparison*/
10345                               << Result);
10346   }
10347 
10348   if (isa<CastExpr>(LHSStripped))
10349     LHSStripped = LHSStripped->IgnoreParenCasts();
10350   if (isa<CastExpr>(RHSStripped))
10351     RHSStripped = RHSStripped->IgnoreParenCasts();
10352 
10353   // Warn about comparisons against a string constant (unless the other
10354   // operand is null); the user probably wants strcmp.
10355   Expr *LiteralString = nullptr;
10356   Expr *LiteralStringStripped = nullptr;
10357   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10358       !RHSStripped->isNullPointerConstant(S.Context,
10359                                           Expr::NPC_ValueDependentIsNull)) {
10360     LiteralString = LHS;
10361     LiteralStringStripped = LHSStripped;
10362   } else if ((isa<StringLiteral>(RHSStripped) ||
10363               isa<ObjCEncodeExpr>(RHSStripped)) &&
10364              !LHSStripped->isNullPointerConstant(S.Context,
10365                                           Expr::NPC_ValueDependentIsNull)) {
10366     LiteralString = RHS;
10367     LiteralStringStripped = RHSStripped;
10368   }
10369 
10370   if (LiteralString) {
10371     S.DiagRuntimeBehavior(Loc, nullptr,
10372                           S.PDiag(diag::warn_stringcompare)
10373                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10374                               << LiteralString->getSourceRange());
10375   }
10376 }
10377 
10378 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10379   switch (CK) {
10380   default: {
10381 #ifndef NDEBUG
10382     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10383                  << "\n";
10384 #endif
10385     llvm_unreachable("unhandled cast kind");
10386   }
10387   case CK_UserDefinedConversion:
10388     return ICK_Identity;
10389   case CK_LValueToRValue:
10390     return ICK_Lvalue_To_Rvalue;
10391   case CK_ArrayToPointerDecay:
10392     return ICK_Array_To_Pointer;
10393   case CK_FunctionToPointerDecay:
10394     return ICK_Function_To_Pointer;
10395   case CK_IntegralCast:
10396     return ICK_Integral_Conversion;
10397   case CK_FloatingCast:
10398     return ICK_Floating_Conversion;
10399   case CK_IntegralToFloating:
10400   case CK_FloatingToIntegral:
10401     return ICK_Floating_Integral;
10402   case CK_IntegralComplexCast:
10403   case CK_FloatingComplexCast:
10404   case CK_FloatingComplexToIntegralComplex:
10405   case CK_IntegralComplexToFloatingComplex:
10406     return ICK_Complex_Conversion;
10407   case CK_FloatingComplexToReal:
10408   case CK_FloatingRealToComplex:
10409   case CK_IntegralComplexToReal:
10410   case CK_IntegralRealToComplex:
10411     return ICK_Complex_Real;
10412   }
10413 }
10414 
10415 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10416                                              QualType FromType,
10417                                              SourceLocation Loc) {
10418   // Check for a narrowing implicit conversion.
10419   StandardConversionSequence SCS;
10420   SCS.setAsIdentityConversion();
10421   SCS.setToType(0, FromType);
10422   SCS.setToType(1, ToType);
10423   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10424     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10425 
10426   APValue PreNarrowingValue;
10427   QualType PreNarrowingType;
10428   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10429                                PreNarrowingType,
10430                                /*IgnoreFloatToIntegralConversion*/ true)) {
10431   case NK_Dependent_Narrowing:
10432     // Implicit conversion to a narrower type, but the expression is
10433     // value-dependent so we can't tell whether it's actually narrowing.
10434   case NK_Not_Narrowing:
10435     return false;
10436 
10437   case NK_Constant_Narrowing:
10438     // Implicit conversion to a narrower type, and the value is not a constant
10439     // expression.
10440     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10441         << /*Constant*/ 1
10442         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10443     return true;
10444 
10445   case NK_Variable_Narrowing:
10446     // Implicit conversion to a narrower type, and the value is not a constant
10447     // expression.
10448   case NK_Type_Narrowing:
10449     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10450         << /*Constant*/ 0 << FromType << ToType;
10451     // TODO: It's not a constant expression, but what if the user intended it
10452     // to be? Can we produce notes to help them figure out why it isn't?
10453     return true;
10454   }
10455   llvm_unreachable("unhandled case in switch");
10456 }
10457 
10458 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10459                                                          ExprResult &LHS,
10460                                                          ExprResult &RHS,
10461                                                          SourceLocation Loc) {
10462   using CCT = ComparisonCategoryType;
10463 
10464   QualType LHSType = LHS.get()->getType();
10465   QualType RHSType = RHS.get()->getType();
10466   // Dig out the original argument type and expression before implicit casts
10467   // were applied. These are the types/expressions we need to check the
10468   // [expr.spaceship] requirements against.
10469   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10470   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10471   QualType LHSStrippedType = LHSStripped.get()->getType();
10472   QualType RHSStrippedType = RHSStripped.get()->getType();
10473 
10474   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10475   // other is not, the program is ill-formed.
10476   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10477     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10478     return QualType();
10479   }
10480 
10481   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10482                     RHSStrippedType->isEnumeralType();
10483   if (NumEnumArgs == 1) {
10484     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10485     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10486     if (OtherTy->hasFloatingRepresentation()) {
10487       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10488       return QualType();
10489     }
10490   }
10491   if (NumEnumArgs == 2) {
10492     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10493     // type E, the operator yields the result of converting the operands
10494     // to the underlying type of E and applying <=> to the converted operands.
10495     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10496       S.InvalidOperands(Loc, LHS, RHS);
10497       return QualType();
10498     }
10499     QualType IntType =
10500         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10501     assert(IntType->isArithmeticType());
10502 
10503     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10504     // promote the boolean type, and all other promotable integer types, to
10505     // avoid this.
10506     if (IntType->isPromotableIntegerType())
10507       IntType = S.Context.getPromotedIntegerType(IntType);
10508 
10509     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10510     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10511     LHSType = RHSType = IntType;
10512   }
10513 
10514   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10515   // usual arithmetic conversions are applied to the operands.
10516   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10517   if (LHS.isInvalid() || RHS.isInvalid())
10518     return QualType();
10519   if (Type.isNull())
10520     return S.InvalidOperands(Loc, LHS, RHS);
10521   assert(Type->isArithmeticType() || Type->isEnumeralType());
10522 
10523   bool HasNarrowing = checkThreeWayNarrowingConversion(
10524       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10525   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10526                                                    RHS.get()->getBeginLoc());
10527   if (HasNarrowing)
10528     return QualType();
10529 
10530   assert(!Type.isNull() && "composite type for <=> has not been set");
10531 
10532   auto TypeKind = [&]() {
10533     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10534       if (CT->getElementType()->hasFloatingRepresentation())
10535         return CCT::WeakEquality;
10536       return CCT::StrongEquality;
10537     }
10538     if (Type->isIntegralOrEnumerationType())
10539       return CCT::StrongOrdering;
10540     if (Type->hasFloatingRepresentation())
10541       return CCT::PartialOrdering;
10542     llvm_unreachable("other types are unimplemented");
10543   }();
10544 
10545   return S.CheckComparisonCategoryType(TypeKind, Loc);
10546 }
10547 
10548 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10549                                                  ExprResult &RHS,
10550                                                  SourceLocation Loc,
10551                                                  BinaryOperatorKind Opc) {
10552   if (Opc == BO_Cmp)
10553     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10554 
10555   // C99 6.5.8p3 / C99 6.5.9p4
10556   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10557   if (LHS.isInvalid() || RHS.isInvalid())
10558     return QualType();
10559   if (Type.isNull())
10560     return S.InvalidOperands(Loc, LHS, RHS);
10561   assert(Type->isArithmeticType() || Type->isEnumeralType());
10562 
10563   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10564 
10565   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10566     return S.InvalidOperands(Loc, LHS, RHS);
10567 
10568   // Check for comparisons of floating point operands using != and ==.
10569   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10570     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10571 
10572   // The result of comparisons is 'bool' in C++, 'int' in C.
10573   return S.Context.getLogicalOperationType();
10574 }
10575 
10576 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10577   if (!NullE.get()->getType()->isAnyPointerType())
10578     return;
10579   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10580   if (!E.get()->getType()->isAnyPointerType() &&
10581       E.get()->isNullPointerConstant(Context,
10582                                      Expr::NPC_ValueDependentIsNotNull) ==
10583         Expr::NPCK_ZeroExpression) {
10584     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10585       if (CL->getValue() == 0)
10586         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10587             << NullValue
10588             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10589                                             NullValue ? "NULL" : "(void *)0");
10590     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10591         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10592         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10593         if (T == Context.CharTy)
10594           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10595               << NullValue
10596               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10597                                               NullValue ? "NULL" : "(void *)0");
10598       }
10599   }
10600 }
10601 
10602 // C99 6.5.8, C++ [expr.rel]
10603 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10604                                     SourceLocation Loc,
10605                                     BinaryOperatorKind Opc) {
10606   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10607   bool IsThreeWay = Opc == BO_Cmp;
10608   auto IsAnyPointerType = [](ExprResult E) {
10609     QualType Ty = E.get()->getType();
10610     return Ty->isPointerType() || Ty->isMemberPointerType();
10611   };
10612 
10613   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10614   // type, array-to-pointer, ..., conversions are performed on both operands to
10615   // bring them to their composite type.
10616   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10617   // any type-related checks.
10618   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10619     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10620     if (LHS.isInvalid())
10621       return QualType();
10622     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10623     if (RHS.isInvalid())
10624       return QualType();
10625   } else {
10626     LHS = DefaultLvalueConversion(LHS.get());
10627     if (LHS.isInvalid())
10628       return QualType();
10629     RHS = DefaultLvalueConversion(RHS.get());
10630     if (RHS.isInvalid())
10631       return QualType();
10632   }
10633 
10634   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10635   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10636     CheckPtrComparisonWithNullChar(LHS, RHS);
10637     CheckPtrComparisonWithNullChar(RHS, LHS);
10638   }
10639 
10640   // Handle vector comparisons separately.
10641   if (LHS.get()->getType()->isVectorType() ||
10642       RHS.get()->getType()->isVectorType())
10643     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10644 
10645   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10646   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10647 
10648   QualType LHSType = LHS.get()->getType();
10649   QualType RHSType = RHS.get()->getType();
10650   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10651       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10652     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10653 
10654   const Expr::NullPointerConstantKind LHSNullKind =
10655       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10656   const Expr::NullPointerConstantKind RHSNullKind =
10657       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10658   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10659   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10660 
10661   auto computeResultTy = [&]() {
10662     if (Opc != BO_Cmp)
10663       return Context.getLogicalOperationType();
10664     assert(getLangOpts().CPlusPlus);
10665     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10666 
10667     QualType CompositeTy = LHS.get()->getType();
10668     assert(!CompositeTy->isReferenceType());
10669 
10670     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10671       return CheckComparisonCategoryType(Kind, Loc);
10672     };
10673 
10674     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10675     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10676     // result is of type std::strong_equality
10677     if (CompositeTy->isFunctionPointerType() ||
10678         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10679       // FIXME: consider making the function pointer case produce
10680       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10681       // and direction polls
10682       return buildResultTy(ComparisonCategoryType::StrongEquality);
10683 
10684     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10685     // pointer type, p <=> q is of type std::strong_ordering.
10686     if (CompositeTy->isPointerType()) {
10687       // P0946R0: Comparisons between a null pointer constant and an object
10688       // pointer result in std::strong_equality
10689       if (LHSIsNull != RHSIsNull)
10690         return buildResultTy(ComparisonCategoryType::StrongEquality);
10691       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10692     }
10693     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10694     // TODO: Extend support for operator<=> to ObjC types.
10695     return InvalidOperands(Loc, LHS, RHS);
10696   };
10697 
10698 
10699   if (!IsRelational && LHSIsNull != RHSIsNull) {
10700     bool IsEquality = Opc == BO_EQ;
10701     if (RHSIsNull)
10702       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10703                                    RHS.get()->getSourceRange());
10704     else
10705       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10706                                    LHS.get()->getSourceRange());
10707   }
10708 
10709   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10710       (RHSType->isIntegerType() && !RHSIsNull)) {
10711     // Skip normal pointer conversion checks in this case; we have better
10712     // diagnostics for this below.
10713   } else if (getLangOpts().CPlusPlus) {
10714     // Equality comparison of a function pointer to a void pointer is invalid,
10715     // but we allow it as an extension.
10716     // FIXME: If we really want to allow this, should it be part of composite
10717     // pointer type computation so it works in conditionals too?
10718     if (!IsRelational &&
10719         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10720          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10721       // This is a gcc extension compatibility comparison.
10722       // In a SFINAE context, we treat this as a hard error to maintain
10723       // conformance with the C++ standard.
10724       diagnoseFunctionPointerToVoidComparison(
10725           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10726 
10727       if (isSFINAEContext())
10728         return QualType();
10729 
10730       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10731       return computeResultTy();
10732     }
10733 
10734     // C++ [expr.eq]p2:
10735     //   If at least one operand is a pointer [...] bring them to their
10736     //   composite pointer type.
10737     // C++ [expr.spaceship]p6
10738     //  If at least one of the operands is of pointer type, [...] bring them
10739     //  to their composite pointer type.
10740     // C++ [expr.rel]p2:
10741     //   If both operands are pointers, [...] bring them to their composite
10742     //   pointer type.
10743     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10744             (IsRelational ? 2 : 1) &&
10745         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10746                                          RHSType->isObjCObjectPointerType()))) {
10747       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10748         return QualType();
10749       return computeResultTy();
10750     }
10751   } else if (LHSType->isPointerType() &&
10752              RHSType->isPointerType()) { // C99 6.5.8p2
10753     // All of the following pointer-related warnings are GCC extensions, except
10754     // when handling null pointer constants.
10755     QualType LCanPointeeTy =
10756       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10757     QualType RCanPointeeTy =
10758       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10759 
10760     // C99 6.5.9p2 and C99 6.5.8p2
10761     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10762                                    RCanPointeeTy.getUnqualifiedType())) {
10763       // Valid unless a relational comparison of function pointers
10764       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10765         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10766           << LHSType << RHSType << LHS.get()->getSourceRange()
10767           << RHS.get()->getSourceRange();
10768       }
10769     } else if (!IsRelational &&
10770                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10771       // Valid unless comparison between non-null pointer and function pointer
10772       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10773           && !LHSIsNull && !RHSIsNull)
10774         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10775                                                 /*isError*/false);
10776     } else {
10777       // Invalid
10778       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10779     }
10780     if (LCanPointeeTy != RCanPointeeTy) {
10781       // Treat NULL constant as a special case in OpenCL.
10782       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10783         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10784         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10785           Diag(Loc,
10786                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10787               << LHSType << RHSType << 0 /* comparison */
10788               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10789         }
10790       }
10791       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10792       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10793       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10794                                                : CK_BitCast;
10795       if (LHSIsNull && !RHSIsNull)
10796         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10797       else
10798         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10799     }
10800     return computeResultTy();
10801   }
10802 
10803   if (getLangOpts().CPlusPlus) {
10804     // C++ [expr.eq]p4:
10805     //   Two operands of type std::nullptr_t or one operand of type
10806     //   std::nullptr_t and the other a null pointer constant compare equal.
10807     if (!IsRelational && LHSIsNull && RHSIsNull) {
10808       if (LHSType->isNullPtrType()) {
10809         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10810         return computeResultTy();
10811       }
10812       if (RHSType->isNullPtrType()) {
10813         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10814         return computeResultTy();
10815       }
10816     }
10817 
10818     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10819     // These aren't covered by the composite pointer type rules.
10820     if (!IsRelational && RHSType->isNullPtrType() &&
10821         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10822       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10823       return computeResultTy();
10824     }
10825     if (!IsRelational && LHSType->isNullPtrType() &&
10826         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10827       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10828       return computeResultTy();
10829     }
10830 
10831     if (IsRelational &&
10832         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10833          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10834       // HACK: Relational comparison of nullptr_t against a pointer type is
10835       // invalid per DR583, but we allow it within std::less<> and friends,
10836       // since otherwise common uses of it break.
10837       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10838       // friends to have std::nullptr_t overload candidates.
10839       DeclContext *DC = CurContext;
10840       if (isa<FunctionDecl>(DC))
10841         DC = DC->getParent();
10842       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10843         if (CTSD->isInStdNamespace() &&
10844             llvm::StringSwitch<bool>(CTSD->getName())
10845                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10846                 .Default(false)) {
10847           if (RHSType->isNullPtrType())
10848             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10849           else
10850             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10851           return computeResultTy();
10852         }
10853       }
10854     }
10855 
10856     // C++ [expr.eq]p2:
10857     //   If at least one operand is a pointer to member, [...] bring them to
10858     //   their composite pointer type.
10859     if (!IsRelational &&
10860         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10861       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10862         return QualType();
10863       else
10864         return computeResultTy();
10865     }
10866   }
10867 
10868   // Handle block pointer types.
10869   if (!IsRelational && LHSType->isBlockPointerType() &&
10870       RHSType->isBlockPointerType()) {
10871     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10872     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10873 
10874     if (!LHSIsNull && !RHSIsNull &&
10875         !Context.typesAreCompatible(lpointee, rpointee)) {
10876       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10877         << LHSType << RHSType << LHS.get()->getSourceRange()
10878         << RHS.get()->getSourceRange();
10879     }
10880     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10881     return computeResultTy();
10882   }
10883 
10884   // Allow block pointers to be compared with null pointer constants.
10885   if (!IsRelational
10886       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10887           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10888     if (!LHSIsNull && !RHSIsNull) {
10889       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10890              ->getPointeeType()->isVoidType())
10891             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10892                 ->getPointeeType()->isVoidType())))
10893         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10894           << LHSType << RHSType << LHS.get()->getSourceRange()
10895           << RHS.get()->getSourceRange();
10896     }
10897     if (LHSIsNull && !RHSIsNull)
10898       LHS = ImpCastExprToType(LHS.get(), RHSType,
10899                               RHSType->isPointerType() ? CK_BitCast
10900                                 : CK_AnyPointerToBlockPointerCast);
10901     else
10902       RHS = ImpCastExprToType(RHS.get(), LHSType,
10903                               LHSType->isPointerType() ? CK_BitCast
10904                                 : CK_AnyPointerToBlockPointerCast);
10905     return computeResultTy();
10906   }
10907 
10908   if (LHSType->isObjCObjectPointerType() ||
10909       RHSType->isObjCObjectPointerType()) {
10910     const PointerType *LPT = LHSType->getAs<PointerType>();
10911     const PointerType *RPT = RHSType->getAs<PointerType>();
10912     if (LPT || RPT) {
10913       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10914       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10915 
10916       if (!LPtrToVoid && !RPtrToVoid &&
10917           !Context.typesAreCompatible(LHSType, RHSType)) {
10918         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10919                                           /*isError*/false);
10920       }
10921       if (LHSIsNull && !RHSIsNull) {
10922         Expr *E = LHS.get();
10923         if (getLangOpts().ObjCAutoRefCount)
10924           CheckObjCConversion(SourceRange(), RHSType, E,
10925                               CCK_ImplicitConversion);
10926         LHS = ImpCastExprToType(E, RHSType,
10927                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10928       }
10929       else {
10930         Expr *E = RHS.get();
10931         if (getLangOpts().ObjCAutoRefCount)
10932           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10933                               /*Diagnose=*/true,
10934                               /*DiagnoseCFAudited=*/false, Opc);
10935         RHS = ImpCastExprToType(E, LHSType,
10936                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10937       }
10938       return computeResultTy();
10939     }
10940     if (LHSType->isObjCObjectPointerType() &&
10941         RHSType->isObjCObjectPointerType()) {
10942       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10943         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10944                                           /*isError*/false);
10945       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10946         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10947 
10948       if (LHSIsNull && !RHSIsNull)
10949         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10950       else
10951         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10952       return computeResultTy();
10953     }
10954 
10955     if (!IsRelational && LHSType->isBlockPointerType() &&
10956         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10957       LHS = ImpCastExprToType(LHS.get(), RHSType,
10958                               CK_BlockPointerToObjCPointerCast);
10959       return computeResultTy();
10960     } else if (!IsRelational &&
10961                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10962                RHSType->isBlockPointerType()) {
10963       RHS = ImpCastExprToType(RHS.get(), LHSType,
10964                               CK_BlockPointerToObjCPointerCast);
10965       return computeResultTy();
10966     }
10967   }
10968   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10969       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10970     unsigned DiagID = 0;
10971     bool isError = false;
10972     if (LangOpts.DebuggerSupport) {
10973       // Under a debugger, allow the comparison of pointers to integers,
10974       // since users tend to want to compare addresses.
10975     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10976                (RHSIsNull && RHSType->isIntegerType())) {
10977       if (IsRelational) {
10978         isError = getLangOpts().CPlusPlus;
10979         DiagID =
10980           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10981                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10982       }
10983     } else if (getLangOpts().CPlusPlus) {
10984       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10985       isError = true;
10986     } else if (IsRelational)
10987       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10988     else
10989       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10990 
10991     if (DiagID) {
10992       Diag(Loc, DiagID)
10993         << LHSType << RHSType << LHS.get()->getSourceRange()
10994         << RHS.get()->getSourceRange();
10995       if (isError)
10996         return QualType();
10997     }
10998 
10999     if (LHSType->isIntegerType())
11000       LHS = ImpCastExprToType(LHS.get(), RHSType,
11001                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11002     else
11003       RHS = ImpCastExprToType(RHS.get(), LHSType,
11004                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11005     return computeResultTy();
11006   }
11007 
11008   // Handle block pointers.
11009   if (!IsRelational && RHSIsNull
11010       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11011     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11012     return computeResultTy();
11013   }
11014   if (!IsRelational && LHSIsNull
11015       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11016     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11017     return computeResultTy();
11018   }
11019 
11020   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11021     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11022       return computeResultTy();
11023     }
11024 
11025     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11026       return computeResultTy();
11027     }
11028 
11029     if (LHSIsNull && RHSType->isQueueT()) {
11030       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11031       return computeResultTy();
11032     }
11033 
11034     if (LHSType->isQueueT() && RHSIsNull) {
11035       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11036       return computeResultTy();
11037     }
11038   }
11039 
11040   return InvalidOperands(Loc, LHS, RHS);
11041 }
11042 
11043 // Return a signed ext_vector_type that is of identical size and number of
11044 // elements. For floating point vectors, return an integer type of identical
11045 // size and number of elements. In the non ext_vector_type case, search from
11046 // the largest type to the smallest type to avoid cases where long long == long,
11047 // where long gets picked over long long.
11048 QualType Sema::GetSignedVectorType(QualType V) {
11049   const VectorType *VTy = V->castAs<VectorType>();
11050   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11051 
11052   if (isa<ExtVectorType>(VTy)) {
11053     if (TypeSize == Context.getTypeSize(Context.CharTy))
11054       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11055     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11056       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11057     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11058       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11059     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11060       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11061     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11062            "Unhandled vector element size in vector compare");
11063     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11064   }
11065 
11066   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11067     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11068                                  VectorType::GenericVector);
11069   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11070     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11071                                  VectorType::GenericVector);
11072   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11073     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11074                                  VectorType::GenericVector);
11075   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11076     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11077                                  VectorType::GenericVector);
11078   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11079          "Unhandled vector element size in vector compare");
11080   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11081                                VectorType::GenericVector);
11082 }
11083 
11084 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11085 /// operates on extended vector types.  Instead of producing an IntTy result,
11086 /// like a scalar comparison, a vector comparison produces a vector of integer
11087 /// types.
11088 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11089                                           SourceLocation Loc,
11090                                           BinaryOperatorKind Opc) {
11091   // Check to make sure we're operating on vectors of the same type and width,
11092   // Allowing one side to be a scalar of element type.
11093   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11094                               /*AllowBothBool*/true,
11095                               /*AllowBoolConversions*/getLangOpts().ZVector);
11096   if (vType.isNull())
11097     return vType;
11098 
11099   QualType LHSType = LHS.get()->getType();
11100 
11101   // If AltiVec, the comparison results in a numeric type, i.e.
11102   // bool for C++, int for C
11103   if (getLangOpts().AltiVec &&
11104       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11105     return Context.getLogicalOperationType();
11106 
11107   // For non-floating point types, check for self-comparisons of the form
11108   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11109   // often indicate logic errors in the program.
11110   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11111 
11112   // Check for comparisons of floating point operands using != and ==.
11113   if (BinaryOperator::isEqualityOp(Opc) &&
11114       LHSType->hasFloatingRepresentation()) {
11115     assert(RHS.get()->getType()->hasFloatingRepresentation());
11116     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11117   }
11118 
11119   // Return a signed type for the vector.
11120   return GetSignedVectorType(vType);
11121 }
11122 
11123 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11124                                     const ExprResult &XorRHS,
11125                                     const SourceLocation Loc) {
11126   // Do not diagnose macros.
11127   if (Loc.isMacroID())
11128     return;
11129 
11130   bool Negative = false;
11131   bool ExplicitPlus = false;
11132   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11133   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11134 
11135   if (!LHSInt)
11136     return;
11137   if (!RHSInt) {
11138     // Check negative literals.
11139     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11140       UnaryOperatorKind Opc = UO->getOpcode();
11141       if (Opc != UO_Minus && Opc != UO_Plus)
11142         return;
11143       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11144       if (!RHSInt)
11145         return;
11146       Negative = (Opc == UO_Minus);
11147       ExplicitPlus = !Negative;
11148     } else {
11149       return;
11150     }
11151   }
11152 
11153   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11154   llvm::APInt RightSideValue = RHSInt->getValue();
11155   if (LeftSideValue != 2 && LeftSideValue != 10)
11156     return;
11157 
11158   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11159     return;
11160 
11161   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11162       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11163   llvm::StringRef ExprStr =
11164       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11165 
11166   CharSourceRange XorRange =
11167       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11168   llvm::StringRef XorStr =
11169       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11170   // Do not diagnose if xor keyword/macro is used.
11171   if (XorStr == "xor")
11172     return;
11173 
11174   std::string LHSStr = Lexer::getSourceText(
11175       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11176       S.getSourceManager(), S.getLangOpts());
11177   std::string RHSStr = Lexer::getSourceText(
11178       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11179       S.getSourceManager(), S.getLangOpts());
11180 
11181   if (Negative) {
11182     RightSideValue = -RightSideValue;
11183     RHSStr = "-" + RHSStr;
11184   } else if (ExplicitPlus) {
11185     RHSStr = "+" + RHSStr;
11186   }
11187 
11188   StringRef LHSStrRef = LHSStr;
11189   StringRef RHSStrRef = RHSStr;
11190   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11191   // literals.
11192   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11193       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11194       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11195       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11196       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11197       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11198       LHSStrRef.find('\'') != StringRef::npos ||
11199       RHSStrRef.find('\'') != StringRef::npos)
11200     return;
11201 
11202   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11203   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11204   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11205   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11206     std::string SuggestedExpr = "1 << " + RHSStr;
11207     bool Overflow = false;
11208     llvm::APInt One = (LeftSideValue - 1);
11209     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11210     if (Overflow) {
11211       if (RightSideIntValue < 64)
11212         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11213             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11214             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11215       else if (RightSideIntValue == 64)
11216         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11217       else
11218         return;
11219     } else {
11220       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11221           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11222           << PowValue.toString(10, true)
11223           << FixItHint::CreateReplacement(
11224                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11225     }
11226 
11227     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11228   } else if (LeftSideValue == 10) {
11229     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11230     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11231         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11232         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11233     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11234   }
11235 }
11236 
11237 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11238                                           SourceLocation Loc) {
11239   // Ensure that either both operands are of the same vector type, or
11240   // one operand is of a vector type and the other is of its element type.
11241   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11242                                        /*AllowBothBool*/true,
11243                                        /*AllowBoolConversions*/false);
11244   if (vType.isNull())
11245     return InvalidOperands(Loc, LHS, RHS);
11246   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11247       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11248     return InvalidOperands(Loc, LHS, RHS);
11249   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11250   //        usage of the logical operators && and || with vectors in C. This
11251   //        check could be notionally dropped.
11252   if (!getLangOpts().CPlusPlus &&
11253       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11254     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11255 
11256   return GetSignedVectorType(LHS.get()->getType());
11257 }
11258 
11259 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11260                                            SourceLocation Loc,
11261                                            BinaryOperatorKind Opc) {
11262   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11263 
11264   bool IsCompAssign =
11265       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11266 
11267   if (LHS.get()->getType()->isVectorType() ||
11268       RHS.get()->getType()->isVectorType()) {
11269     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11270         RHS.get()->getType()->hasIntegerRepresentation())
11271       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11272                         /*AllowBothBool*/true,
11273                         /*AllowBoolConversions*/getLangOpts().ZVector);
11274     return InvalidOperands(Loc, LHS, RHS);
11275   }
11276 
11277   if (Opc == BO_And)
11278     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11279 
11280   ExprResult LHSResult = LHS, RHSResult = RHS;
11281   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
11282                                                  IsCompAssign);
11283   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11284     return QualType();
11285   LHS = LHSResult.get();
11286   RHS = RHSResult.get();
11287 
11288   if (Opc == BO_Xor)
11289     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11290 
11291   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11292     return compType;
11293   return InvalidOperands(Loc, LHS, RHS);
11294 }
11295 
11296 // C99 6.5.[13,14]
11297 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11298                                            SourceLocation Loc,
11299                                            BinaryOperatorKind Opc) {
11300   // Check vector operands differently.
11301   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11302     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11303 
11304   bool EnumConstantInBoolContext = false;
11305   for (const ExprResult &HS : {LHS, RHS}) {
11306     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11307       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11308       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11309         EnumConstantInBoolContext = true;
11310     }
11311   }
11312 
11313   if (EnumConstantInBoolContext)
11314     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11315 
11316   // Diagnose cases where the user write a logical and/or but probably meant a
11317   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11318   // is a constant.
11319   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11320       !LHS.get()->getType()->isBooleanType() &&
11321       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11322       // Don't warn in macros or template instantiations.
11323       !Loc.isMacroID() && !inTemplateInstantiation()) {
11324     // If the RHS can be constant folded, and if it constant folds to something
11325     // that isn't 0 or 1 (which indicate a potential logical operation that
11326     // happened to fold to true/false) then warn.
11327     // Parens on the RHS are ignored.
11328     Expr::EvalResult EVResult;
11329     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11330       llvm::APSInt Result = EVResult.Val.getInt();
11331       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11332            !RHS.get()->getExprLoc().isMacroID()) ||
11333           (Result != 0 && Result != 1)) {
11334         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11335           << RHS.get()->getSourceRange()
11336           << (Opc == BO_LAnd ? "&&" : "||");
11337         // Suggest replacing the logical operator with the bitwise version
11338         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11339             << (Opc == BO_LAnd ? "&" : "|")
11340             << FixItHint::CreateReplacement(SourceRange(
11341                                                  Loc, getLocForEndOfToken(Loc)),
11342                                             Opc == BO_LAnd ? "&" : "|");
11343         if (Opc == BO_LAnd)
11344           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11345           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11346               << FixItHint::CreateRemoval(
11347                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11348                                  RHS.get()->getEndLoc()));
11349       }
11350     }
11351   }
11352 
11353   if (!Context.getLangOpts().CPlusPlus) {
11354     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11355     // not operate on the built-in scalar and vector float types.
11356     if (Context.getLangOpts().OpenCL &&
11357         Context.getLangOpts().OpenCLVersion < 120) {
11358       if (LHS.get()->getType()->isFloatingType() ||
11359           RHS.get()->getType()->isFloatingType())
11360         return InvalidOperands(Loc, LHS, RHS);
11361     }
11362 
11363     LHS = UsualUnaryConversions(LHS.get());
11364     if (LHS.isInvalid())
11365       return QualType();
11366 
11367     RHS = UsualUnaryConversions(RHS.get());
11368     if (RHS.isInvalid())
11369       return QualType();
11370 
11371     if (!LHS.get()->getType()->isScalarType() ||
11372         !RHS.get()->getType()->isScalarType())
11373       return InvalidOperands(Loc, LHS, RHS);
11374 
11375     return Context.IntTy;
11376   }
11377 
11378   // The following is safe because we only use this method for
11379   // non-overloadable operands.
11380 
11381   // C++ [expr.log.and]p1
11382   // C++ [expr.log.or]p1
11383   // The operands are both contextually converted to type bool.
11384   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11385   if (LHSRes.isInvalid())
11386     return InvalidOperands(Loc, LHS, RHS);
11387   LHS = LHSRes;
11388 
11389   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11390   if (RHSRes.isInvalid())
11391     return InvalidOperands(Loc, LHS, RHS);
11392   RHS = RHSRes;
11393 
11394   // C++ [expr.log.and]p2
11395   // C++ [expr.log.or]p2
11396   // The result is a bool.
11397   return Context.BoolTy;
11398 }
11399 
11400 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11401   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11402   if (!ME) return false;
11403   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11404   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11405       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11406   if (!Base) return false;
11407   return Base->getMethodDecl() != nullptr;
11408 }
11409 
11410 /// Is the given expression (which must be 'const') a reference to a
11411 /// variable which was originally non-const, but which has become
11412 /// 'const' due to being captured within a block?
11413 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11414 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11415   assert(E->isLValue() && E->getType().isConstQualified());
11416   E = E->IgnoreParens();
11417 
11418   // Must be a reference to a declaration from an enclosing scope.
11419   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11420   if (!DRE) return NCCK_None;
11421   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11422 
11423   // The declaration must be a variable which is not declared 'const'.
11424   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11425   if (!var) return NCCK_None;
11426   if (var->getType().isConstQualified()) return NCCK_None;
11427   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11428 
11429   // Decide whether the first capture was for a block or a lambda.
11430   DeclContext *DC = S.CurContext, *Prev = nullptr;
11431   // Decide whether the first capture was for a block or a lambda.
11432   while (DC) {
11433     // For init-capture, it is possible that the variable belongs to the
11434     // template pattern of the current context.
11435     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11436       if (var->isInitCapture() &&
11437           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11438         break;
11439     if (DC == var->getDeclContext())
11440       break;
11441     Prev = DC;
11442     DC = DC->getParent();
11443   }
11444   // Unless we have an init-capture, we've gone one step too far.
11445   if (!var->isInitCapture())
11446     DC = Prev;
11447   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11448 }
11449 
11450 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11451   Ty = Ty.getNonReferenceType();
11452   if (IsDereference && Ty->isPointerType())
11453     Ty = Ty->getPointeeType();
11454   return !Ty.isConstQualified();
11455 }
11456 
11457 // Update err_typecheck_assign_const and note_typecheck_assign_const
11458 // when this enum is changed.
11459 enum {
11460   ConstFunction,
11461   ConstVariable,
11462   ConstMember,
11463   ConstMethod,
11464   NestedConstMember,
11465   ConstUnknown,  // Keep as last element
11466 };
11467 
11468 /// Emit the "read-only variable not assignable" error and print notes to give
11469 /// more information about why the variable is not assignable, such as pointing
11470 /// to the declaration of a const variable, showing that a method is const, or
11471 /// that the function is returning a const reference.
11472 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11473                                     SourceLocation Loc) {
11474   SourceRange ExprRange = E->getSourceRange();
11475 
11476   // Only emit one error on the first const found.  All other consts will emit
11477   // a note to the error.
11478   bool DiagnosticEmitted = false;
11479 
11480   // Track if the current expression is the result of a dereference, and if the
11481   // next checked expression is the result of a dereference.
11482   bool IsDereference = false;
11483   bool NextIsDereference = false;
11484 
11485   // Loop to process MemberExpr chains.
11486   while (true) {
11487     IsDereference = NextIsDereference;
11488 
11489     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11490     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11491       NextIsDereference = ME->isArrow();
11492       const ValueDecl *VD = ME->getMemberDecl();
11493       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11494         // Mutable fields can be modified even if the class is const.
11495         if (Field->isMutable()) {
11496           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11497           break;
11498         }
11499 
11500         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11501           if (!DiagnosticEmitted) {
11502             S.Diag(Loc, diag::err_typecheck_assign_const)
11503                 << ExprRange << ConstMember << false /*static*/ << Field
11504                 << Field->getType();
11505             DiagnosticEmitted = true;
11506           }
11507           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11508               << ConstMember << false /*static*/ << Field << Field->getType()
11509               << Field->getSourceRange();
11510         }
11511         E = ME->getBase();
11512         continue;
11513       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11514         if (VDecl->getType().isConstQualified()) {
11515           if (!DiagnosticEmitted) {
11516             S.Diag(Loc, diag::err_typecheck_assign_const)
11517                 << ExprRange << ConstMember << true /*static*/ << VDecl
11518                 << VDecl->getType();
11519             DiagnosticEmitted = true;
11520           }
11521           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11522               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11523               << VDecl->getSourceRange();
11524         }
11525         // Static fields do not inherit constness from parents.
11526         break;
11527       }
11528       break; // End MemberExpr
11529     } else if (const ArraySubscriptExpr *ASE =
11530                    dyn_cast<ArraySubscriptExpr>(E)) {
11531       E = ASE->getBase()->IgnoreParenImpCasts();
11532       continue;
11533     } else if (const ExtVectorElementExpr *EVE =
11534                    dyn_cast<ExtVectorElementExpr>(E)) {
11535       E = EVE->getBase()->IgnoreParenImpCasts();
11536       continue;
11537     }
11538     break;
11539   }
11540 
11541   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11542     // Function calls
11543     const FunctionDecl *FD = CE->getDirectCallee();
11544     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11545       if (!DiagnosticEmitted) {
11546         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11547                                                       << ConstFunction << FD;
11548         DiagnosticEmitted = true;
11549       }
11550       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11551              diag::note_typecheck_assign_const)
11552           << ConstFunction << FD << FD->getReturnType()
11553           << FD->getReturnTypeSourceRange();
11554     }
11555   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11556     // Point to variable declaration.
11557     if (const ValueDecl *VD = DRE->getDecl()) {
11558       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11559         if (!DiagnosticEmitted) {
11560           S.Diag(Loc, diag::err_typecheck_assign_const)
11561               << ExprRange << ConstVariable << VD << VD->getType();
11562           DiagnosticEmitted = true;
11563         }
11564         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11565             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11566       }
11567     }
11568   } else if (isa<CXXThisExpr>(E)) {
11569     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11570       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11571         if (MD->isConst()) {
11572           if (!DiagnosticEmitted) {
11573             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11574                                                           << ConstMethod << MD;
11575             DiagnosticEmitted = true;
11576           }
11577           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11578               << ConstMethod << MD << MD->getSourceRange();
11579         }
11580       }
11581     }
11582   }
11583 
11584   if (DiagnosticEmitted)
11585     return;
11586 
11587   // Can't determine a more specific message, so display the generic error.
11588   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11589 }
11590 
11591 enum OriginalExprKind {
11592   OEK_Variable,
11593   OEK_Member,
11594   OEK_LValue
11595 };
11596 
11597 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11598                                          const RecordType *Ty,
11599                                          SourceLocation Loc, SourceRange Range,
11600                                          OriginalExprKind OEK,
11601                                          bool &DiagnosticEmitted) {
11602   std::vector<const RecordType *> RecordTypeList;
11603   RecordTypeList.push_back(Ty);
11604   unsigned NextToCheckIndex = 0;
11605   // We walk the record hierarchy breadth-first to ensure that we print
11606   // diagnostics in field nesting order.
11607   while (RecordTypeList.size() > NextToCheckIndex) {
11608     bool IsNested = NextToCheckIndex > 0;
11609     for (const FieldDecl *Field :
11610          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11611       // First, check every field for constness.
11612       QualType FieldTy = Field->getType();
11613       if (FieldTy.isConstQualified()) {
11614         if (!DiagnosticEmitted) {
11615           S.Diag(Loc, diag::err_typecheck_assign_const)
11616               << Range << NestedConstMember << OEK << VD
11617               << IsNested << Field;
11618           DiagnosticEmitted = true;
11619         }
11620         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11621             << NestedConstMember << IsNested << Field
11622             << FieldTy << Field->getSourceRange();
11623       }
11624 
11625       // Then we append it to the list to check next in order.
11626       FieldTy = FieldTy.getCanonicalType();
11627       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11628         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11629           RecordTypeList.push_back(FieldRecTy);
11630       }
11631     }
11632     ++NextToCheckIndex;
11633   }
11634 }
11635 
11636 /// Emit an error for the case where a record we are trying to assign to has a
11637 /// const-qualified field somewhere in its hierarchy.
11638 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11639                                          SourceLocation Loc) {
11640   QualType Ty = E->getType();
11641   assert(Ty->isRecordType() && "lvalue was not record?");
11642   SourceRange Range = E->getSourceRange();
11643   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11644   bool DiagEmitted = false;
11645 
11646   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11647     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11648             Range, OEK_Member, DiagEmitted);
11649   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11650     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11651             Range, OEK_Variable, DiagEmitted);
11652   else
11653     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11654             Range, OEK_LValue, DiagEmitted);
11655   if (!DiagEmitted)
11656     DiagnoseConstAssignment(S, E, Loc);
11657 }
11658 
11659 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11660 /// emit an error and return true.  If so, return false.
11661 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11662   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11663 
11664   S.CheckShadowingDeclModification(E, Loc);
11665 
11666   SourceLocation OrigLoc = Loc;
11667   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11668                                                               &Loc);
11669   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11670     IsLV = Expr::MLV_InvalidMessageExpression;
11671   if (IsLV == Expr::MLV_Valid)
11672     return false;
11673 
11674   unsigned DiagID = 0;
11675   bool NeedType = false;
11676   switch (IsLV) { // C99 6.5.16p2
11677   case Expr::MLV_ConstQualified:
11678     // Use a specialized diagnostic when we're assigning to an object
11679     // from an enclosing function or block.
11680     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11681       if (NCCK == NCCK_Block)
11682         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11683       else
11684         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11685       break;
11686     }
11687 
11688     // In ARC, use some specialized diagnostics for occasions where we
11689     // infer 'const'.  These are always pseudo-strong variables.
11690     if (S.getLangOpts().ObjCAutoRefCount) {
11691       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11692       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11693         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11694 
11695         // Use the normal diagnostic if it's pseudo-__strong but the
11696         // user actually wrote 'const'.
11697         if (var->isARCPseudoStrong() &&
11698             (!var->getTypeSourceInfo() ||
11699              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11700           // There are three pseudo-strong cases:
11701           //  - self
11702           ObjCMethodDecl *method = S.getCurMethodDecl();
11703           if (method && var == method->getSelfDecl()) {
11704             DiagID = method->isClassMethod()
11705               ? diag::err_typecheck_arc_assign_self_class_method
11706               : diag::err_typecheck_arc_assign_self;
11707 
11708           //  - Objective-C externally_retained attribute.
11709           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11710                      isa<ParmVarDecl>(var)) {
11711             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11712 
11713           //  - fast enumeration variables
11714           } else {
11715             DiagID = diag::err_typecheck_arr_assign_enumeration;
11716           }
11717 
11718           SourceRange Assign;
11719           if (Loc != OrigLoc)
11720             Assign = SourceRange(OrigLoc, OrigLoc);
11721           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11722           // We need to preserve the AST regardless, so migration tool
11723           // can do its job.
11724           return false;
11725         }
11726       }
11727     }
11728 
11729     // If none of the special cases above are triggered, then this is a
11730     // simple const assignment.
11731     if (DiagID == 0) {
11732       DiagnoseConstAssignment(S, E, Loc);
11733       return true;
11734     }
11735 
11736     break;
11737   case Expr::MLV_ConstAddrSpace:
11738     DiagnoseConstAssignment(S, E, Loc);
11739     return true;
11740   case Expr::MLV_ConstQualifiedField:
11741     DiagnoseRecursiveConstFields(S, E, Loc);
11742     return true;
11743   case Expr::MLV_ArrayType:
11744   case Expr::MLV_ArrayTemporary:
11745     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11746     NeedType = true;
11747     break;
11748   case Expr::MLV_NotObjectType:
11749     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11750     NeedType = true;
11751     break;
11752   case Expr::MLV_LValueCast:
11753     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11754     break;
11755   case Expr::MLV_Valid:
11756     llvm_unreachable("did not take early return for MLV_Valid");
11757   case Expr::MLV_InvalidExpression:
11758   case Expr::MLV_MemberFunction:
11759   case Expr::MLV_ClassTemporary:
11760     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11761     break;
11762   case Expr::MLV_IncompleteType:
11763   case Expr::MLV_IncompleteVoidType:
11764     return S.RequireCompleteType(Loc, E->getType(),
11765              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11766   case Expr::MLV_DuplicateVectorComponents:
11767     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11768     break;
11769   case Expr::MLV_NoSetterProperty:
11770     llvm_unreachable("readonly properties should be processed differently");
11771   case Expr::MLV_InvalidMessageExpression:
11772     DiagID = diag::err_readonly_message_assignment;
11773     break;
11774   case Expr::MLV_SubObjCPropertySetting:
11775     DiagID = diag::err_no_subobject_property_setting;
11776     break;
11777   }
11778 
11779   SourceRange Assign;
11780   if (Loc != OrigLoc)
11781     Assign = SourceRange(OrigLoc, OrigLoc);
11782   if (NeedType)
11783     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11784   else
11785     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11786   return true;
11787 }
11788 
11789 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11790                                          SourceLocation Loc,
11791                                          Sema &Sema) {
11792   if (Sema.inTemplateInstantiation())
11793     return;
11794   if (Sema.isUnevaluatedContext())
11795     return;
11796   if (Loc.isInvalid() || Loc.isMacroID())
11797     return;
11798   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11799     return;
11800 
11801   // C / C++ fields
11802   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11803   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11804   if (ML && MR) {
11805     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11806       return;
11807     const ValueDecl *LHSDecl =
11808         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11809     const ValueDecl *RHSDecl =
11810         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11811     if (LHSDecl != RHSDecl)
11812       return;
11813     if (LHSDecl->getType().isVolatileQualified())
11814       return;
11815     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11816       if (RefTy->getPointeeType().isVolatileQualified())
11817         return;
11818 
11819     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11820   }
11821 
11822   // Objective-C instance variables
11823   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11824   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11825   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11826     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11827     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11828     if (RL && RR && RL->getDecl() == RR->getDecl())
11829       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11830   }
11831 }
11832 
11833 // C99 6.5.16.1
11834 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11835                                        SourceLocation Loc,
11836                                        QualType CompoundType) {
11837   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11838 
11839   // Verify that LHS is a modifiable lvalue, and emit error if not.
11840   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11841     return QualType();
11842 
11843   QualType LHSType = LHSExpr->getType();
11844   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11845                                              CompoundType;
11846   // OpenCL v1.2 s6.1.1.1 p2:
11847   // The half data type can only be used to declare a pointer to a buffer that
11848   // contains half values
11849   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11850     LHSType->isHalfType()) {
11851     Diag(Loc, diag::err_opencl_half_load_store) << 1
11852         << LHSType.getUnqualifiedType();
11853     return QualType();
11854   }
11855 
11856   AssignConvertType ConvTy;
11857   if (CompoundType.isNull()) {
11858     Expr *RHSCheck = RHS.get();
11859 
11860     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11861 
11862     QualType LHSTy(LHSType);
11863     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11864     if (RHS.isInvalid())
11865       return QualType();
11866     // Special case of NSObject attributes on c-style pointer types.
11867     if (ConvTy == IncompatiblePointer &&
11868         ((Context.isObjCNSObjectType(LHSType) &&
11869           RHSType->isObjCObjectPointerType()) ||
11870          (Context.isObjCNSObjectType(RHSType) &&
11871           LHSType->isObjCObjectPointerType())))
11872       ConvTy = Compatible;
11873 
11874     if (ConvTy == Compatible &&
11875         LHSType->isObjCObjectType())
11876         Diag(Loc, diag::err_objc_object_assignment)
11877           << LHSType;
11878 
11879     // If the RHS is a unary plus or minus, check to see if they = and + are
11880     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11881     // instead of "x += 4".
11882     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11883       RHSCheck = ICE->getSubExpr();
11884     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11885       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11886           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11887           // Only if the two operators are exactly adjacent.
11888           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11889           // And there is a space or other character before the subexpr of the
11890           // unary +/-.  We don't want to warn on "x=-1".
11891           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11892           UO->getSubExpr()->getBeginLoc().isFileID()) {
11893         Diag(Loc, diag::warn_not_compound_assign)
11894           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11895           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11896       }
11897     }
11898 
11899     if (ConvTy == Compatible) {
11900       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11901         // Warn about retain cycles where a block captures the LHS, but
11902         // not if the LHS is a simple variable into which the block is
11903         // being stored...unless that variable can be captured by reference!
11904         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11905         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11906         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11907           checkRetainCycles(LHSExpr, RHS.get());
11908       }
11909 
11910       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11911           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11912         // It is safe to assign a weak reference into a strong variable.
11913         // Although this code can still have problems:
11914         //   id x = self.weakProp;
11915         //   id y = self.weakProp;
11916         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11917         // paths through the function. This should be revisited if
11918         // -Wrepeated-use-of-weak is made flow-sensitive.
11919         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11920         // variable, which will be valid for the current autorelease scope.
11921         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11922                              RHS.get()->getBeginLoc()))
11923           getCurFunction()->markSafeWeakUse(RHS.get());
11924 
11925       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11926         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11927       }
11928     }
11929   } else {
11930     // Compound assignment "x += y"
11931     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11932   }
11933 
11934   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11935                                RHS.get(), AA_Assigning))
11936     return QualType();
11937 
11938   CheckForNullPointerDereference(*this, LHSExpr);
11939 
11940   // C99 6.5.16p3: The type of an assignment expression is the type of the
11941   // left operand unless the left operand has qualified type, in which case
11942   // it is the unqualified version of the type of the left operand.
11943   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11944   // is converted to the type of the assignment expression (above).
11945   // C++ 5.17p1: the type of the assignment expression is that of its left
11946   // operand.
11947   return (getLangOpts().CPlusPlus
11948           ? LHSType : LHSType.getUnqualifiedType());
11949 }
11950 
11951 // Only ignore explicit casts to void.
11952 static bool IgnoreCommaOperand(const Expr *E) {
11953   E = E->IgnoreParens();
11954 
11955   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11956     if (CE->getCastKind() == CK_ToVoid) {
11957       return true;
11958     }
11959 
11960     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11961     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11962         CE->getSubExpr()->getType()->isDependentType()) {
11963       return true;
11964     }
11965   }
11966 
11967   return false;
11968 }
11969 
11970 // Look for instances where it is likely the comma operator is confused with
11971 // another operator.  There is a whitelist of acceptable expressions for the
11972 // left hand side of the comma operator, otherwise emit a warning.
11973 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11974   // No warnings in macros
11975   if (Loc.isMacroID())
11976     return;
11977 
11978   // Don't warn in template instantiations.
11979   if (inTemplateInstantiation())
11980     return;
11981 
11982   // Scope isn't fine-grained enough to whitelist the specific cases, so
11983   // instead, skip more than needed, then call back into here with the
11984   // CommaVisitor in SemaStmt.cpp.
11985   // The whitelisted locations are the initialization and increment portions
11986   // of a for loop.  The additional checks are on the condition of
11987   // if statements, do/while loops, and for loops.
11988   // Differences in scope flags for C89 mode requires the extra logic.
11989   const unsigned ForIncrementFlags =
11990       getLangOpts().C99 || getLangOpts().CPlusPlus
11991           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11992           : Scope::ContinueScope | Scope::BreakScope;
11993   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11994   const unsigned ScopeFlags = getCurScope()->getFlags();
11995   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11996       (ScopeFlags & ForInitFlags) == ForInitFlags)
11997     return;
11998 
11999   // If there are multiple comma operators used together, get the RHS of the
12000   // of the comma operator as the LHS.
12001   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12002     if (BO->getOpcode() != BO_Comma)
12003       break;
12004     LHS = BO->getRHS();
12005   }
12006 
12007   // Only allow some expressions on LHS to not warn.
12008   if (IgnoreCommaOperand(LHS))
12009     return;
12010 
12011   Diag(Loc, diag::warn_comma_operator);
12012   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12013       << LHS->getSourceRange()
12014       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12015                                     LangOpts.CPlusPlus ? "static_cast<void>("
12016                                                        : "(void)(")
12017       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12018                                     ")");
12019 }
12020 
12021 // C99 6.5.17
12022 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12023                                    SourceLocation Loc) {
12024   LHS = S.CheckPlaceholderExpr(LHS.get());
12025   RHS = S.CheckPlaceholderExpr(RHS.get());
12026   if (LHS.isInvalid() || RHS.isInvalid())
12027     return QualType();
12028 
12029   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12030   // operands, but not unary promotions.
12031   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12032 
12033   // So we treat the LHS as a ignored value, and in C++ we allow the
12034   // containing site to determine what should be done with the RHS.
12035   LHS = S.IgnoredValueConversions(LHS.get());
12036   if (LHS.isInvalid())
12037     return QualType();
12038 
12039   S.DiagnoseUnusedExprResult(LHS.get());
12040 
12041   if (!S.getLangOpts().CPlusPlus) {
12042     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12043     if (RHS.isInvalid())
12044       return QualType();
12045     if (!RHS.get()->getType()->isVoidType())
12046       S.RequireCompleteType(Loc, RHS.get()->getType(),
12047                             diag::err_incomplete_type);
12048   }
12049 
12050   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12051     S.DiagnoseCommaOperator(LHS.get(), Loc);
12052 
12053   return RHS.get()->getType();
12054 }
12055 
12056 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12057 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12058 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12059                                                ExprValueKind &VK,
12060                                                ExprObjectKind &OK,
12061                                                SourceLocation OpLoc,
12062                                                bool IsInc, bool IsPrefix) {
12063   if (Op->isTypeDependent())
12064     return S.Context.DependentTy;
12065 
12066   QualType ResType = Op->getType();
12067   // Atomic types can be used for increment / decrement where the non-atomic
12068   // versions can, so ignore the _Atomic() specifier for the purpose of
12069   // checking.
12070   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12071     ResType = ResAtomicType->getValueType();
12072 
12073   assert(!ResType.isNull() && "no type for increment/decrement expression");
12074 
12075   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12076     // Decrement of bool is not allowed.
12077     if (!IsInc) {
12078       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12079       return QualType();
12080     }
12081     // Increment of bool sets it to true, but is deprecated.
12082     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12083                                               : diag::warn_increment_bool)
12084       << Op->getSourceRange();
12085   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12086     // Error on enum increments and decrements in C++ mode
12087     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12088     return QualType();
12089   } else if (ResType->isRealType()) {
12090     // OK!
12091   } else if (ResType->isPointerType()) {
12092     // C99 6.5.2.4p2, 6.5.6p2
12093     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12094       return QualType();
12095   } else if (ResType->isObjCObjectPointerType()) {
12096     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12097     // Otherwise, we just need a complete type.
12098     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12099         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12100       return QualType();
12101   } else if (ResType->isAnyComplexType()) {
12102     // C99 does not support ++/-- on complex types, we allow as an extension.
12103     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12104       << ResType << Op->getSourceRange();
12105   } else if (ResType->isPlaceholderType()) {
12106     ExprResult PR = S.CheckPlaceholderExpr(Op);
12107     if (PR.isInvalid()) return QualType();
12108     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12109                                           IsInc, IsPrefix);
12110   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12111     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12112   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12113              (ResType->castAs<VectorType>()->getVectorKind() !=
12114               VectorType::AltiVecBool)) {
12115     // The z vector extensions allow ++ and -- for non-bool vectors.
12116   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12117             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12118     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12119   } else {
12120     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12121       << ResType << int(IsInc) << Op->getSourceRange();
12122     return QualType();
12123   }
12124   // At this point, we know we have a real, complex or pointer type.
12125   // Now make sure the operand is a modifiable lvalue.
12126   if (CheckForModifiableLvalue(Op, OpLoc, S))
12127     return QualType();
12128   // In C++, a prefix increment is the same type as the operand. Otherwise
12129   // (in C or with postfix), the increment is the unqualified type of the
12130   // operand.
12131   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12132     VK = VK_LValue;
12133     OK = Op->getObjectKind();
12134     return ResType;
12135   } else {
12136     VK = VK_RValue;
12137     return ResType.getUnqualifiedType();
12138   }
12139 }
12140 
12141 
12142 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12143 /// This routine allows us to typecheck complex/recursive expressions
12144 /// where the declaration is needed for type checking. We only need to
12145 /// handle cases when the expression references a function designator
12146 /// or is an lvalue. Here are some examples:
12147 ///  - &(x) => x
12148 ///  - &*****f => f for f a function designator.
12149 ///  - &s.xx => s
12150 ///  - &s.zz[1].yy -> s, if zz is an array
12151 ///  - *(x + 1) -> x, if x is an array
12152 ///  - &"123"[2] -> 0
12153 ///  - & __real__ x -> x
12154 static ValueDecl *getPrimaryDecl(Expr *E) {
12155   switch (E->getStmtClass()) {
12156   case Stmt::DeclRefExprClass:
12157     return cast<DeclRefExpr>(E)->getDecl();
12158   case Stmt::MemberExprClass:
12159     // If this is an arrow operator, the address is an offset from
12160     // the base's value, so the object the base refers to is
12161     // irrelevant.
12162     if (cast<MemberExpr>(E)->isArrow())
12163       return nullptr;
12164     // Otherwise, the expression refers to a part of the base
12165     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12166   case Stmt::ArraySubscriptExprClass: {
12167     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12168     // promotion of register arrays earlier.
12169     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12170     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12171       if (ICE->getSubExpr()->getType()->isArrayType())
12172         return getPrimaryDecl(ICE->getSubExpr());
12173     }
12174     return nullptr;
12175   }
12176   case Stmt::UnaryOperatorClass: {
12177     UnaryOperator *UO = cast<UnaryOperator>(E);
12178 
12179     switch(UO->getOpcode()) {
12180     case UO_Real:
12181     case UO_Imag:
12182     case UO_Extension:
12183       return getPrimaryDecl(UO->getSubExpr());
12184     default:
12185       return nullptr;
12186     }
12187   }
12188   case Stmt::ParenExprClass:
12189     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12190   case Stmt::ImplicitCastExprClass:
12191     // If the result of an implicit cast is an l-value, we care about
12192     // the sub-expression; otherwise, the result here doesn't matter.
12193     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12194   default:
12195     return nullptr;
12196   }
12197 }
12198 
12199 namespace {
12200   enum {
12201     AO_Bit_Field = 0,
12202     AO_Vector_Element = 1,
12203     AO_Property_Expansion = 2,
12204     AO_Register_Variable = 3,
12205     AO_No_Error = 4
12206   };
12207 }
12208 /// Diagnose invalid operand for address of operations.
12209 ///
12210 /// \param Type The type of operand which cannot have its address taken.
12211 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12212                                          Expr *E, unsigned Type) {
12213   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12214 }
12215 
12216 /// CheckAddressOfOperand - The operand of & must be either a function
12217 /// designator or an lvalue designating an object. If it is an lvalue, the
12218 /// object cannot be declared with storage class register or be a bit field.
12219 /// Note: The usual conversions are *not* applied to the operand of the &
12220 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12221 /// In C++, the operand might be an overloaded function name, in which case
12222 /// we allow the '&' but retain the overloaded-function type.
12223 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12224   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12225     if (PTy->getKind() == BuiltinType::Overload) {
12226       Expr *E = OrigOp.get()->IgnoreParens();
12227       if (!isa<OverloadExpr>(E)) {
12228         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12229         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12230           << OrigOp.get()->getSourceRange();
12231         return QualType();
12232       }
12233 
12234       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12235       if (isa<UnresolvedMemberExpr>(Ovl))
12236         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12237           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12238             << OrigOp.get()->getSourceRange();
12239           return QualType();
12240         }
12241 
12242       return Context.OverloadTy;
12243     }
12244 
12245     if (PTy->getKind() == BuiltinType::UnknownAny)
12246       return Context.UnknownAnyTy;
12247 
12248     if (PTy->getKind() == BuiltinType::BoundMember) {
12249       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12250         << OrigOp.get()->getSourceRange();
12251       return QualType();
12252     }
12253 
12254     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12255     if (OrigOp.isInvalid()) return QualType();
12256   }
12257 
12258   if (OrigOp.get()->isTypeDependent())
12259     return Context.DependentTy;
12260 
12261   assert(!OrigOp.get()->getType()->isPlaceholderType());
12262 
12263   // Make sure to ignore parentheses in subsequent checks
12264   Expr *op = OrigOp.get()->IgnoreParens();
12265 
12266   // In OpenCL captures for blocks called as lambda functions
12267   // are located in the private address space. Blocks used in
12268   // enqueue_kernel can be located in a different address space
12269   // depending on a vendor implementation. Thus preventing
12270   // taking an address of the capture to avoid invalid AS casts.
12271   if (LangOpts.OpenCL) {
12272     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12273     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12274       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12275       return QualType();
12276     }
12277   }
12278 
12279   if (getLangOpts().C99) {
12280     // Implement C99-only parts of addressof rules.
12281     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12282       if (uOp->getOpcode() == UO_Deref)
12283         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12284         // (assuming the deref expression is valid).
12285         return uOp->getSubExpr()->getType();
12286     }
12287     // Technically, there should be a check for array subscript
12288     // expressions here, but the result of one is always an lvalue anyway.
12289   }
12290   ValueDecl *dcl = getPrimaryDecl(op);
12291 
12292   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12293     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12294                                            op->getBeginLoc()))
12295       return QualType();
12296 
12297   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12298   unsigned AddressOfError = AO_No_Error;
12299 
12300   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12301     bool sfinae = (bool)isSFINAEContext();
12302     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12303                                   : diag::ext_typecheck_addrof_temporary)
12304       << op->getType() << op->getSourceRange();
12305     if (sfinae)
12306       return QualType();
12307     // Materialize the temporary as an lvalue so that we can take its address.
12308     OrigOp = op =
12309         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12310   } else if (isa<ObjCSelectorExpr>(op)) {
12311     return Context.getPointerType(op->getType());
12312   } else if (lval == Expr::LV_MemberFunction) {
12313     // If it's an instance method, make a member pointer.
12314     // The expression must have exactly the form &A::foo.
12315 
12316     // If the underlying expression isn't a decl ref, give up.
12317     if (!isa<DeclRefExpr>(op)) {
12318       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12319         << OrigOp.get()->getSourceRange();
12320       return QualType();
12321     }
12322     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12323     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12324 
12325     // The id-expression was parenthesized.
12326     if (OrigOp.get() != DRE) {
12327       Diag(OpLoc, diag::err_parens_pointer_member_function)
12328         << OrigOp.get()->getSourceRange();
12329 
12330     // The method was named without a qualifier.
12331     } else if (!DRE->getQualifier()) {
12332       if (MD->getParent()->getName().empty())
12333         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12334           << op->getSourceRange();
12335       else {
12336         SmallString<32> Str;
12337         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12338         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12339           << op->getSourceRange()
12340           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12341       }
12342     }
12343 
12344     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12345     if (isa<CXXDestructorDecl>(MD))
12346       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12347 
12348     QualType MPTy = Context.getMemberPointerType(
12349         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12350     // Under the MS ABI, lock down the inheritance model now.
12351     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12352       (void)isCompleteType(OpLoc, MPTy);
12353     return MPTy;
12354   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12355     // C99 6.5.3.2p1
12356     // The operand must be either an l-value or a function designator
12357     if (!op->getType()->isFunctionType()) {
12358       // Use a special diagnostic for loads from property references.
12359       if (isa<PseudoObjectExpr>(op)) {
12360         AddressOfError = AO_Property_Expansion;
12361       } else {
12362         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12363           << op->getType() << op->getSourceRange();
12364         return QualType();
12365       }
12366     }
12367   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12368     // The operand cannot be a bit-field
12369     AddressOfError = AO_Bit_Field;
12370   } else if (op->getObjectKind() == OK_VectorComponent) {
12371     // The operand cannot be an element of a vector
12372     AddressOfError = AO_Vector_Element;
12373   } else if (dcl) { // C99 6.5.3.2p1
12374     // We have an lvalue with a decl. Make sure the decl is not declared
12375     // with the register storage-class specifier.
12376     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12377       // in C++ it is not error to take address of a register
12378       // variable (c++03 7.1.1P3)
12379       if (vd->getStorageClass() == SC_Register &&
12380           !getLangOpts().CPlusPlus) {
12381         AddressOfError = AO_Register_Variable;
12382       }
12383     } else if (isa<MSPropertyDecl>(dcl)) {
12384       AddressOfError = AO_Property_Expansion;
12385     } else if (isa<FunctionTemplateDecl>(dcl)) {
12386       return Context.OverloadTy;
12387     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12388       // Okay: we can take the address of a field.
12389       // Could be a pointer to member, though, if there is an explicit
12390       // scope qualifier for the class.
12391       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12392         DeclContext *Ctx = dcl->getDeclContext();
12393         if (Ctx && Ctx->isRecord()) {
12394           if (dcl->getType()->isReferenceType()) {
12395             Diag(OpLoc,
12396                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12397               << dcl->getDeclName() << dcl->getType();
12398             return QualType();
12399           }
12400 
12401           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12402             Ctx = Ctx->getParent();
12403 
12404           QualType MPTy = Context.getMemberPointerType(
12405               op->getType(),
12406               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12407           // Under the MS ABI, lock down the inheritance model now.
12408           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12409             (void)isCompleteType(OpLoc, MPTy);
12410           return MPTy;
12411         }
12412       }
12413     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12414                !isa<BindingDecl>(dcl))
12415       llvm_unreachable("Unknown/unexpected decl type");
12416   }
12417 
12418   if (AddressOfError != AO_No_Error) {
12419     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12420     return QualType();
12421   }
12422 
12423   if (lval == Expr::LV_IncompleteVoidType) {
12424     // Taking the address of a void variable is technically illegal, but we
12425     // allow it in cases which are otherwise valid.
12426     // Example: "extern void x; void* y = &x;".
12427     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12428   }
12429 
12430   // If the operand has type "type", the result has type "pointer to type".
12431   if (op->getType()->isObjCObjectType())
12432     return Context.getObjCObjectPointerType(op->getType());
12433 
12434   CheckAddressOfPackedMember(op);
12435 
12436   return Context.getPointerType(op->getType());
12437 }
12438 
12439 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12440   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12441   if (!DRE)
12442     return;
12443   const Decl *D = DRE->getDecl();
12444   if (!D)
12445     return;
12446   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12447   if (!Param)
12448     return;
12449   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12450     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12451       return;
12452   if (FunctionScopeInfo *FD = S.getCurFunction())
12453     if (!FD->ModifiedNonNullParams.count(Param))
12454       FD->ModifiedNonNullParams.insert(Param);
12455 }
12456 
12457 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12458 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12459                                         SourceLocation OpLoc) {
12460   if (Op->isTypeDependent())
12461     return S.Context.DependentTy;
12462 
12463   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12464   if (ConvResult.isInvalid())
12465     return QualType();
12466   Op = ConvResult.get();
12467   QualType OpTy = Op->getType();
12468   QualType Result;
12469 
12470   if (isa<CXXReinterpretCastExpr>(Op)) {
12471     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12472     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12473                                      Op->getSourceRange());
12474   }
12475 
12476   if (const PointerType *PT = OpTy->getAs<PointerType>())
12477   {
12478     Result = PT->getPointeeType();
12479   }
12480   else if (const ObjCObjectPointerType *OPT =
12481              OpTy->getAs<ObjCObjectPointerType>())
12482     Result = OPT->getPointeeType();
12483   else {
12484     ExprResult PR = S.CheckPlaceholderExpr(Op);
12485     if (PR.isInvalid()) return QualType();
12486     if (PR.get() != Op)
12487       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12488   }
12489 
12490   if (Result.isNull()) {
12491     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12492       << OpTy << Op->getSourceRange();
12493     return QualType();
12494   }
12495 
12496   // Note that per both C89 and C99, indirection is always legal, even if Result
12497   // is an incomplete type or void.  It would be possible to warn about
12498   // dereferencing a void pointer, but it's completely well-defined, and such a
12499   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12500   // for pointers to 'void' but is fine for any other pointer type:
12501   //
12502   // C++ [expr.unary.op]p1:
12503   //   [...] the expression to which [the unary * operator] is applied shall
12504   //   be a pointer to an object type, or a pointer to a function type
12505   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12506     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12507       << OpTy << Op->getSourceRange();
12508 
12509   // Dereferences are usually l-values...
12510   VK = VK_LValue;
12511 
12512   // ...except that certain expressions are never l-values in C.
12513   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12514     VK = VK_RValue;
12515 
12516   return Result;
12517 }
12518 
12519 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12520   BinaryOperatorKind Opc;
12521   switch (Kind) {
12522   default: llvm_unreachable("Unknown binop!");
12523   case tok::periodstar:           Opc = BO_PtrMemD; break;
12524   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12525   case tok::star:                 Opc = BO_Mul; break;
12526   case tok::slash:                Opc = BO_Div; break;
12527   case tok::percent:              Opc = BO_Rem; break;
12528   case tok::plus:                 Opc = BO_Add; break;
12529   case tok::minus:                Opc = BO_Sub; break;
12530   case tok::lessless:             Opc = BO_Shl; break;
12531   case tok::greatergreater:       Opc = BO_Shr; break;
12532   case tok::lessequal:            Opc = BO_LE; break;
12533   case tok::less:                 Opc = BO_LT; break;
12534   case tok::greaterequal:         Opc = BO_GE; break;
12535   case tok::greater:              Opc = BO_GT; break;
12536   case tok::exclaimequal:         Opc = BO_NE; break;
12537   case tok::equalequal:           Opc = BO_EQ; break;
12538   case tok::spaceship:            Opc = BO_Cmp; break;
12539   case tok::amp:                  Opc = BO_And; break;
12540   case tok::caret:                Opc = BO_Xor; break;
12541   case tok::pipe:                 Opc = BO_Or; break;
12542   case tok::ampamp:               Opc = BO_LAnd; break;
12543   case tok::pipepipe:             Opc = BO_LOr; break;
12544   case tok::equal:                Opc = BO_Assign; break;
12545   case tok::starequal:            Opc = BO_MulAssign; break;
12546   case tok::slashequal:           Opc = BO_DivAssign; break;
12547   case tok::percentequal:         Opc = BO_RemAssign; break;
12548   case tok::plusequal:            Opc = BO_AddAssign; break;
12549   case tok::minusequal:           Opc = BO_SubAssign; break;
12550   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12551   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12552   case tok::ampequal:             Opc = BO_AndAssign; break;
12553   case tok::caretequal:           Opc = BO_XorAssign; break;
12554   case tok::pipeequal:            Opc = BO_OrAssign; break;
12555   case tok::comma:                Opc = BO_Comma; break;
12556   }
12557   return Opc;
12558 }
12559 
12560 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12561   tok::TokenKind Kind) {
12562   UnaryOperatorKind Opc;
12563   switch (Kind) {
12564   default: llvm_unreachable("Unknown unary op!");
12565   case tok::plusplus:     Opc = UO_PreInc; break;
12566   case tok::minusminus:   Opc = UO_PreDec; break;
12567   case tok::amp:          Opc = UO_AddrOf; break;
12568   case tok::star:         Opc = UO_Deref; break;
12569   case tok::plus:         Opc = UO_Plus; break;
12570   case tok::minus:        Opc = UO_Minus; break;
12571   case tok::tilde:        Opc = UO_Not; break;
12572   case tok::exclaim:      Opc = UO_LNot; break;
12573   case tok::kw___real:    Opc = UO_Real; break;
12574   case tok::kw___imag:    Opc = UO_Imag; break;
12575   case tok::kw___extension__: Opc = UO_Extension; break;
12576   }
12577   return Opc;
12578 }
12579 
12580 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12581 /// This warning suppressed in the event of macro expansions.
12582 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12583                                    SourceLocation OpLoc, bool IsBuiltin) {
12584   if (S.inTemplateInstantiation())
12585     return;
12586   if (S.isUnevaluatedContext())
12587     return;
12588   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12589     return;
12590   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12591   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12592   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12593   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12594   if (!LHSDeclRef || !RHSDeclRef ||
12595       LHSDeclRef->getLocation().isMacroID() ||
12596       RHSDeclRef->getLocation().isMacroID())
12597     return;
12598   const ValueDecl *LHSDecl =
12599     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12600   const ValueDecl *RHSDecl =
12601     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12602   if (LHSDecl != RHSDecl)
12603     return;
12604   if (LHSDecl->getType().isVolatileQualified())
12605     return;
12606   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12607     if (RefTy->getPointeeType().isVolatileQualified())
12608       return;
12609 
12610   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12611                           : diag::warn_self_assignment_overloaded)
12612       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12613       << RHSExpr->getSourceRange();
12614 }
12615 
12616 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12617 /// is usually indicative of introspection within the Objective-C pointer.
12618 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12619                                           SourceLocation OpLoc) {
12620   if (!S.getLangOpts().ObjC)
12621     return;
12622 
12623   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12624   const Expr *LHS = L.get();
12625   const Expr *RHS = R.get();
12626 
12627   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12628     ObjCPointerExpr = LHS;
12629     OtherExpr = RHS;
12630   }
12631   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12632     ObjCPointerExpr = RHS;
12633     OtherExpr = LHS;
12634   }
12635 
12636   // This warning is deliberately made very specific to reduce false
12637   // positives with logic that uses '&' for hashing.  This logic mainly
12638   // looks for code trying to introspect into tagged pointers, which
12639   // code should generally never do.
12640   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12641     unsigned Diag = diag::warn_objc_pointer_masking;
12642     // Determine if we are introspecting the result of performSelectorXXX.
12643     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12644     // Special case messages to -performSelector and friends, which
12645     // can return non-pointer values boxed in a pointer value.
12646     // Some clients may wish to silence warnings in this subcase.
12647     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12648       Selector S = ME->getSelector();
12649       StringRef SelArg0 = S.getNameForSlot(0);
12650       if (SelArg0.startswith("performSelector"))
12651         Diag = diag::warn_objc_pointer_masking_performSelector;
12652     }
12653 
12654     S.Diag(OpLoc, Diag)
12655       << ObjCPointerExpr->getSourceRange();
12656   }
12657 }
12658 
12659 static NamedDecl *getDeclFromExpr(Expr *E) {
12660   if (!E)
12661     return nullptr;
12662   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12663     return DRE->getDecl();
12664   if (auto *ME = dyn_cast<MemberExpr>(E))
12665     return ME->getMemberDecl();
12666   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12667     return IRE->getDecl();
12668   return nullptr;
12669 }
12670 
12671 // This helper function promotes a binary operator's operands (which are of a
12672 // half vector type) to a vector of floats and then truncates the result to
12673 // a vector of either half or short.
12674 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12675                                       BinaryOperatorKind Opc, QualType ResultTy,
12676                                       ExprValueKind VK, ExprObjectKind OK,
12677                                       bool IsCompAssign, SourceLocation OpLoc,
12678                                       FPOptions FPFeatures) {
12679   auto &Context = S.getASTContext();
12680   assert((isVector(ResultTy, Context.HalfTy) ||
12681           isVector(ResultTy, Context.ShortTy)) &&
12682          "Result must be a vector of half or short");
12683   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12684          isVector(RHS.get()->getType(), Context.HalfTy) &&
12685          "both operands expected to be a half vector");
12686 
12687   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12688   QualType BinOpResTy = RHS.get()->getType();
12689 
12690   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12691   // change BinOpResTy to a vector of ints.
12692   if (isVector(ResultTy, Context.ShortTy))
12693     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12694 
12695   if (IsCompAssign)
12696     return new (Context) CompoundAssignOperator(
12697         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12698         OpLoc, FPFeatures);
12699 
12700   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12701   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12702                                           VK, OK, OpLoc, FPFeatures);
12703   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12704 }
12705 
12706 static std::pair<ExprResult, ExprResult>
12707 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12708                            Expr *RHSExpr) {
12709   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12710   if (!S.getLangOpts().CPlusPlus) {
12711     // C cannot handle TypoExpr nodes on either side of a binop because it
12712     // doesn't handle dependent types properly, so make sure any TypoExprs have
12713     // been dealt with before checking the operands.
12714     LHS = S.CorrectDelayedTyposInExpr(LHS);
12715     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12716       if (Opc != BO_Assign)
12717         return ExprResult(E);
12718       // Avoid correcting the RHS to the same Expr as the LHS.
12719       Decl *D = getDeclFromExpr(E);
12720       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12721     });
12722   }
12723   return std::make_pair(LHS, RHS);
12724 }
12725 
12726 /// Returns true if conversion between vectors of halfs and vectors of floats
12727 /// is needed.
12728 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12729                                      QualType SrcType) {
12730   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12731          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12732          isVector(SrcType, Ctx.HalfTy);
12733 }
12734 
12735 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12736 /// operator @p Opc at location @c TokLoc. This routine only supports
12737 /// built-in operations; ActOnBinOp handles overloaded operators.
12738 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12739                                     BinaryOperatorKind Opc,
12740                                     Expr *LHSExpr, Expr *RHSExpr) {
12741   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12742     // The syntax only allows initializer lists on the RHS of assignment,
12743     // so we don't need to worry about accepting invalid code for
12744     // non-assignment operators.
12745     // C++11 5.17p9:
12746     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12747     //   of x = {} is x = T().
12748     InitializationKind Kind = InitializationKind::CreateDirectList(
12749         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12750     InitializedEntity Entity =
12751         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12752     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12753     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12754     if (Init.isInvalid())
12755       return Init;
12756     RHSExpr = Init.get();
12757   }
12758 
12759   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12760   QualType ResultTy;     // Result type of the binary operator.
12761   // The following two variables are used for compound assignment operators
12762   QualType CompLHSTy;    // Type of LHS after promotions for computation
12763   QualType CompResultTy; // Type of computation result
12764   ExprValueKind VK = VK_RValue;
12765   ExprObjectKind OK = OK_Ordinary;
12766   bool ConvertHalfVec = false;
12767 
12768   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12769   if (!LHS.isUsable() || !RHS.isUsable())
12770     return ExprError();
12771 
12772   if (getLangOpts().OpenCL) {
12773     QualType LHSTy = LHSExpr->getType();
12774     QualType RHSTy = RHSExpr->getType();
12775     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12776     // the ATOMIC_VAR_INIT macro.
12777     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12778       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12779       if (BO_Assign == Opc)
12780         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12781       else
12782         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12783       return ExprError();
12784     }
12785 
12786     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12787     // only with a builtin functions and therefore should be disallowed here.
12788     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12789         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12790         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12791         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12792       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12793       return ExprError();
12794     }
12795   }
12796 
12797   // Diagnose operations on the unsupported types for OpenMP device compilation.
12798   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12799     if (Opc != BO_Assign && Opc != BO_Comma) {
12800       checkOpenMPDeviceExpr(LHSExpr);
12801       checkOpenMPDeviceExpr(RHSExpr);
12802     }
12803   }
12804 
12805   switch (Opc) {
12806   case BO_Assign:
12807     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12808     if (getLangOpts().CPlusPlus &&
12809         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12810       VK = LHS.get()->getValueKind();
12811       OK = LHS.get()->getObjectKind();
12812     }
12813     if (!ResultTy.isNull()) {
12814       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12815       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12816 
12817       // Avoid copying a block to the heap if the block is assigned to a local
12818       // auto variable that is declared in the same scope as the block. This
12819       // optimization is unsafe if the local variable is declared in an outer
12820       // scope. For example:
12821       //
12822       // BlockTy b;
12823       // {
12824       //   b = ^{...};
12825       // }
12826       // // It is unsafe to invoke the block here if it wasn't copied to the
12827       // // heap.
12828       // b();
12829 
12830       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12831         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12832           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12833             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12834               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12835 
12836       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
12837         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
12838                               NTCUC_Assignment, NTCUK_Copy);
12839     }
12840     RecordModifiableNonNullParam(*this, LHS.get());
12841     break;
12842   case BO_PtrMemD:
12843   case BO_PtrMemI:
12844     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12845                                             Opc == BO_PtrMemI);
12846     break;
12847   case BO_Mul:
12848   case BO_Div:
12849     ConvertHalfVec = true;
12850     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12851                                            Opc == BO_Div);
12852     break;
12853   case BO_Rem:
12854     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12855     break;
12856   case BO_Add:
12857     ConvertHalfVec = true;
12858     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12859     break;
12860   case BO_Sub:
12861     ConvertHalfVec = true;
12862     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12863     break;
12864   case BO_Shl:
12865   case BO_Shr:
12866     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12867     break;
12868   case BO_LE:
12869   case BO_LT:
12870   case BO_GE:
12871   case BO_GT:
12872     ConvertHalfVec = true;
12873     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12874     break;
12875   case BO_EQ:
12876   case BO_NE:
12877     ConvertHalfVec = true;
12878     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12879     break;
12880   case BO_Cmp:
12881     ConvertHalfVec = true;
12882     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12883     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12884     break;
12885   case BO_And:
12886     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12887     LLVM_FALLTHROUGH;
12888   case BO_Xor:
12889   case BO_Or:
12890     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12891     break;
12892   case BO_LAnd:
12893   case BO_LOr:
12894     ConvertHalfVec = true;
12895     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12896     break;
12897   case BO_MulAssign:
12898   case BO_DivAssign:
12899     ConvertHalfVec = true;
12900     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12901                                                Opc == BO_DivAssign);
12902     CompLHSTy = CompResultTy;
12903     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12904       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12905     break;
12906   case BO_RemAssign:
12907     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12908     CompLHSTy = CompResultTy;
12909     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12910       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12911     break;
12912   case BO_AddAssign:
12913     ConvertHalfVec = true;
12914     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12915     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12916       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12917     break;
12918   case BO_SubAssign:
12919     ConvertHalfVec = true;
12920     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12921     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12922       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12923     break;
12924   case BO_ShlAssign:
12925   case BO_ShrAssign:
12926     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12927     CompLHSTy = CompResultTy;
12928     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12929       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12930     break;
12931   case BO_AndAssign:
12932   case BO_OrAssign: // fallthrough
12933     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12934     LLVM_FALLTHROUGH;
12935   case BO_XorAssign:
12936     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12937     CompLHSTy = CompResultTy;
12938     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12939       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12940     break;
12941   case BO_Comma:
12942     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12943     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12944       VK = RHS.get()->getValueKind();
12945       OK = RHS.get()->getObjectKind();
12946     }
12947     break;
12948   }
12949   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12950     return ExprError();
12951 
12952   // Some of the binary operations require promoting operands of half vector to
12953   // float vectors and truncating the result back to half vector. For now, we do
12954   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12955   // arm64).
12956   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12957          isVector(LHS.get()->getType(), Context.HalfTy) &&
12958          "both sides are half vectors or neither sides are");
12959   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12960                                             LHS.get()->getType());
12961 
12962   // Check for array bounds violations for both sides of the BinaryOperator
12963   CheckArrayAccess(LHS.get());
12964   CheckArrayAccess(RHS.get());
12965 
12966   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12967     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12968                                                  &Context.Idents.get("object_setClass"),
12969                                                  SourceLocation(), LookupOrdinaryName);
12970     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12971       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12972       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12973           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12974                                         "object_setClass(")
12975           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12976                                           ",")
12977           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12978     }
12979     else
12980       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12981   }
12982   else if (const ObjCIvarRefExpr *OIRE =
12983            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12984     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12985 
12986   // Opc is not a compound assignment if CompResultTy is null.
12987   if (CompResultTy.isNull()) {
12988     if (ConvertHalfVec)
12989       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12990                                  OpLoc, FPFeatures);
12991     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12992                                         OK, OpLoc, FPFeatures);
12993   }
12994 
12995   // Handle compound assignments.
12996   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12997       OK_ObjCProperty) {
12998     VK = VK_LValue;
12999     OK = LHS.get()->getObjectKind();
13000   }
13001 
13002   if (ConvertHalfVec)
13003     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13004                                OpLoc, FPFeatures);
13005 
13006   return new (Context) CompoundAssignOperator(
13007       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13008       OpLoc, FPFeatures);
13009 }
13010 
13011 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13012 /// operators are mixed in a way that suggests that the programmer forgot that
13013 /// comparison operators have higher precedence. The most typical example of
13014 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13015 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13016                                       SourceLocation OpLoc, Expr *LHSExpr,
13017                                       Expr *RHSExpr) {
13018   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13019   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13020 
13021   // Check that one of the sides is a comparison operator and the other isn't.
13022   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13023   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13024   if (isLeftComp == isRightComp)
13025     return;
13026 
13027   // Bitwise operations are sometimes used as eager logical ops.
13028   // Don't diagnose this.
13029   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13030   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13031   if (isLeftBitwise || isRightBitwise)
13032     return;
13033 
13034   SourceRange DiagRange = isLeftComp
13035                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13036                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13037   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13038   SourceRange ParensRange =
13039       isLeftComp
13040           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13041           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13042 
13043   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13044     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13045   SuggestParentheses(Self, OpLoc,
13046     Self.PDiag(diag::note_precedence_silence) << OpStr,
13047     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13048   SuggestParentheses(Self, OpLoc,
13049     Self.PDiag(diag::note_precedence_bitwise_first)
13050       << BinaryOperator::getOpcodeStr(Opc),
13051     ParensRange);
13052 }
13053 
13054 /// It accepts a '&&' expr that is inside a '||' one.
13055 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13056 /// in parentheses.
13057 static void
13058 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13059                                        BinaryOperator *Bop) {
13060   assert(Bop->getOpcode() == BO_LAnd);
13061   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13062       << Bop->getSourceRange() << OpLoc;
13063   SuggestParentheses(Self, Bop->getOperatorLoc(),
13064     Self.PDiag(diag::note_precedence_silence)
13065       << Bop->getOpcodeStr(),
13066     Bop->getSourceRange());
13067 }
13068 
13069 /// Returns true if the given expression can be evaluated as a constant
13070 /// 'true'.
13071 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13072   bool Res;
13073   return !E->isValueDependent() &&
13074          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13075 }
13076 
13077 /// Returns true if the given expression can be evaluated as a constant
13078 /// 'false'.
13079 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13080   bool Res;
13081   return !E->isValueDependent() &&
13082          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13083 }
13084 
13085 /// Look for '&&' in the left hand of a '||' expr.
13086 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13087                                              Expr *LHSExpr, Expr *RHSExpr) {
13088   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13089     if (Bop->getOpcode() == BO_LAnd) {
13090       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13091       if (EvaluatesAsFalse(S, RHSExpr))
13092         return;
13093       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13094       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13095         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13096     } else if (Bop->getOpcode() == BO_LOr) {
13097       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13098         // If it's "a || b && 1 || c" we didn't warn earlier for
13099         // "a || b && 1", but warn now.
13100         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13101           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13102       }
13103     }
13104   }
13105 }
13106 
13107 /// Look for '&&' in the right hand of a '||' expr.
13108 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13109                                              Expr *LHSExpr, Expr *RHSExpr) {
13110   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13111     if (Bop->getOpcode() == BO_LAnd) {
13112       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13113       if (EvaluatesAsFalse(S, LHSExpr))
13114         return;
13115       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13116       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13117         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13118     }
13119   }
13120 }
13121 
13122 /// Look for bitwise op in the left or right hand of a bitwise op with
13123 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13124 /// the '&' expression in parentheses.
13125 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13126                                          SourceLocation OpLoc, Expr *SubExpr) {
13127   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13128     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13129       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13130         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13131         << Bop->getSourceRange() << OpLoc;
13132       SuggestParentheses(S, Bop->getOperatorLoc(),
13133         S.PDiag(diag::note_precedence_silence)
13134           << Bop->getOpcodeStr(),
13135         Bop->getSourceRange());
13136     }
13137   }
13138 }
13139 
13140 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13141                                     Expr *SubExpr, StringRef Shift) {
13142   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13143     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13144       StringRef Op = Bop->getOpcodeStr();
13145       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13146           << Bop->getSourceRange() << OpLoc << Shift << Op;
13147       SuggestParentheses(S, Bop->getOperatorLoc(),
13148           S.PDiag(diag::note_precedence_silence) << Op,
13149           Bop->getSourceRange());
13150     }
13151   }
13152 }
13153 
13154 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13155                                  Expr *LHSExpr, Expr *RHSExpr) {
13156   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13157   if (!OCE)
13158     return;
13159 
13160   FunctionDecl *FD = OCE->getDirectCallee();
13161   if (!FD || !FD->isOverloadedOperator())
13162     return;
13163 
13164   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13165   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13166     return;
13167 
13168   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13169       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13170       << (Kind == OO_LessLess);
13171   SuggestParentheses(S, OCE->getOperatorLoc(),
13172                      S.PDiag(diag::note_precedence_silence)
13173                          << (Kind == OO_LessLess ? "<<" : ">>"),
13174                      OCE->getSourceRange());
13175   SuggestParentheses(
13176       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13177       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13178 }
13179 
13180 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13181 /// precedence.
13182 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13183                                     SourceLocation OpLoc, Expr *LHSExpr,
13184                                     Expr *RHSExpr){
13185   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13186   if (BinaryOperator::isBitwiseOp(Opc))
13187     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13188 
13189   // Diagnose "arg1 & arg2 | arg3"
13190   if ((Opc == BO_Or || Opc == BO_Xor) &&
13191       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13192     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13193     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13194   }
13195 
13196   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13197   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13198   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13199     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13200     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13201   }
13202 
13203   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13204       || Opc == BO_Shr) {
13205     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13206     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13207     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13208   }
13209 
13210   // Warn on overloaded shift operators and comparisons, such as:
13211   // cout << 5 == 4;
13212   if (BinaryOperator::isComparisonOp(Opc))
13213     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13214 }
13215 
13216 // Binary Operators.  'Tok' is the token for the operator.
13217 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13218                             tok::TokenKind Kind,
13219                             Expr *LHSExpr, Expr *RHSExpr) {
13220   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13221   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13222   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13223 
13224   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13225   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13226 
13227   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13228 }
13229 
13230 /// Build an overloaded binary operator expression in the given scope.
13231 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13232                                        BinaryOperatorKind Opc,
13233                                        Expr *LHS, Expr *RHS) {
13234   switch (Opc) {
13235   case BO_Assign:
13236   case BO_DivAssign:
13237   case BO_RemAssign:
13238   case BO_SubAssign:
13239   case BO_AndAssign:
13240   case BO_OrAssign:
13241   case BO_XorAssign:
13242     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13243     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13244     break;
13245   default:
13246     break;
13247   }
13248 
13249   // Find all of the overloaded operators visible from this
13250   // point. We perform both an operator-name lookup from the local
13251   // scope and an argument-dependent lookup based on the types of
13252   // the arguments.
13253   UnresolvedSet<16> Functions;
13254   OverloadedOperatorKind OverOp
13255     = BinaryOperator::getOverloadedOperator(Opc);
13256   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13257     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13258                                    RHS->getType(), Functions);
13259 
13260   // Build the (potentially-overloaded, potentially-dependent)
13261   // binary operation.
13262   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13263 }
13264 
13265 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13266                             BinaryOperatorKind Opc,
13267                             Expr *LHSExpr, Expr *RHSExpr) {
13268   ExprResult LHS, RHS;
13269   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13270   if (!LHS.isUsable() || !RHS.isUsable())
13271     return ExprError();
13272   LHSExpr = LHS.get();
13273   RHSExpr = RHS.get();
13274 
13275   // We want to end up calling one of checkPseudoObjectAssignment
13276   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13277   // both expressions are overloadable or either is type-dependent),
13278   // or CreateBuiltinBinOp (in any other case).  We also want to get
13279   // any placeholder types out of the way.
13280 
13281   // Handle pseudo-objects in the LHS.
13282   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13283     // Assignments with a pseudo-object l-value need special analysis.
13284     if (pty->getKind() == BuiltinType::PseudoObject &&
13285         BinaryOperator::isAssignmentOp(Opc))
13286       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13287 
13288     // Don't resolve overloads if the other type is overloadable.
13289     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13290       // We can't actually test that if we still have a placeholder,
13291       // though.  Fortunately, none of the exceptions we see in that
13292       // code below are valid when the LHS is an overload set.  Note
13293       // that an overload set can be dependently-typed, but it never
13294       // instantiates to having an overloadable type.
13295       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13296       if (resolvedRHS.isInvalid()) return ExprError();
13297       RHSExpr = resolvedRHS.get();
13298 
13299       if (RHSExpr->isTypeDependent() ||
13300           RHSExpr->getType()->isOverloadableType())
13301         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13302     }
13303 
13304     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13305     // template, diagnose the missing 'template' keyword instead of diagnosing
13306     // an invalid use of a bound member function.
13307     //
13308     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13309     // to C++1z [over.over]/1.4, but we already checked for that case above.
13310     if (Opc == BO_LT && inTemplateInstantiation() &&
13311         (pty->getKind() == BuiltinType::BoundMember ||
13312          pty->getKind() == BuiltinType::Overload)) {
13313       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13314       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13315           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13316             return isa<FunctionTemplateDecl>(ND);
13317           })) {
13318         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13319                                 : OE->getNameLoc(),
13320              diag::err_template_kw_missing)
13321           << OE->getName().getAsString() << "";
13322         return ExprError();
13323       }
13324     }
13325 
13326     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13327     if (LHS.isInvalid()) return ExprError();
13328     LHSExpr = LHS.get();
13329   }
13330 
13331   // Handle pseudo-objects in the RHS.
13332   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13333     // An overload in the RHS can potentially be resolved by the type
13334     // being assigned to.
13335     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13336       if (getLangOpts().CPlusPlus &&
13337           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13338            LHSExpr->getType()->isOverloadableType()))
13339         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13340 
13341       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13342     }
13343 
13344     // Don't resolve overloads if the other type is overloadable.
13345     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13346         LHSExpr->getType()->isOverloadableType())
13347       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13348 
13349     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13350     if (!resolvedRHS.isUsable()) return ExprError();
13351     RHSExpr = resolvedRHS.get();
13352   }
13353 
13354   if (getLangOpts().CPlusPlus) {
13355     // If either expression is type-dependent, always build an
13356     // overloaded op.
13357     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13358       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13359 
13360     // Otherwise, build an overloaded op if either expression has an
13361     // overloadable type.
13362     if (LHSExpr->getType()->isOverloadableType() ||
13363         RHSExpr->getType()->isOverloadableType())
13364       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13365   }
13366 
13367   // Build a built-in binary operation.
13368   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13369 }
13370 
13371 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13372   if (T.isNull() || T->isDependentType())
13373     return false;
13374 
13375   if (!T->isPromotableIntegerType())
13376     return true;
13377 
13378   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13379 }
13380 
13381 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13382                                       UnaryOperatorKind Opc,
13383                                       Expr *InputExpr) {
13384   ExprResult Input = InputExpr;
13385   ExprValueKind VK = VK_RValue;
13386   ExprObjectKind OK = OK_Ordinary;
13387   QualType resultType;
13388   bool CanOverflow = false;
13389 
13390   bool ConvertHalfVec = false;
13391   if (getLangOpts().OpenCL) {
13392     QualType Ty = InputExpr->getType();
13393     // The only legal unary operation for atomics is '&'.
13394     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13395     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13396     // only with a builtin functions and therefore should be disallowed here.
13397         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13398         || Ty->isBlockPointerType())) {
13399       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13400                        << InputExpr->getType()
13401                        << Input.get()->getSourceRange());
13402     }
13403   }
13404   // Diagnose operations on the unsupported types for OpenMP device compilation.
13405   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13406     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13407         UnaryOperator::isArithmeticOp(Opc))
13408       checkOpenMPDeviceExpr(InputExpr);
13409   }
13410 
13411   switch (Opc) {
13412   case UO_PreInc:
13413   case UO_PreDec:
13414   case UO_PostInc:
13415   case UO_PostDec:
13416     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13417                                                 OpLoc,
13418                                                 Opc == UO_PreInc ||
13419                                                 Opc == UO_PostInc,
13420                                                 Opc == UO_PreInc ||
13421                                                 Opc == UO_PreDec);
13422     CanOverflow = isOverflowingIntegerType(Context, resultType);
13423     break;
13424   case UO_AddrOf:
13425     resultType = CheckAddressOfOperand(Input, OpLoc);
13426     CheckAddressOfNoDeref(InputExpr);
13427     RecordModifiableNonNullParam(*this, InputExpr);
13428     break;
13429   case UO_Deref: {
13430     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13431     if (Input.isInvalid()) return ExprError();
13432     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13433     break;
13434   }
13435   case UO_Plus:
13436   case UO_Minus:
13437     CanOverflow = Opc == UO_Minus &&
13438                   isOverflowingIntegerType(Context, Input.get()->getType());
13439     Input = UsualUnaryConversions(Input.get());
13440     if (Input.isInvalid()) return ExprError();
13441     // Unary plus and minus require promoting an operand of half vector to a
13442     // float vector and truncating the result back to a half vector. For now, we
13443     // do this only when HalfArgsAndReturns is set (that is, when the target is
13444     // arm or arm64).
13445     ConvertHalfVec =
13446         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13447 
13448     // If the operand is a half vector, promote it to a float vector.
13449     if (ConvertHalfVec)
13450       Input = convertVector(Input.get(), Context.FloatTy, *this);
13451     resultType = Input.get()->getType();
13452     if (resultType->isDependentType())
13453       break;
13454     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13455       break;
13456     else if (resultType->isVectorType() &&
13457              // The z vector extensions don't allow + or - with bool vectors.
13458              (!Context.getLangOpts().ZVector ||
13459               resultType->castAs<VectorType>()->getVectorKind() !=
13460               VectorType::AltiVecBool))
13461       break;
13462     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13463              Opc == UO_Plus &&
13464              resultType->isPointerType())
13465       break;
13466 
13467     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13468       << resultType << Input.get()->getSourceRange());
13469 
13470   case UO_Not: // bitwise complement
13471     Input = UsualUnaryConversions(Input.get());
13472     if (Input.isInvalid())
13473       return ExprError();
13474     resultType = Input.get()->getType();
13475     if (resultType->isDependentType())
13476       break;
13477     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13478     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13479       // C99 does not support '~' for complex conjugation.
13480       Diag(OpLoc, diag::ext_integer_complement_complex)
13481           << resultType << Input.get()->getSourceRange();
13482     else if (Input.get()->isKnownToHaveBooleanValue())
13483       Diag(OpLoc, diag::warn_bitwise_negation_bool)
13484           << FixItHint::CreateReplacement(OpLoc, "!");
13485     else if (resultType->hasIntegerRepresentation())
13486       break;
13487     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13488       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13489       // on vector float types.
13490       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13491       if (!T->isIntegerType())
13492         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13493                           << resultType << Input.get()->getSourceRange());
13494     } else {
13495       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13496                        << resultType << Input.get()->getSourceRange());
13497     }
13498     break;
13499 
13500   case UO_LNot: // logical negation
13501     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13502     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13503     if (Input.isInvalid()) return ExprError();
13504     resultType = Input.get()->getType();
13505 
13506     // Though we still have to promote half FP to float...
13507     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13508       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13509       resultType = Context.FloatTy;
13510     }
13511 
13512     if (resultType->isDependentType())
13513       break;
13514     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13515       // C99 6.5.3.3p1: ok, fallthrough;
13516       if (Context.getLangOpts().CPlusPlus) {
13517         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13518         // operand contextually converted to bool.
13519         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13520                                   ScalarTypeToBooleanCastKind(resultType));
13521       } else if (Context.getLangOpts().OpenCL &&
13522                  Context.getLangOpts().OpenCLVersion < 120) {
13523         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13524         // operate on scalar float types.
13525         if (!resultType->isIntegerType() && !resultType->isPointerType())
13526           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13527                            << resultType << Input.get()->getSourceRange());
13528       }
13529     } else if (resultType->isExtVectorType()) {
13530       if (Context.getLangOpts().OpenCL &&
13531           Context.getLangOpts().OpenCLVersion < 120 &&
13532           !Context.getLangOpts().OpenCLCPlusPlus) {
13533         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13534         // operate on vector float types.
13535         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13536         if (!T->isIntegerType())
13537           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13538                            << resultType << Input.get()->getSourceRange());
13539       }
13540       // Vector logical not returns the signed variant of the operand type.
13541       resultType = GetSignedVectorType(resultType);
13542       break;
13543     } else {
13544       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13545       //        type in C++. We should allow that here too.
13546       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13547         << resultType << Input.get()->getSourceRange());
13548     }
13549 
13550     // LNot always has type int. C99 6.5.3.3p5.
13551     // In C++, it's bool. C++ 5.3.1p8
13552     resultType = Context.getLogicalOperationType();
13553     break;
13554   case UO_Real:
13555   case UO_Imag:
13556     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13557     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13558     // complex l-values to ordinary l-values and all other values to r-values.
13559     if (Input.isInvalid()) return ExprError();
13560     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13561       if (Input.get()->getValueKind() != VK_RValue &&
13562           Input.get()->getObjectKind() == OK_Ordinary)
13563         VK = Input.get()->getValueKind();
13564     } else if (!getLangOpts().CPlusPlus) {
13565       // In C, a volatile scalar is read by __imag. In C++, it is not.
13566       Input = DefaultLvalueConversion(Input.get());
13567     }
13568     break;
13569   case UO_Extension:
13570     resultType = Input.get()->getType();
13571     VK = Input.get()->getValueKind();
13572     OK = Input.get()->getObjectKind();
13573     break;
13574   case UO_Coawait:
13575     // It's unnecessary to represent the pass-through operator co_await in the
13576     // AST; just return the input expression instead.
13577     assert(!Input.get()->getType()->isDependentType() &&
13578                    "the co_await expression must be non-dependant before "
13579                    "building operator co_await");
13580     return Input;
13581   }
13582   if (resultType.isNull() || Input.isInvalid())
13583     return ExprError();
13584 
13585   // Check for array bounds violations in the operand of the UnaryOperator,
13586   // except for the '*' and '&' operators that have to be handled specially
13587   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13588   // that are explicitly defined as valid by the standard).
13589   if (Opc != UO_AddrOf && Opc != UO_Deref)
13590     CheckArrayAccess(Input.get());
13591 
13592   auto *UO = new (Context)
13593       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13594 
13595   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13596       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13597     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13598 
13599   // Convert the result back to a half vector.
13600   if (ConvertHalfVec)
13601     return convertVector(UO, Context.HalfTy, *this);
13602   return UO;
13603 }
13604 
13605 /// Determine whether the given expression is a qualified member
13606 /// access expression, of a form that could be turned into a pointer to member
13607 /// with the address-of operator.
13608 bool Sema::isQualifiedMemberAccess(Expr *E) {
13609   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13610     if (!DRE->getQualifier())
13611       return false;
13612 
13613     ValueDecl *VD = DRE->getDecl();
13614     if (!VD->isCXXClassMember())
13615       return false;
13616 
13617     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13618       return true;
13619     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13620       return Method->isInstance();
13621 
13622     return false;
13623   }
13624 
13625   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13626     if (!ULE->getQualifier())
13627       return false;
13628 
13629     for (NamedDecl *D : ULE->decls()) {
13630       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13631         if (Method->isInstance())
13632           return true;
13633       } else {
13634         // Overload set does not contain methods.
13635         break;
13636       }
13637     }
13638 
13639     return false;
13640   }
13641 
13642   return false;
13643 }
13644 
13645 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13646                               UnaryOperatorKind Opc, Expr *Input) {
13647   // First things first: handle placeholders so that the
13648   // overloaded-operator check considers the right type.
13649   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13650     // Increment and decrement of pseudo-object references.
13651     if (pty->getKind() == BuiltinType::PseudoObject &&
13652         UnaryOperator::isIncrementDecrementOp(Opc))
13653       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13654 
13655     // extension is always a builtin operator.
13656     if (Opc == UO_Extension)
13657       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13658 
13659     // & gets special logic for several kinds of placeholder.
13660     // The builtin code knows what to do.
13661     if (Opc == UO_AddrOf &&
13662         (pty->getKind() == BuiltinType::Overload ||
13663          pty->getKind() == BuiltinType::UnknownAny ||
13664          pty->getKind() == BuiltinType::BoundMember))
13665       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13666 
13667     // Anything else needs to be handled now.
13668     ExprResult Result = CheckPlaceholderExpr(Input);
13669     if (Result.isInvalid()) return ExprError();
13670     Input = Result.get();
13671   }
13672 
13673   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13674       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13675       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13676     // Find all of the overloaded operators visible from this
13677     // point. We perform both an operator-name lookup from the local
13678     // scope and an argument-dependent lookup based on the types of
13679     // the arguments.
13680     UnresolvedSet<16> Functions;
13681     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13682     if (S && OverOp != OO_None)
13683       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13684                                    Functions);
13685 
13686     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13687   }
13688 
13689   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13690 }
13691 
13692 // Unary Operators.  'Tok' is the token for the operator.
13693 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13694                               tok::TokenKind Op, Expr *Input) {
13695   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13696 }
13697 
13698 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13699 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13700                                 LabelDecl *TheDecl) {
13701   TheDecl->markUsed(Context);
13702   // Create the AST node.  The address of a label always has type 'void*'.
13703   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13704                                      Context.getPointerType(Context.VoidTy));
13705 }
13706 
13707 void Sema::ActOnStartStmtExpr() {
13708   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13709 }
13710 
13711 void Sema::ActOnStmtExprError() {
13712   // Note that function is also called by TreeTransform when leaving a
13713   // StmtExpr scope without rebuilding anything.
13714 
13715   DiscardCleanupsInEvaluationContext();
13716   PopExpressionEvaluationContext();
13717 }
13718 
13719 ExprResult
13720 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13721                     SourceLocation RPLoc) { // "({..})"
13722   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13723   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13724 
13725   if (hasAnyUnrecoverableErrorsInThisFunction())
13726     DiscardCleanupsInEvaluationContext();
13727   assert(!Cleanup.exprNeedsCleanups() &&
13728          "cleanups within StmtExpr not correctly bound!");
13729   PopExpressionEvaluationContext();
13730 
13731   // FIXME: there are a variety of strange constraints to enforce here, for
13732   // example, it is not possible to goto into a stmt expression apparently.
13733   // More semantic analysis is needed.
13734 
13735   // If there are sub-stmts in the compound stmt, take the type of the last one
13736   // as the type of the stmtexpr.
13737   QualType Ty = Context.VoidTy;
13738   bool StmtExprMayBindToTemp = false;
13739   if (!Compound->body_empty()) {
13740     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13741     if (const auto *LastStmt =
13742             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13743       if (const Expr *Value = LastStmt->getExprStmt()) {
13744         StmtExprMayBindToTemp = true;
13745         Ty = Value->getType();
13746       }
13747     }
13748   }
13749 
13750   // FIXME: Check that expression type is complete/non-abstract; statement
13751   // expressions are not lvalues.
13752   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13753   if (StmtExprMayBindToTemp)
13754     return MaybeBindToTemporary(ResStmtExpr);
13755   return ResStmtExpr;
13756 }
13757 
13758 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13759   if (ER.isInvalid())
13760     return ExprError();
13761 
13762   // Do function/array conversion on the last expression, but not
13763   // lvalue-to-rvalue.  However, initialize an unqualified type.
13764   ER = DefaultFunctionArrayConversion(ER.get());
13765   if (ER.isInvalid())
13766     return ExprError();
13767   Expr *E = ER.get();
13768 
13769   if (E->isTypeDependent())
13770     return E;
13771 
13772   // In ARC, if the final expression ends in a consume, splice
13773   // the consume out and bind it later.  In the alternate case
13774   // (when dealing with a retainable type), the result
13775   // initialization will create a produce.  In both cases the
13776   // result will be +1, and we'll need to balance that out with
13777   // a bind.
13778   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13779   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13780     return Cast->getSubExpr();
13781 
13782   // FIXME: Provide a better location for the initialization.
13783   return PerformCopyInitialization(
13784       InitializedEntity::InitializeStmtExprResult(
13785           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13786       SourceLocation(), E);
13787 }
13788 
13789 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13790                                       TypeSourceInfo *TInfo,
13791                                       ArrayRef<OffsetOfComponent> Components,
13792                                       SourceLocation RParenLoc) {
13793   QualType ArgTy = TInfo->getType();
13794   bool Dependent = ArgTy->isDependentType();
13795   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13796 
13797   // We must have at least one component that refers to the type, and the first
13798   // one is known to be a field designator.  Verify that the ArgTy represents
13799   // a struct/union/class.
13800   if (!Dependent && !ArgTy->isRecordType())
13801     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13802                        << ArgTy << TypeRange);
13803 
13804   // Type must be complete per C99 7.17p3 because a declaring a variable
13805   // with an incomplete type would be ill-formed.
13806   if (!Dependent
13807       && RequireCompleteType(BuiltinLoc, ArgTy,
13808                              diag::err_offsetof_incomplete_type, TypeRange))
13809     return ExprError();
13810 
13811   bool DidWarnAboutNonPOD = false;
13812   QualType CurrentType = ArgTy;
13813   SmallVector<OffsetOfNode, 4> Comps;
13814   SmallVector<Expr*, 4> Exprs;
13815   for (const OffsetOfComponent &OC : Components) {
13816     if (OC.isBrackets) {
13817       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13818       if (!CurrentType->isDependentType()) {
13819         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13820         if(!AT)
13821           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13822                            << CurrentType);
13823         CurrentType = AT->getElementType();
13824       } else
13825         CurrentType = Context.DependentTy;
13826 
13827       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13828       if (IdxRval.isInvalid())
13829         return ExprError();
13830       Expr *Idx = IdxRval.get();
13831 
13832       // The expression must be an integral expression.
13833       // FIXME: An integral constant expression?
13834       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13835           !Idx->getType()->isIntegerType())
13836         return ExprError(
13837             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13838             << Idx->getSourceRange());
13839 
13840       // Record this array index.
13841       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13842       Exprs.push_back(Idx);
13843       continue;
13844     }
13845 
13846     // Offset of a field.
13847     if (CurrentType->isDependentType()) {
13848       // We have the offset of a field, but we can't look into the dependent
13849       // type. Just record the identifier of the field.
13850       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13851       CurrentType = Context.DependentTy;
13852       continue;
13853     }
13854 
13855     // We need to have a complete type to look into.
13856     if (RequireCompleteType(OC.LocStart, CurrentType,
13857                             diag::err_offsetof_incomplete_type))
13858       return ExprError();
13859 
13860     // Look for the designated field.
13861     const RecordType *RC = CurrentType->getAs<RecordType>();
13862     if (!RC)
13863       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13864                        << CurrentType);
13865     RecordDecl *RD = RC->getDecl();
13866 
13867     // C++ [lib.support.types]p5:
13868     //   The macro offsetof accepts a restricted set of type arguments in this
13869     //   International Standard. type shall be a POD structure or a POD union
13870     //   (clause 9).
13871     // C++11 [support.types]p4:
13872     //   If type is not a standard-layout class (Clause 9), the results are
13873     //   undefined.
13874     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13875       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13876       unsigned DiagID =
13877         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13878                             : diag::ext_offsetof_non_pod_type;
13879 
13880       if (!IsSafe && !DidWarnAboutNonPOD &&
13881           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13882                               PDiag(DiagID)
13883                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13884                               << CurrentType))
13885         DidWarnAboutNonPOD = true;
13886     }
13887 
13888     // Look for the field.
13889     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13890     LookupQualifiedName(R, RD);
13891     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13892     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13893     if (!MemberDecl) {
13894       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13895         MemberDecl = IndirectMemberDecl->getAnonField();
13896     }
13897 
13898     if (!MemberDecl)
13899       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13900                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13901                                                               OC.LocEnd));
13902 
13903     // C99 7.17p3:
13904     //   (If the specified member is a bit-field, the behavior is undefined.)
13905     //
13906     // We diagnose this as an error.
13907     if (MemberDecl->isBitField()) {
13908       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13909         << MemberDecl->getDeclName()
13910         << SourceRange(BuiltinLoc, RParenLoc);
13911       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13912       return ExprError();
13913     }
13914 
13915     RecordDecl *Parent = MemberDecl->getParent();
13916     if (IndirectMemberDecl)
13917       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13918 
13919     // If the member was found in a base class, introduce OffsetOfNodes for
13920     // the base class indirections.
13921     CXXBasePaths Paths;
13922     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13923                       Paths)) {
13924       if (Paths.getDetectedVirtual()) {
13925         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13926           << MemberDecl->getDeclName()
13927           << SourceRange(BuiltinLoc, RParenLoc);
13928         return ExprError();
13929       }
13930 
13931       CXXBasePath &Path = Paths.front();
13932       for (const CXXBasePathElement &B : Path)
13933         Comps.push_back(OffsetOfNode(B.Base));
13934     }
13935 
13936     if (IndirectMemberDecl) {
13937       for (auto *FI : IndirectMemberDecl->chain()) {
13938         assert(isa<FieldDecl>(FI));
13939         Comps.push_back(OffsetOfNode(OC.LocStart,
13940                                      cast<FieldDecl>(FI), OC.LocEnd));
13941       }
13942     } else
13943       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13944 
13945     CurrentType = MemberDecl->getType().getNonReferenceType();
13946   }
13947 
13948   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13949                               Comps, Exprs, RParenLoc);
13950 }
13951 
13952 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13953                                       SourceLocation BuiltinLoc,
13954                                       SourceLocation TypeLoc,
13955                                       ParsedType ParsedArgTy,
13956                                       ArrayRef<OffsetOfComponent> Components,
13957                                       SourceLocation RParenLoc) {
13958 
13959   TypeSourceInfo *ArgTInfo;
13960   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13961   if (ArgTy.isNull())
13962     return ExprError();
13963 
13964   if (!ArgTInfo)
13965     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13966 
13967   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13968 }
13969 
13970 
13971 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13972                                  Expr *CondExpr,
13973                                  Expr *LHSExpr, Expr *RHSExpr,
13974                                  SourceLocation RPLoc) {
13975   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13976 
13977   ExprValueKind VK = VK_RValue;
13978   ExprObjectKind OK = OK_Ordinary;
13979   QualType resType;
13980   bool ValueDependent = false;
13981   bool CondIsTrue = false;
13982   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13983     resType = Context.DependentTy;
13984     ValueDependent = true;
13985   } else {
13986     // The conditional expression is required to be a constant expression.
13987     llvm::APSInt condEval(32);
13988     ExprResult CondICE
13989       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13990           diag::err_typecheck_choose_expr_requires_constant, false);
13991     if (CondICE.isInvalid())
13992       return ExprError();
13993     CondExpr = CondICE.get();
13994     CondIsTrue = condEval.getZExtValue();
13995 
13996     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13997     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13998 
13999     resType = ActiveExpr->getType();
14000     ValueDependent = ActiveExpr->isValueDependent();
14001     VK = ActiveExpr->getValueKind();
14002     OK = ActiveExpr->getObjectKind();
14003   }
14004 
14005   return new (Context)
14006       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14007                  CondIsTrue, resType->isDependentType(), ValueDependent);
14008 }
14009 
14010 //===----------------------------------------------------------------------===//
14011 // Clang Extensions.
14012 //===----------------------------------------------------------------------===//
14013 
14014 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14015 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14016   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14017 
14018   if (LangOpts.CPlusPlus) {
14019     Decl *ManglingContextDecl;
14020     if (MangleNumberingContext *MCtx =
14021             getCurrentMangleNumberContext(Block->getDeclContext(),
14022                                           ManglingContextDecl)) {
14023       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14024       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14025     }
14026   }
14027 
14028   PushBlockScope(CurScope, Block);
14029   CurContext->addDecl(Block);
14030   if (CurScope)
14031     PushDeclContext(CurScope, Block);
14032   else
14033     CurContext = Block;
14034 
14035   getCurBlock()->HasImplicitReturnType = true;
14036 
14037   // Enter a new evaluation context to insulate the block from any
14038   // cleanups from the enclosing full-expression.
14039   PushExpressionEvaluationContext(
14040       ExpressionEvaluationContext::PotentiallyEvaluated);
14041 }
14042 
14043 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14044                                Scope *CurScope) {
14045   assert(ParamInfo.getIdentifier() == nullptr &&
14046          "block-id should have no identifier!");
14047   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14048   BlockScopeInfo *CurBlock = getCurBlock();
14049 
14050   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14051   QualType T = Sig->getType();
14052 
14053   // FIXME: We should allow unexpanded parameter packs here, but that would,
14054   // in turn, make the block expression contain unexpanded parameter packs.
14055   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14056     // Drop the parameters.
14057     FunctionProtoType::ExtProtoInfo EPI;
14058     EPI.HasTrailingReturn = false;
14059     EPI.TypeQuals.addConst();
14060     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14061     Sig = Context.getTrivialTypeSourceInfo(T);
14062   }
14063 
14064   // GetTypeForDeclarator always produces a function type for a block
14065   // literal signature.  Furthermore, it is always a FunctionProtoType
14066   // unless the function was written with a typedef.
14067   assert(T->isFunctionType() &&
14068          "GetTypeForDeclarator made a non-function block signature");
14069 
14070   // Look for an explicit signature in that function type.
14071   FunctionProtoTypeLoc ExplicitSignature;
14072 
14073   if ((ExplicitSignature = Sig->getTypeLoc()
14074                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14075 
14076     // Check whether that explicit signature was synthesized by
14077     // GetTypeForDeclarator.  If so, don't save that as part of the
14078     // written signature.
14079     if (ExplicitSignature.getLocalRangeBegin() ==
14080         ExplicitSignature.getLocalRangeEnd()) {
14081       // This would be much cheaper if we stored TypeLocs instead of
14082       // TypeSourceInfos.
14083       TypeLoc Result = ExplicitSignature.getReturnLoc();
14084       unsigned Size = Result.getFullDataSize();
14085       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14086       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14087 
14088       ExplicitSignature = FunctionProtoTypeLoc();
14089     }
14090   }
14091 
14092   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14093   CurBlock->FunctionType = T;
14094 
14095   const FunctionType *Fn = T->getAs<FunctionType>();
14096   QualType RetTy = Fn->getReturnType();
14097   bool isVariadic =
14098     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14099 
14100   CurBlock->TheDecl->setIsVariadic(isVariadic);
14101 
14102   // Context.DependentTy is used as a placeholder for a missing block
14103   // return type.  TODO:  what should we do with declarators like:
14104   //   ^ * { ... }
14105   // If the answer is "apply template argument deduction"....
14106   if (RetTy != Context.DependentTy) {
14107     CurBlock->ReturnType = RetTy;
14108     CurBlock->TheDecl->setBlockMissingReturnType(false);
14109     CurBlock->HasImplicitReturnType = false;
14110   }
14111 
14112   // Push block parameters from the declarator if we had them.
14113   SmallVector<ParmVarDecl*, 8> Params;
14114   if (ExplicitSignature) {
14115     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14116       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14117       if (Param->getIdentifier() == nullptr &&
14118           !Param->isImplicit() &&
14119           !Param->isInvalidDecl() &&
14120           !getLangOpts().CPlusPlus)
14121         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14122       Params.push_back(Param);
14123     }
14124 
14125   // Fake up parameter variables if we have a typedef, like
14126   //   ^ fntype { ... }
14127   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14128     for (const auto &I : Fn->param_types()) {
14129       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14130           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14131       Params.push_back(Param);
14132     }
14133   }
14134 
14135   // Set the parameters on the block decl.
14136   if (!Params.empty()) {
14137     CurBlock->TheDecl->setParams(Params);
14138     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14139                              /*CheckParameterNames=*/false);
14140   }
14141 
14142   // Finally we can process decl attributes.
14143   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14144 
14145   // Put the parameter variables in scope.
14146   for (auto AI : CurBlock->TheDecl->parameters()) {
14147     AI->setOwningFunction(CurBlock->TheDecl);
14148 
14149     // If this has an identifier, add it to the scope stack.
14150     if (AI->getIdentifier()) {
14151       CheckShadow(CurBlock->TheScope, AI);
14152 
14153       PushOnScopeChains(AI, CurBlock->TheScope);
14154     }
14155   }
14156 }
14157 
14158 /// ActOnBlockError - If there is an error parsing a block, this callback
14159 /// is invoked to pop the information about the block from the action impl.
14160 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14161   // Leave the expression-evaluation context.
14162   DiscardCleanupsInEvaluationContext();
14163   PopExpressionEvaluationContext();
14164 
14165   // Pop off CurBlock, handle nested blocks.
14166   PopDeclContext();
14167   PopFunctionScopeInfo();
14168 }
14169 
14170 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14171 /// literal was successfully completed.  ^(int x){...}
14172 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14173                                     Stmt *Body, Scope *CurScope) {
14174   // If blocks are disabled, emit an error.
14175   if (!LangOpts.Blocks)
14176     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14177 
14178   // Leave the expression-evaluation context.
14179   if (hasAnyUnrecoverableErrorsInThisFunction())
14180     DiscardCleanupsInEvaluationContext();
14181   assert(!Cleanup.exprNeedsCleanups() &&
14182          "cleanups within block not correctly bound!");
14183   PopExpressionEvaluationContext();
14184 
14185   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14186   BlockDecl *BD = BSI->TheDecl;
14187 
14188   if (BSI->HasImplicitReturnType)
14189     deduceClosureReturnType(*BSI);
14190 
14191   QualType RetTy = Context.VoidTy;
14192   if (!BSI->ReturnType.isNull())
14193     RetTy = BSI->ReturnType;
14194 
14195   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14196   QualType BlockTy;
14197 
14198   // If the user wrote a function type in some form, try to use that.
14199   if (!BSI->FunctionType.isNull()) {
14200     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14201 
14202     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14203     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14204 
14205     // Turn protoless block types into nullary block types.
14206     if (isa<FunctionNoProtoType>(FTy)) {
14207       FunctionProtoType::ExtProtoInfo EPI;
14208       EPI.ExtInfo = Ext;
14209       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14210 
14211     // Otherwise, if we don't need to change anything about the function type,
14212     // preserve its sugar structure.
14213     } else if (FTy->getReturnType() == RetTy &&
14214                (!NoReturn || FTy->getNoReturnAttr())) {
14215       BlockTy = BSI->FunctionType;
14216 
14217     // Otherwise, make the minimal modifications to the function type.
14218     } else {
14219       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14220       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14221       EPI.TypeQuals = Qualifiers();
14222       EPI.ExtInfo = Ext;
14223       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14224     }
14225 
14226   // If we don't have a function type, just build one from nothing.
14227   } else {
14228     FunctionProtoType::ExtProtoInfo EPI;
14229     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14230     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14231   }
14232 
14233   DiagnoseUnusedParameters(BD->parameters());
14234   BlockTy = Context.getBlockPointerType(BlockTy);
14235 
14236   // If needed, diagnose invalid gotos and switches in the block.
14237   if (getCurFunction()->NeedsScopeChecking() &&
14238       !PP.isCodeCompletionEnabled())
14239     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14240 
14241   BD->setBody(cast<CompoundStmt>(Body));
14242 
14243   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14244     DiagnoseUnguardedAvailabilityViolations(BD);
14245 
14246   // Try to apply the named return value optimization. We have to check again
14247   // if we can do this, though, because blocks keep return statements around
14248   // to deduce an implicit return type.
14249   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14250       !BD->isDependentContext())
14251     computeNRVO(Body, BSI);
14252 
14253   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14254       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14255     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14256                           NTCUK_Destruct|NTCUK_Copy);
14257 
14258   PopDeclContext();
14259 
14260   // Pop the block scope now but keep it alive to the end of this function.
14261   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14262   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14263 
14264   // Set the captured variables on the block.
14265   SmallVector<BlockDecl::Capture, 4> Captures;
14266   for (Capture &Cap : BSI->Captures) {
14267     if (Cap.isInvalid() || Cap.isThisCapture())
14268       continue;
14269 
14270     VarDecl *Var = Cap.getVariable();
14271     Expr *CopyExpr = nullptr;
14272     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14273       if (const RecordType *Record =
14274               Cap.getCaptureType()->getAs<RecordType>()) {
14275         // The capture logic needs the destructor, so make sure we mark it.
14276         // Usually this is unnecessary because most local variables have
14277         // their destructors marked at declaration time, but parameters are
14278         // an exception because it's technically only the call site that
14279         // actually requires the destructor.
14280         if (isa<ParmVarDecl>(Var))
14281           FinalizeVarWithDestructor(Var, Record);
14282 
14283         // Enter a separate potentially-evaluated context while building block
14284         // initializers to isolate their cleanups from those of the block
14285         // itself.
14286         // FIXME: Is this appropriate even when the block itself occurs in an
14287         // unevaluated operand?
14288         EnterExpressionEvaluationContext EvalContext(
14289             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14290 
14291         SourceLocation Loc = Cap.getLocation();
14292 
14293         ExprResult Result = BuildDeclarationNameExpr(
14294             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14295 
14296         // According to the blocks spec, the capture of a variable from
14297         // the stack requires a const copy constructor.  This is not true
14298         // of the copy/move done to move a __block variable to the heap.
14299         if (!Result.isInvalid() &&
14300             !Result.get()->getType().isConstQualified()) {
14301           Result = ImpCastExprToType(Result.get(),
14302                                      Result.get()->getType().withConst(),
14303                                      CK_NoOp, VK_LValue);
14304         }
14305 
14306         if (!Result.isInvalid()) {
14307           Result = PerformCopyInitialization(
14308               InitializedEntity::InitializeBlock(Var->getLocation(),
14309                                                  Cap.getCaptureType(), false),
14310               Loc, Result.get());
14311         }
14312 
14313         // Build a full-expression copy expression if initialization
14314         // succeeded and used a non-trivial constructor.  Recover from
14315         // errors by pretending that the copy isn't necessary.
14316         if (!Result.isInvalid() &&
14317             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14318                 ->isTrivial()) {
14319           Result = MaybeCreateExprWithCleanups(Result);
14320           CopyExpr = Result.get();
14321         }
14322       }
14323     }
14324 
14325     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14326                               CopyExpr);
14327     Captures.push_back(NewCap);
14328   }
14329   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14330 
14331   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14332 
14333   // If the block isn't obviously global, i.e. it captures anything at
14334   // all, then we need to do a few things in the surrounding context:
14335   if (Result->getBlockDecl()->hasCaptures()) {
14336     // First, this expression has a new cleanup object.
14337     ExprCleanupObjects.push_back(Result->getBlockDecl());
14338     Cleanup.setExprNeedsCleanups(true);
14339 
14340     // It also gets a branch-protected scope if any of the captured
14341     // variables needs destruction.
14342     for (const auto &CI : Result->getBlockDecl()->captures()) {
14343       const VarDecl *var = CI.getVariable();
14344       if (var->getType().isDestructedType() != QualType::DK_none) {
14345         setFunctionHasBranchProtectedScope();
14346         break;
14347       }
14348     }
14349   }
14350 
14351   if (getCurFunction())
14352     getCurFunction()->addBlock(BD);
14353 
14354   return Result;
14355 }
14356 
14357 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14358                             SourceLocation RPLoc) {
14359   TypeSourceInfo *TInfo;
14360   GetTypeFromParser(Ty, &TInfo);
14361   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14362 }
14363 
14364 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14365                                 Expr *E, TypeSourceInfo *TInfo,
14366                                 SourceLocation RPLoc) {
14367   Expr *OrigExpr = E;
14368   bool IsMS = false;
14369 
14370   // CUDA device code does not support varargs.
14371   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14372     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14373       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14374       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14375         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14376     }
14377   }
14378 
14379   // NVPTX does not support va_arg expression.
14380   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14381       Context.getTargetInfo().getTriple().isNVPTX())
14382     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14383 
14384   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14385   // as Microsoft ABI on an actual Microsoft platform, where
14386   // __builtin_ms_va_list and __builtin_va_list are the same.)
14387   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14388       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14389     QualType MSVaListType = Context.getBuiltinMSVaListType();
14390     if (Context.hasSameType(MSVaListType, E->getType())) {
14391       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14392         return ExprError();
14393       IsMS = true;
14394     }
14395   }
14396 
14397   // Get the va_list type
14398   QualType VaListType = Context.getBuiltinVaListType();
14399   if (!IsMS) {
14400     if (VaListType->isArrayType()) {
14401       // Deal with implicit array decay; for example, on x86-64,
14402       // va_list is an array, but it's supposed to decay to
14403       // a pointer for va_arg.
14404       VaListType = Context.getArrayDecayedType(VaListType);
14405       // Make sure the input expression also decays appropriately.
14406       ExprResult Result = UsualUnaryConversions(E);
14407       if (Result.isInvalid())
14408         return ExprError();
14409       E = Result.get();
14410     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14411       // If va_list is a record type and we are compiling in C++ mode,
14412       // check the argument using reference binding.
14413       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14414           Context, Context.getLValueReferenceType(VaListType), false);
14415       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14416       if (Init.isInvalid())
14417         return ExprError();
14418       E = Init.getAs<Expr>();
14419     } else {
14420       // Otherwise, the va_list argument must be an l-value because
14421       // it is modified by va_arg.
14422       if (!E->isTypeDependent() &&
14423           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14424         return ExprError();
14425     }
14426   }
14427 
14428   if (!IsMS && !E->isTypeDependent() &&
14429       !Context.hasSameType(VaListType, E->getType()))
14430     return ExprError(
14431         Diag(E->getBeginLoc(),
14432              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14433         << OrigExpr->getType() << E->getSourceRange());
14434 
14435   if (!TInfo->getType()->isDependentType()) {
14436     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14437                             diag::err_second_parameter_to_va_arg_incomplete,
14438                             TInfo->getTypeLoc()))
14439       return ExprError();
14440 
14441     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14442                                TInfo->getType(),
14443                                diag::err_second_parameter_to_va_arg_abstract,
14444                                TInfo->getTypeLoc()))
14445       return ExprError();
14446 
14447     if (!TInfo->getType().isPODType(Context)) {
14448       Diag(TInfo->getTypeLoc().getBeginLoc(),
14449            TInfo->getType()->isObjCLifetimeType()
14450              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14451              : diag::warn_second_parameter_to_va_arg_not_pod)
14452         << TInfo->getType()
14453         << TInfo->getTypeLoc().getSourceRange();
14454     }
14455 
14456     // Check for va_arg where arguments of the given type will be promoted
14457     // (i.e. this va_arg is guaranteed to have undefined behavior).
14458     QualType PromoteType;
14459     if (TInfo->getType()->isPromotableIntegerType()) {
14460       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14461       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14462         PromoteType = QualType();
14463     }
14464     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14465       PromoteType = Context.DoubleTy;
14466     if (!PromoteType.isNull())
14467       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14468                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14469                           << TInfo->getType()
14470                           << PromoteType
14471                           << TInfo->getTypeLoc().getSourceRange());
14472   }
14473 
14474   QualType T = TInfo->getType().getNonLValueExprType(Context);
14475   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14476 }
14477 
14478 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14479   // The type of __null will be int or long, depending on the size of
14480   // pointers on the target.
14481   QualType Ty;
14482   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14483   if (pw == Context.getTargetInfo().getIntWidth())
14484     Ty = Context.IntTy;
14485   else if (pw == Context.getTargetInfo().getLongWidth())
14486     Ty = Context.LongTy;
14487   else if (pw == Context.getTargetInfo().getLongLongWidth())
14488     Ty = Context.LongLongTy;
14489   else {
14490     llvm_unreachable("I don't know size of pointer!");
14491   }
14492 
14493   return new (Context) GNUNullExpr(Ty, TokenLoc);
14494 }
14495 
14496 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14497                                     SourceLocation BuiltinLoc,
14498                                     SourceLocation RPLoc) {
14499   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14500 }
14501 
14502 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14503                                     SourceLocation BuiltinLoc,
14504                                     SourceLocation RPLoc,
14505                                     DeclContext *ParentContext) {
14506   return new (Context)
14507       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14508 }
14509 
14510 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14511                                               bool Diagnose) {
14512   if (!getLangOpts().ObjC)
14513     return false;
14514 
14515   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14516   if (!PT)
14517     return false;
14518 
14519   if (!PT->isObjCIdType()) {
14520     // Check if the destination is the 'NSString' interface.
14521     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14522     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14523       return false;
14524   }
14525 
14526   // Ignore any parens, implicit casts (should only be
14527   // array-to-pointer decays), and not-so-opaque values.  The last is
14528   // important for making this trigger for property assignments.
14529   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14530   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14531     if (OV->getSourceExpr())
14532       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14533 
14534   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14535   if (!SL || !SL->isAscii())
14536     return false;
14537   if (Diagnose) {
14538     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14539         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14540     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14541   }
14542   return true;
14543 }
14544 
14545 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14546                                               const Expr *SrcExpr) {
14547   if (!DstType->isFunctionPointerType() ||
14548       !SrcExpr->getType()->isFunctionType())
14549     return false;
14550 
14551   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14552   if (!DRE)
14553     return false;
14554 
14555   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14556   if (!FD)
14557     return false;
14558 
14559   return !S.checkAddressOfFunctionIsAvailable(FD,
14560                                               /*Complain=*/true,
14561                                               SrcExpr->getBeginLoc());
14562 }
14563 
14564 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14565                                     SourceLocation Loc,
14566                                     QualType DstType, QualType SrcType,
14567                                     Expr *SrcExpr, AssignmentAction Action,
14568                                     bool *Complained) {
14569   if (Complained)
14570     *Complained = false;
14571 
14572   // Decode the result (notice that AST's are still created for extensions).
14573   bool CheckInferredResultType = false;
14574   bool isInvalid = false;
14575   unsigned DiagKind = 0;
14576   FixItHint Hint;
14577   ConversionFixItGenerator ConvHints;
14578   bool MayHaveConvFixit = false;
14579   bool MayHaveFunctionDiff = false;
14580   const ObjCInterfaceDecl *IFace = nullptr;
14581   const ObjCProtocolDecl *PDecl = nullptr;
14582 
14583   switch (ConvTy) {
14584   case Compatible:
14585       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14586       return false;
14587 
14588   case PointerToInt:
14589     DiagKind = diag::ext_typecheck_convert_pointer_int;
14590     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14591     MayHaveConvFixit = true;
14592     break;
14593   case IntToPointer:
14594     DiagKind = diag::ext_typecheck_convert_int_pointer;
14595     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14596     MayHaveConvFixit = true;
14597     break;
14598   case IncompatiblePointer:
14599     if (Action == AA_Passing_CFAudited)
14600       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14601     else if (SrcType->isFunctionPointerType() &&
14602              DstType->isFunctionPointerType())
14603       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14604     else
14605       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14606 
14607     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14608       SrcType->isObjCObjectPointerType();
14609     if (Hint.isNull() && !CheckInferredResultType) {
14610       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14611     }
14612     else if (CheckInferredResultType) {
14613       SrcType = SrcType.getUnqualifiedType();
14614       DstType = DstType.getUnqualifiedType();
14615     }
14616     MayHaveConvFixit = true;
14617     break;
14618   case IncompatiblePointerSign:
14619     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14620     break;
14621   case FunctionVoidPointer:
14622     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14623     break;
14624   case IncompatiblePointerDiscardsQualifiers: {
14625     // Perform array-to-pointer decay if necessary.
14626     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14627 
14628     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14629     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14630     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14631       DiagKind = diag::err_typecheck_incompatible_address_space;
14632       break;
14633 
14634     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14635       DiagKind = diag::err_typecheck_incompatible_ownership;
14636       break;
14637     }
14638 
14639     llvm_unreachable("unknown error case for discarding qualifiers!");
14640     // fallthrough
14641   }
14642   case CompatiblePointerDiscardsQualifiers:
14643     // If the qualifiers lost were because we were applying the
14644     // (deprecated) C++ conversion from a string literal to a char*
14645     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14646     // Ideally, this check would be performed in
14647     // checkPointerTypesForAssignment. However, that would require a
14648     // bit of refactoring (so that the second argument is an
14649     // expression, rather than a type), which should be done as part
14650     // of a larger effort to fix checkPointerTypesForAssignment for
14651     // C++ semantics.
14652     if (getLangOpts().CPlusPlus &&
14653         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14654       return false;
14655     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14656     break;
14657   case IncompatibleNestedPointerQualifiers:
14658     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14659     break;
14660   case IncompatibleNestedPointerAddressSpaceMismatch:
14661     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14662     break;
14663   case IntToBlockPointer:
14664     DiagKind = diag::err_int_to_block_pointer;
14665     break;
14666   case IncompatibleBlockPointer:
14667     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14668     break;
14669   case IncompatibleObjCQualifiedId: {
14670     if (SrcType->isObjCQualifiedIdType()) {
14671       const ObjCObjectPointerType *srcOPT =
14672                 SrcType->castAs<ObjCObjectPointerType>();
14673       for (auto *srcProto : srcOPT->quals()) {
14674         PDecl = srcProto;
14675         break;
14676       }
14677       if (const ObjCInterfaceType *IFaceT =
14678             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14679         IFace = IFaceT->getDecl();
14680     }
14681     else if (DstType->isObjCQualifiedIdType()) {
14682       const ObjCObjectPointerType *dstOPT =
14683         DstType->castAs<ObjCObjectPointerType>();
14684       for (auto *dstProto : dstOPT->quals()) {
14685         PDecl = dstProto;
14686         break;
14687       }
14688       if (const ObjCInterfaceType *IFaceT =
14689             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14690         IFace = IFaceT->getDecl();
14691     }
14692     DiagKind = diag::warn_incompatible_qualified_id;
14693     break;
14694   }
14695   case IncompatibleVectors:
14696     DiagKind = diag::warn_incompatible_vectors;
14697     break;
14698   case IncompatibleObjCWeakRef:
14699     DiagKind = diag::err_arc_weak_unavailable_assign;
14700     break;
14701   case Incompatible:
14702     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14703       if (Complained)
14704         *Complained = true;
14705       return true;
14706     }
14707 
14708     DiagKind = diag::err_typecheck_convert_incompatible;
14709     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14710     MayHaveConvFixit = true;
14711     isInvalid = true;
14712     MayHaveFunctionDiff = true;
14713     break;
14714   }
14715 
14716   QualType FirstType, SecondType;
14717   switch (Action) {
14718   case AA_Assigning:
14719   case AA_Initializing:
14720     // The destination type comes first.
14721     FirstType = DstType;
14722     SecondType = SrcType;
14723     break;
14724 
14725   case AA_Returning:
14726   case AA_Passing:
14727   case AA_Passing_CFAudited:
14728   case AA_Converting:
14729   case AA_Sending:
14730   case AA_Casting:
14731     // The source type comes first.
14732     FirstType = SrcType;
14733     SecondType = DstType;
14734     break;
14735   }
14736 
14737   PartialDiagnostic FDiag = PDiag(DiagKind);
14738   if (Action == AA_Passing_CFAudited)
14739     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14740   else
14741     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14742 
14743   // If we can fix the conversion, suggest the FixIts.
14744   assert(ConvHints.isNull() || Hint.isNull());
14745   if (!ConvHints.isNull()) {
14746     for (FixItHint &H : ConvHints.Hints)
14747       FDiag << H;
14748   } else {
14749     FDiag << Hint;
14750   }
14751   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14752 
14753   if (MayHaveFunctionDiff)
14754     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14755 
14756   Diag(Loc, FDiag);
14757   if (DiagKind == diag::warn_incompatible_qualified_id &&
14758       PDecl && IFace && !IFace->hasDefinition())
14759       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14760         << IFace << PDecl;
14761 
14762   if (SecondType == Context.OverloadTy)
14763     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14764                               FirstType, /*TakingAddress=*/true);
14765 
14766   if (CheckInferredResultType)
14767     EmitRelatedResultTypeNote(SrcExpr);
14768 
14769   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14770     EmitRelatedResultTypeNoteForReturn(DstType);
14771 
14772   if (Complained)
14773     *Complained = true;
14774   return isInvalid;
14775 }
14776 
14777 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14778                                                  llvm::APSInt *Result) {
14779   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14780   public:
14781     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14782       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14783     }
14784   } Diagnoser;
14785 
14786   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14787 }
14788 
14789 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14790                                                  llvm::APSInt *Result,
14791                                                  unsigned DiagID,
14792                                                  bool AllowFold) {
14793   class IDDiagnoser : public VerifyICEDiagnoser {
14794     unsigned DiagID;
14795 
14796   public:
14797     IDDiagnoser(unsigned DiagID)
14798       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14799 
14800     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14801       S.Diag(Loc, DiagID) << SR;
14802     }
14803   } Diagnoser(DiagID);
14804 
14805   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14806 }
14807 
14808 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14809                                             SourceRange SR) {
14810   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14811 }
14812 
14813 ExprResult
14814 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14815                                       VerifyICEDiagnoser &Diagnoser,
14816                                       bool AllowFold) {
14817   SourceLocation DiagLoc = E->getBeginLoc();
14818 
14819   if (getLangOpts().CPlusPlus11) {
14820     // C++11 [expr.const]p5:
14821     //   If an expression of literal class type is used in a context where an
14822     //   integral constant expression is required, then that class type shall
14823     //   have a single non-explicit conversion function to an integral or
14824     //   unscoped enumeration type
14825     ExprResult Converted;
14826     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14827     public:
14828       CXX11ConvertDiagnoser(bool Silent)
14829           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14830                                 Silent, true) {}
14831 
14832       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14833                                            QualType T) override {
14834         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14835       }
14836 
14837       SemaDiagnosticBuilder diagnoseIncomplete(
14838           Sema &S, SourceLocation Loc, QualType T) override {
14839         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14840       }
14841 
14842       SemaDiagnosticBuilder diagnoseExplicitConv(
14843           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14844         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14845       }
14846 
14847       SemaDiagnosticBuilder noteExplicitConv(
14848           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14849         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14850                  << ConvTy->isEnumeralType() << ConvTy;
14851       }
14852 
14853       SemaDiagnosticBuilder diagnoseAmbiguous(
14854           Sema &S, SourceLocation Loc, QualType T) override {
14855         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14856       }
14857 
14858       SemaDiagnosticBuilder noteAmbiguous(
14859           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14860         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14861                  << ConvTy->isEnumeralType() << ConvTy;
14862       }
14863 
14864       SemaDiagnosticBuilder diagnoseConversion(
14865           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14866         llvm_unreachable("conversion functions are permitted");
14867       }
14868     } ConvertDiagnoser(Diagnoser.Suppress);
14869 
14870     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14871                                                     ConvertDiagnoser);
14872     if (Converted.isInvalid())
14873       return Converted;
14874     E = Converted.get();
14875     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14876       return ExprError();
14877   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14878     // An ICE must be of integral or unscoped enumeration type.
14879     if (!Diagnoser.Suppress)
14880       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14881     return ExprError();
14882   }
14883 
14884   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14885   // in the non-ICE case.
14886   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14887     if (Result)
14888       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14889     if (!isa<ConstantExpr>(E))
14890       E = ConstantExpr::Create(Context, E);
14891     return E;
14892   }
14893 
14894   Expr::EvalResult EvalResult;
14895   SmallVector<PartialDiagnosticAt, 8> Notes;
14896   EvalResult.Diag = &Notes;
14897 
14898   // Try to evaluate the expression, and produce diagnostics explaining why it's
14899   // not a constant expression as a side-effect.
14900   bool Folded =
14901       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14902       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14903 
14904   if (!isa<ConstantExpr>(E))
14905     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14906 
14907   // In C++11, we can rely on diagnostics being produced for any expression
14908   // which is not a constant expression. If no diagnostics were produced, then
14909   // this is a constant expression.
14910   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14911     if (Result)
14912       *Result = EvalResult.Val.getInt();
14913     return E;
14914   }
14915 
14916   // If our only note is the usual "invalid subexpression" note, just point
14917   // the caret at its location rather than producing an essentially
14918   // redundant note.
14919   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14920         diag::note_invalid_subexpr_in_const_expr) {
14921     DiagLoc = Notes[0].first;
14922     Notes.clear();
14923   }
14924 
14925   if (!Folded || !AllowFold) {
14926     if (!Diagnoser.Suppress) {
14927       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14928       for (const PartialDiagnosticAt &Note : Notes)
14929         Diag(Note.first, Note.second);
14930     }
14931 
14932     return ExprError();
14933   }
14934 
14935   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14936   for (const PartialDiagnosticAt &Note : Notes)
14937     Diag(Note.first, Note.second);
14938 
14939   if (Result)
14940     *Result = EvalResult.Val.getInt();
14941   return E;
14942 }
14943 
14944 namespace {
14945   // Handle the case where we conclude a expression which we speculatively
14946   // considered to be unevaluated is actually evaluated.
14947   class TransformToPE : public TreeTransform<TransformToPE> {
14948     typedef TreeTransform<TransformToPE> BaseTransform;
14949 
14950   public:
14951     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14952 
14953     // Make sure we redo semantic analysis
14954     bool AlwaysRebuild() { return true; }
14955     bool ReplacingOriginal() { return true; }
14956 
14957     // We need to special-case DeclRefExprs referring to FieldDecls which
14958     // are not part of a member pointer formation; normal TreeTransforming
14959     // doesn't catch this case because of the way we represent them in the AST.
14960     // FIXME: This is a bit ugly; is it really the best way to handle this
14961     // case?
14962     //
14963     // Error on DeclRefExprs referring to FieldDecls.
14964     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14965       if (isa<FieldDecl>(E->getDecl()) &&
14966           !SemaRef.isUnevaluatedContext())
14967         return SemaRef.Diag(E->getLocation(),
14968                             diag::err_invalid_non_static_member_use)
14969             << E->getDecl() << E->getSourceRange();
14970 
14971       return BaseTransform::TransformDeclRefExpr(E);
14972     }
14973 
14974     // Exception: filter out member pointer formation
14975     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14976       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14977         return E;
14978 
14979       return BaseTransform::TransformUnaryOperator(E);
14980     }
14981 
14982     // The body of a lambda-expression is in a separate expression evaluation
14983     // context so never needs to be transformed.
14984     // FIXME: Ideally we wouldn't transform the closure type either, and would
14985     // just recreate the capture expressions and lambda expression.
14986     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
14987       return SkipLambdaBody(E, Body);
14988     }
14989   };
14990 }
14991 
14992 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14993   assert(isUnevaluatedContext() &&
14994          "Should only transform unevaluated expressions");
14995   ExprEvalContexts.back().Context =
14996       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14997   if (isUnevaluatedContext())
14998     return E;
14999   return TransformToPE(*this).TransformExpr(E);
15000 }
15001 
15002 void
15003 Sema::PushExpressionEvaluationContext(
15004     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15005     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15006   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15007                                 LambdaContextDecl, ExprContext);
15008   Cleanup.reset();
15009   if (!MaybeODRUseExprs.empty())
15010     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15011 }
15012 
15013 void
15014 Sema::PushExpressionEvaluationContext(
15015     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15016     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15017   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15018   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15019 }
15020 
15021 namespace {
15022 
15023 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15024   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15025   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15026     if (E->getOpcode() == UO_Deref)
15027       return CheckPossibleDeref(S, E->getSubExpr());
15028   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15029     return CheckPossibleDeref(S, E->getBase());
15030   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15031     return CheckPossibleDeref(S, E->getBase());
15032   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15033     QualType Inner;
15034     QualType Ty = E->getType();
15035     if (const auto *Ptr = Ty->getAs<PointerType>())
15036       Inner = Ptr->getPointeeType();
15037     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15038       Inner = Arr->getElementType();
15039     else
15040       return nullptr;
15041 
15042     if (Inner->hasAttr(attr::NoDeref))
15043       return E;
15044   }
15045   return nullptr;
15046 }
15047 
15048 } // namespace
15049 
15050 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15051   for (const Expr *E : Rec.PossibleDerefs) {
15052     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15053     if (DeclRef) {
15054       const ValueDecl *Decl = DeclRef->getDecl();
15055       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15056           << Decl->getName() << E->getSourceRange();
15057       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15058     } else {
15059       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15060           << E->getSourceRange();
15061     }
15062   }
15063   Rec.PossibleDerefs.clear();
15064 }
15065 
15066 void Sema::PopExpressionEvaluationContext() {
15067   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15068   unsigned NumTypos = Rec.NumTypos;
15069 
15070   if (!Rec.Lambdas.empty()) {
15071     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15072     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15073         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15074       unsigned D;
15075       if (Rec.isUnevaluated()) {
15076         // C++11 [expr.prim.lambda]p2:
15077         //   A lambda-expression shall not appear in an unevaluated operand
15078         //   (Clause 5).
15079         D = diag::err_lambda_unevaluated_operand;
15080       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15081         // C++1y [expr.const]p2:
15082         //   A conditional-expression e is a core constant expression unless the
15083         //   evaluation of e, following the rules of the abstract machine, would
15084         //   evaluate [...] a lambda-expression.
15085         D = diag::err_lambda_in_constant_expression;
15086       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15087         // C++17 [expr.prim.lamda]p2:
15088         // A lambda-expression shall not appear [...] in a template-argument.
15089         D = diag::err_lambda_in_invalid_context;
15090       } else
15091         llvm_unreachable("Couldn't infer lambda error message.");
15092 
15093       for (const auto *L : Rec.Lambdas)
15094         Diag(L->getBeginLoc(), D);
15095     }
15096   }
15097 
15098   WarnOnPendingNoDerefs(Rec);
15099 
15100   // When are coming out of an unevaluated context, clear out any
15101   // temporaries that we may have created as part of the evaluation of
15102   // the expression in that context: they aren't relevant because they
15103   // will never be constructed.
15104   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15105     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15106                              ExprCleanupObjects.end());
15107     Cleanup = Rec.ParentCleanup;
15108     CleanupVarDeclMarking();
15109     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15110   // Otherwise, merge the contexts together.
15111   } else {
15112     Cleanup.mergeFrom(Rec.ParentCleanup);
15113     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15114                             Rec.SavedMaybeODRUseExprs.end());
15115   }
15116 
15117   // Pop the current expression evaluation context off the stack.
15118   ExprEvalContexts.pop_back();
15119 
15120   // The global expression evaluation context record is never popped.
15121   ExprEvalContexts.back().NumTypos += NumTypos;
15122 }
15123 
15124 void Sema::DiscardCleanupsInEvaluationContext() {
15125   ExprCleanupObjects.erase(
15126          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15127          ExprCleanupObjects.end());
15128   Cleanup.reset();
15129   MaybeODRUseExprs.clear();
15130 }
15131 
15132 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15133   ExprResult Result = CheckPlaceholderExpr(E);
15134   if (Result.isInvalid())
15135     return ExprError();
15136   E = Result.get();
15137   if (!E->getType()->isVariablyModifiedType())
15138     return E;
15139   return TransformToPotentiallyEvaluated(E);
15140 }
15141 
15142 /// Are we in a context that is potentially constant evaluated per C++20
15143 /// [expr.const]p12?
15144 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15145   /// C++2a [expr.const]p12:
15146   //   An expression or conversion is potentially constant evaluated if it is
15147   switch (SemaRef.ExprEvalContexts.back().Context) {
15148     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15149       // -- a manifestly constant-evaluated expression,
15150     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15151     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15152     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15153       // -- a potentially-evaluated expression,
15154     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15155       // -- an immediate subexpression of a braced-init-list,
15156 
15157       // -- [FIXME] an expression of the form & cast-expression that occurs
15158       //    within a templated entity
15159       // -- a subexpression of one of the above that is not a subexpression of
15160       // a nested unevaluated operand.
15161       return true;
15162 
15163     case Sema::ExpressionEvaluationContext::Unevaluated:
15164     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15165       // Expressions in this context are never evaluated.
15166       return false;
15167   }
15168   llvm_unreachable("Invalid context");
15169 }
15170 
15171 /// Return true if this function has a calling convention that requires mangling
15172 /// in the size of the parameter pack.
15173 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15174   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15175   // we don't need parameter type sizes.
15176   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15177   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
15178                             TT.getArch() != llvm::Triple::x86_64))
15179     return false;
15180 
15181   // If this is C++ and this isn't an extern "C" function, parameters do not
15182   // need to be complete. In this case, C++ mangling will apply, which doesn't
15183   // use the size of the parameters.
15184   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15185     return false;
15186 
15187   // Stdcall, fastcall, and vectorcall need this special treatment.
15188   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15189   switch (CC) {
15190   case CC_X86StdCall:
15191   case CC_X86FastCall:
15192   case CC_X86VectorCall:
15193     return true;
15194   default:
15195     break;
15196   }
15197   return false;
15198 }
15199 
15200 /// Require that all of the parameter types of function be complete. Normally,
15201 /// parameter types are only required to be complete when a function is called
15202 /// or defined, but to mangle functions with certain calling conventions, the
15203 /// mangler needs to know the size of the parameter list. In this situation,
15204 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15205 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15206 /// result in a linker error. Clang doesn't implement this behavior, and instead
15207 /// attempts to error at compile time.
15208 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15209                                                   SourceLocation Loc) {
15210   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15211     FunctionDecl *FD;
15212     ParmVarDecl *Param;
15213 
15214   public:
15215     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15216         : FD(FD), Param(Param) {}
15217 
15218     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15219       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15220       StringRef CCName;
15221       switch (CC) {
15222       case CC_X86StdCall:
15223         CCName = "stdcall";
15224         break;
15225       case CC_X86FastCall:
15226         CCName = "fastcall";
15227         break;
15228       case CC_X86VectorCall:
15229         CCName = "vectorcall";
15230         break;
15231       default:
15232         llvm_unreachable("CC does not need mangling");
15233       }
15234 
15235       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15236           << Param->getDeclName() << FD->getDeclName() << CCName;
15237     }
15238   };
15239 
15240   for (ParmVarDecl *Param : FD->parameters()) {
15241     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15242     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15243   }
15244 }
15245 
15246 namespace {
15247 enum class OdrUseContext {
15248   /// Declarations in this context are not odr-used.
15249   None,
15250   /// Declarations in this context are formally odr-used, but this is a
15251   /// dependent context.
15252   Dependent,
15253   /// Declarations in this context are odr-used but not actually used (yet).
15254   FormallyOdrUsed,
15255   /// Declarations in this context are used.
15256   Used
15257 };
15258 }
15259 
15260 /// Are we within a context in which references to resolved functions or to
15261 /// variables result in odr-use?
15262 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15263   OdrUseContext Result;
15264 
15265   switch (SemaRef.ExprEvalContexts.back().Context) {
15266     case Sema::ExpressionEvaluationContext::Unevaluated:
15267     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15268     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15269       return OdrUseContext::None;
15270 
15271     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15272     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15273       Result = OdrUseContext::Used;
15274       break;
15275 
15276     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15277       Result = OdrUseContext::FormallyOdrUsed;
15278       break;
15279 
15280     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15281       // A default argument formally results in odr-use, but doesn't actually
15282       // result in a use in any real sense until it itself is used.
15283       Result = OdrUseContext::FormallyOdrUsed;
15284       break;
15285   }
15286 
15287   if (SemaRef.CurContext->isDependentContext())
15288     return OdrUseContext::Dependent;
15289 
15290   return Result;
15291 }
15292 
15293 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15294   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
15295   return Func->isConstexpr() &&
15296          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
15297 }
15298 
15299 /// Mark a function referenced, and check whether it is odr-used
15300 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15301 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15302                                   bool MightBeOdrUse) {
15303   assert(Func && "No function?");
15304 
15305   Func->setReferenced();
15306 
15307   // Recursive functions aren't really used until they're used from some other
15308   // context.
15309   bool IsRecursiveCall = CurContext == Func;
15310 
15311   // C++11 [basic.def.odr]p3:
15312   //   A function whose name appears as a potentially-evaluated expression is
15313   //   odr-used if it is the unique lookup result or the selected member of a
15314   //   set of overloaded functions [...].
15315   //
15316   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15317   // can just check that here.
15318   OdrUseContext OdrUse =
15319       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15320   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15321     OdrUse = OdrUseContext::FormallyOdrUsed;
15322 
15323   // Trivial default constructors and destructors are never actually used.
15324   // FIXME: What about other special members?
15325   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15326       OdrUse == OdrUseContext::Used) {
15327     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15328       if (Constructor->isDefaultConstructor())
15329         OdrUse = OdrUseContext::FormallyOdrUsed;
15330     if (isa<CXXDestructorDecl>(Func))
15331       OdrUse = OdrUseContext::FormallyOdrUsed;
15332   }
15333 
15334   // C++20 [expr.const]p12:
15335   //   A function [...] is needed for constant evaluation if it is [...] a
15336   //   constexpr function that is named by an expression that is potentially
15337   //   constant evaluated
15338   bool NeededForConstantEvaluation =
15339       isPotentiallyConstantEvaluatedContext(*this) &&
15340       isImplicitlyDefinableConstexprFunction(Func);
15341 
15342   // Determine whether we require a function definition to exist, per
15343   // C++11 [temp.inst]p3:
15344   //   Unless a function template specialization has been explicitly
15345   //   instantiated or explicitly specialized, the function template
15346   //   specialization is implicitly instantiated when the specialization is
15347   //   referenced in a context that requires a function definition to exist.
15348   // C++20 [temp.inst]p7:
15349   //   The existence of a definition of a [...] function is considered to
15350   //   affect the semantics of the program if the [...] function is needed for
15351   //   constant evaluation by an expression
15352   // C++20 [basic.def.odr]p10:
15353   //   Every program shall contain exactly one definition of every non-inline
15354   //   function or variable that is odr-used in that program outside of a
15355   //   discarded statement
15356   // C++20 [special]p1:
15357   //   The implementation will implicitly define [defaulted special members]
15358   //   if they are odr-used or needed for constant evaluation.
15359   //
15360   // Note that we skip the implicit instantiation of templates that are only
15361   // used in unused default arguments or by recursive calls to themselves.
15362   // This is formally non-conforming, but seems reasonable in practice.
15363   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15364                                              NeededForConstantEvaluation);
15365 
15366   // C++14 [temp.expl.spec]p6:
15367   //   If a template [...] is explicitly specialized then that specialization
15368   //   shall be declared before the first use of that specialization that would
15369   //   cause an implicit instantiation to take place, in every translation unit
15370   //   in which such a use occurs
15371   if (NeedDefinition &&
15372       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15373        Func->getMemberSpecializationInfo()))
15374     checkSpecializationVisibility(Loc, Func);
15375 
15376   // C++14 [except.spec]p17:
15377   //   An exception-specification is considered to be needed when:
15378   //   - the function is odr-used or, if it appears in an unevaluated operand,
15379   //     would be odr-used if the expression were potentially-evaluated;
15380   //
15381   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15382   // function is a pure virtual function we're calling, and in that case the
15383   // function was selected by overload resolution and we need to resolve its
15384   // exception specification for a different reason.
15385   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15386   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15387     ResolveExceptionSpec(Loc, FPT);
15388 
15389   if (getLangOpts().CUDA)
15390     CheckCUDACall(Loc, Func);
15391 
15392   // If we need a definition, try to create one.
15393   if (NeedDefinition && !Func->getBody()) {
15394     runWithSufficientStackSpace(Loc, [&] {
15395       if (CXXConstructorDecl *Constructor =
15396               dyn_cast<CXXConstructorDecl>(Func)) {
15397         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15398         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15399           if (Constructor->isDefaultConstructor()) {
15400             if (Constructor->isTrivial() &&
15401                 !Constructor->hasAttr<DLLExportAttr>())
15402               return;
15403             DefineImplicitDefaultConstructor(Loc, Constructor);
15404           } else if (Constructor->isCopyConstructor()) {
15405             DefineImplicitCopyConstructor(Loc, Constructor);
15406           } else if (Constructor->isMoveConstructor()) {
15407             DefineImplicitMoveConstructor(Loc, Constructor);
15408           }
15409         } else if (Constructor->getInheritedConstructor()) {
15410           DefineInheritingConstructor(Loc, Constructor);
15411         }
15412       } else if (CXXDestructorDecl *Destructor =
15413                      dyn_cast<CXXDestructorDecl>(Func)) {
15414         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15415         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15416           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15417             return;
15418           DefineImplicitDestructor(Loc, Destructor);
15419         }
15420         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15421           MarkVTableUsed(Loc, Destructor->getParent());
15422       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15423         if (MethodDecl->isOverloadedOperator() &&
15424             MethodDecl->getOverloadedOperator() == OO_Equal) {
15425           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15426           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15427             if (MethodDecl->isCopyAssignmentOperator())
15428               DefineImplicitCopyAssignment(Loc, MethodDecl);
15429             else if (MethodDecl->isMoveAssignmentOperator())
15430               DefineImplicitMoveAssignment(Loc, MethodDecl);
15431           }
15432         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15433                    MethodDecl->getParent()->isLambda()) {
15434           CXXConversionDecl *Conversion =
15435               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15436           if (Conversion->isLambdaToBlockPointerConversion())
15437             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15438           else
15439             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15440         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15441           MarkVTableUsed(Loc, MethodDecl->getParent());
15442       }
15443 
15444       // Implicit instantiation of function templates and member functions of
15445       // class templates.
15446       if (Func->isImplicitlyInstantiable()) {
15447         TemplateSpecializationKind TSK =
15448             Func->getTemplateSpecializationKindForInstantiation();
15449         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15450         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15451         if (FirstInstantiation) {
15452           PointOfInstantiation = Loc;
15453           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15454         } else if (TSK != TSK_ImplicitInstantiation) {
15455           // Use the point of use as the point of instantiation, instead of the
15456           // point of explicit instantiation (which we track as the actual point
15457           // of instantiation). This gives better backtraces in diagnostics.
15458           PointOfInstantiation = Loc;
15459         }
15460 
15461         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15462             Func->isConstexpr()) {
15463           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15464               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15465               CodeSynthesisContexts.size())
15466             PendingLocalImplicitInstantiations.push_back(
15467                 std::make_pair(Func, PointOfInstantiation));
15468           else if (Func->isConstexpr())
15469             // Do not defer instantiations of constexpr functions, to avoid the
15470             // expression evaluator needing to call back into Sema if it sees a
15471             // call to such a function.
15472             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15473           else {
15474             Func->setInstantiationIsPending(true);
15475             PendingInstantiations.push_back(
15476                 std::make_pair(Func, PointOfInstantiation));
15477             // Notify the consumer that a function was implicitly instantiated.
15478             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15479           }
15480         }
15481       } else {
15482         // Walk redefinitions, as some of them may be instantiable.
15483         for (auto i : Func->redecls()) {
15484           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15485             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15486         }
15487       }
15488     });
15489   }
15490 
15491   // If this is the first "real" use, act on that.
15492   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15493     // Keep track of used but undefined functions.
15494     if (!Func->isDefined()) {
15495       if (mightHaveNonExternalLinkage(Func))
15496         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15497       else if (Func->getMostRecentDecl()->isInlined() &&
15498                !LangOpts.GNUInline &&
15499                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15500         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15501       else if (isExternalWithNoLinkageType(Func))
15502         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15503     }
15504 
15505     // Some x86 Windows calling conventions mangle the size of the parameter
15506     // pack into the name. Computing the size of the parameters requires the
15507     // parameter types to be complete. Check that now.
15508     if (funcHasParameterSizeMangling(*this, Func))
15509       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15510 
15511     Func->markUsed(Context);
15512   }
15513 
15514   if (LangOpts.OpenMP) {
15515     markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15516     if (LangOpts.OpenMPIsDevice)
15517       checkOpenMPDeviceFunction(Loc, Func);
15518     else
15519       checkOpenMPHostFunction(Loc, Func);
15520   }
15521 }
15522 
15523 /// Directly mark a variable odr-used. Given a choice, prefer to use
15524 /// MarkVariableReferenced since it does additional checks and then
15525 /// calls MarkVarDeclODRUsed.
15526 /// If the variable must be captured:
15527 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15528 ///  - else capture it in the DeclContext that maps to the
15529 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15530 static void
15531 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15532                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15533   // Keep track of used but undefined variables.
15534   // FIXME: We shouldn't suppress this warning for static data members.
15535   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15536       (!Var->isExternallyVisible() || Var->isInline() ||
15537        SemaRef.isExternalWithNoLinkageType(Var)) &&
15538       !(Var->isStaticDataMember() && Var->hasInit())) {
15539     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15540     if (old.isInvalid())
15541       old = Loc;
15542   }
15543   QualType CaptureType, DeclRefType;
15544   if (SemaRef.LangOpts.OpenMP)
15545     SemaRef.tryCaptureOpenMPLambdas(Var);
15546   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15547     /*EllipsisLoc*/ SourceLocation(),
15548     /*BuildAndDiagnose*/ true,
15549     CaptureType, DeclRefType,
15550     FunctionScopeIndexToStopAt);
15551 
15552   Var->markUsed(SemaRef.Context);
15553 }
15554 
15555 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15556                                              SourceLocation Loc,
15557                                              unsigned CapturingScopeIndex) {
15558   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15559 }
15560 
15561 static void
15562 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15563                                    ValueDecl *var, DeclContext *DC) {
15564   DeclContext *VarDC = var->getDeclContext();
15565 
15566   //  If the parameter still belongs to the translation unit, then
15567   //  we're actually just using one parameter in the declaration of
15568   //  the next.
15569   if (isa<ParmVarDecl>(var) &&
15570       isa<TranslationUnitDecl>(VarDC))
15571     return;
15572 
15573   // For C code, don't diagnose about capture if we're not actually in code
15574   // right now; it's impossible to write a non-constant expression outside of
15575   // function context, so we'll get other (more useful) diagnostics later.
15576   //
15577   // For C++, things get a bit more nasty... it would be nice to suppress this
15578   // diagnostic for certain cases like using a local variable in an array bound
15579   // for a member of a local class, but the correct predicate is not obvious.
15580   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15581     return;
15582 
15583   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15584   unsigned ContextKind = 3; // unknown
15585   if (isa<CXXMethodDecl>(VarDC) &&
15586       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15587     ContextKind = 2;
15588   } else if (isa<FunctionDecl>(VarDC)) {
15589     ContextKind = 0;
15590   } else if (isa<BlockDecl>(VarDC)) {
15591     ContextKind = 1;
15592   }
15593 
15594   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15595     << var << ValueKind << ContextKind << VarDC;
15596   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15597       << var;
15598 
15599   // FIXME: Add additional diagnostic info about class etc. which prevents
15600   // capture.
15601 }
15602 
15603 
15604 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15605                                       bool &SubCapturesAreNested,
15606                                       QualType &CaptureType,
15607                                       QualType &DeclRefType) {
15608    // Check whether we've already captured it.
15609   if (CSI->CaptureMap.count(Var)) {
15610     // If we found a capture, any subcaptures are nested.
15611     SubCapturesAreNested = true;
15612 
15613     // Retrieve the capture type for this variable.
15614     CaptureType = CSI->getCapture(Var).getCaptureType();
15615 
15616     // Compute the type of an expression that refers to this variable.
15617     DeclRefType = CaptureType.getNonReferenceType();
15618 
15619     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15620     // are mutable in the sense that user can change their value - they are
15621     // private instances of the captured declarations.
15622     const Capture &Cap = CSI->getCapture(Var);
15623     if (Cap.isCopyCapture() &&
15624         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15625         !(isa<CapturedRegionScopeInfo>(CSI) &&
15626           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15627       DeclRefType.addConst();
15628     return true;
15629   }
15630   return false;
15631 }
15632 
15633 // Only block literals, captured statements, and lambda expressions can
15634 // capture; other scopes don't work.
15635 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15636                                  SourceLocation Loc,
15637                                  const bool Diagnose, Sema &S) {
15638   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15639     return getLambdaAwareParentOfDeclContext(DC);
15640   else if (Var->hasLocalStorage()) {
15641     if (Diagnose)
15642        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15643   }
15644   return nullptr;
15645 }
15646 
15647 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15648 // certain types of variables (unnamed, variably modified types etc.)
15649 // so check for eligibility.
15650 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15651                                  SourceLocation Loc,
15652                                  const bool Diagnose, Sema &S) {
15653 
15654   bool IsBlock = isa<BlockScopeInfo>(CSI);
15655   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15656 
15657   // Lambdas are not allowed to capture unnamed variables
15658   // (e.g. anonymous unions).
15659   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15660   // assuming that's the intent.
15661   if (IsLambda && !Var->getDeclName()) {
15662     if (Diagnose) {
15663       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15664       S.Diag(Var->getLocation(), diag::note_declared_at);
15665     }
15666     return false;
15667   }
15668 
15669   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15670   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15671     if (Diagnose) {
15672       S.Diag(Loc, diag::err_ref_vm_type);
15673       S.Diag(Var->getLocation(), diag::note_previous_decl)
15674         << Var->getDeclName();
15675     }
15676     return false;
15677   }
15678   // Prohibit structs with flexible array members too.
15679   // We cannot capture what is in the tail end of the struct.
15680   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15681     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15682       if (Diagnose) {
15683         if (IsBlock)
15684           S.Diag(Loc, diag::err_ref_flexarray_type);
15685         else
15686           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15687             << Var->getDeclName();
15688         S.Diag(Var->getLocation(), diag::note_previous_decl)
15689           << Var->getDeclName();
15690       }
15691       return false;
15692     }
15693   }
15694   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15695   // Lambdas and captured statements are not allowed to capture __block
15696   // variables; they don't support the expected semantics.
15697   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15698     if (Diagnose) {
15699       S.Diag(Loc, diag::err_capture_block_variable)
15700         << Var->getDeclName() << !IsLambda;
15701       S.Diag(Var->getLocation(), diag::note_previous_decl)
15702         << Var->getDeclName();
15703     }
15704     return false;
15705   }
15706   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15707   if (S.getLangOpts().OpenCL && IsBlock &&
15708       Var->getType()->isBlockPointerType()) {
15709     if (Diagnose)
15710       S.Diag(Loc, diag::err_opencl_block_ref_block);
15711     return false;
15712   }
15713 
15714   return true;
15715 }
15716 
15717 // Returns true if the capture by block was successful.
15718 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15719                                  SourceLocation Loc,
15720                                  const bool BuildAndDiagnose,
15721                                  QualType &CaptureType,
15722                                  QualType &DeclRefType,
15723                                  const bool Nested,
15724                                  Sema &S, bool Invalid) {
15725   bool ByRef = false;
15726 
15727   // Blocks are not allowed to capture arrays, excepting OpenCL.
15728   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15729   // (decayed to pointers).
15730   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15731     if (BuildAndDiagnose) {
15732       S.Diag(Loc, diag::err_ref_array_type);
15733       S.Diag(Var->getLocation(), diag::note_previous_decl)
15734       << Var->getDeclName();
15735       Invalid = true;
15736     } else {
15737       return false;
15738     }
15739   }
15740 
15741   // Forbid the block-capture of autoreleasing variables.
15742   if (!Invalid &&
15743       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15744     if (BuildAndDiagnose) {
15745       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15746         << /*block*/ 0;
15747       S.Diag(Var->getLocation(), diag::note_previous_decl)
15748         << Var->getDeclName();
15749       Invalid = true;
15750     } else {
15751       return false;
15752     }
15753   }
15754 
15755   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15756   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15757     QualType PointeeTy = PT->getPointeeType();
15758 
15759     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15760         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15761         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15762       if (BuildAndDiagnose) {
15763         SourceLocation VarLoc = Var->getLocation();
15764         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15765         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15766       }
15767     }
15768   }
15769 
15770   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15771   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15772       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15773     // Block capture by reference does not change the capture or
15774     // declaration reference types.
15775     ByRef = true;
15776   } else {
15777     // Block capture by copy introduces 'const'.
15778     CaptureType = CaptureType.getNonReferenceType().withConst();
15779     DeclRefType = CaptureType;
15780   }
15781 
15782   // Actually capture the variable.
15783   if (BuildAndDiagnose)
15784     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15785                     CaptureType, Invalid);
15786 
15787   return !Invalid;
15788 }
15789 
15790 
15791 /// Capture the given variable in the captured region.
15792 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15793                                     VarDecl *Var,
15794                                     SourceLocation Loc,
15795                                     const bool BuildAndDiagnose,
15796                                     QualType &CaptureType,
15797                                     QualType &DeclRefType,
15798                                     const bool RefersToCapturedVariable,
15799                                     Sema &S, bool Invalid) {
15800   // By default, capture variables by reference.
15801   bool ByRef = true;
15802   // Using an LValue reference type is consistent with Lambdas (see below).
15803   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15804     if (S.isOpenMPCapturedDecl(Var)) {
15805       bool HasConst = DeclRefType.isConstQualified();
15806       DeclRefType = DeclRefType.getUnqualifiedType();
15807       // Don't lose diagnostics about assignments to const.
15808       if (HasConst)
15809         DeclRefType.addConst();
15810     }
15811     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
15812                                     RSI->OpenMPCaptureLevel);
15813   }
15814 
15815   if (ByRef)
15816     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15817   else
15818     CaptureType = DeclRefType;
15819 
15820   // Actually capture the variable.
15821   if (BuildAndDiagnose)
15822     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15823                     Loc, SourceLocation(), CaptureType, Invalid);
15824 
15825   return !Invalid;
15826 }
15827 
15828 /// Capture the given variable in the lambda.
15829 static bool captureInLambda(LambdaScopeInfo *LSI,
15830                             VarDecl *Var,
15831                             SourceLocation Loc,
15832                             const bool BuildAndDiagnose,
15833                             QualType &CaptureType,
15834                             QualType &DeclRefType,
15835                             const bool RefersToCapturedVariable,
15836                             const Sema::TryCaptureKind Kind,
15837                             SourceLocation EllipsisLoc,
15838                             const bool IsTopScope,
15839                             Sema &S, bool Invalid) {
15840   // Determine whether we are capturing by reference or by value.
15841   bool ByRef = false;
15842   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15843     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15844   } else {
15845     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15846   }
15847 
15848   // Compute the type of the field that will capture this variable.
15849   if (ByRef) {
15850     // C++11 [expr.prim.lambda]p15:
15851     //   An entity is captured by reference if it is implicitly or
15852     //   explicitly captured but not captured by copy. It is
15853     //   unspecified whether additional unnamed non-static data
15854     //   members are declared in the closure type for entities
15855     //   captured by reference.
15856     //
15857     // FIXME: It is not clear whether we want to build an lvalue reference
15858     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15859     // to do the former, while EDG does the latter. Core issue 1249 will
15860     // clarify, but for now we follow GCC because it's a more permissive and
15861     // easily defensible position.
15862     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15863   } else {
15864     // C++11 [expr.prim.lambda]p14:
15865     //   For each entity captured by copy, an unnamed non-static
15866     //   data member is declared in the closure type. The
15867     //   declaration order of these members is unspecified. The type
15868     //   of such a data member is the type of the corresponding
15869     //   captured entity if the entity is not a reference to an
15870     //   object, or the referenced type otherwise. [Note: If the
15871     //   captured entity is a reference to a function, the
15872     //   corresponding data member is also a reference to a
15873     //   function. - end note ]
15874     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15875       if (!RefType->getPointeeType()->isFunctionType())
15876         CaptureType = RefType->getPointeeType();
15877     }
15878 
15879     // Forbid the lambda copy-capture of autoreleasing variables.
15880     if (!Invalid &&
15881         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15882       if (BuildAndDiagnose) {
15883         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15884         S.Diag(Var->getLocation(), diag::note_previous_decl)
15885           << Var->getDeclName();
15886         Invalid = true;
15887       } else {
15888         return false;
15889       }
15890     }
15891 
15892     // Make sure that by-copy captures are of a complete and non-abstract type.
15893     if (!Invalid && BuildAndDiagnose) {
15894       if (!CaptureType->isDependentType() &&
15895           S.RequireCompleteType(Loc, CaptureType,
15896                                 diag::err_capture_of_incomplete_type,
15897                                 Var->getDeclName()))
15898         Invalid = true;
15899       else if (S.RequireNonAbstractType(Loc, CaptureType,
15900                                         diag::err_capture_of_abstract_type))
15901         Invalid = true;
15902     }
15903   }
15904 
15905   // Compute the type of a reference to this captured variable.
15906   if (ByRef)
15907     DeclRefType = CaptureType.getNonReferenceType();
15908   else {
15909     // C++ [expr.prim.lambda]p5:
15910     //   The closure type for a lambda-expression has a public inline
15911     //   function call operator [...]. This function call operator is
15912     //   declared const (9.3.1) if and only if the lambda-expression's
15913     //   parameter-declaration-clause is not followed by mutable.
15914     DeclRefType = CaptureType.getNonReferenceType();
15915     if (!LSI->Mutable && !CaptureType->isReferenceType())
15916       DeclRefType.addConst();
15917   }
15918 
15919   // Add the capture.
15920   if (BuildAndDiagnose)
15921     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
15922                     Loc, EllipsisLoc, CaptureType, Invalid);
15923 
15924   return !Invalid;
15925 }
15926 
15927 bool Sema::tryCaptureVariable(
15928     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15929     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15930     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15931   // An init-capture is notionally from the context surrounding its
15932   // declaration, but its parent DC is the lambda class.
15933   DeclContext *VarDC = Var->getDeclContext();
15934   if (Var->isInitCapture())
15935     VarDC = VarDC->getParent();
15936 
15937   DeclContext *DC = CurContext;
15938   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15939       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15940   // We need to sync up the Declaration Context with the
15941   // FunctionScopeIndexToStopAt
15942   if (FunctionScopeIndexToStopAt) {
15943     unsigned FSIndex = FunctionScopes.size() - 1;
15944     while (FSIndex != MaxFunctionScopesIndex) {
15945       DC = getLambdaAwareParentOfDeclContext(DC);
15946       --FSIndex;
15947     }
15948   }
15949 
15950 
15951   // If the variable is declared in the current context, there is no need to
15952   // capture it.
15953   if (VarDC == DC) return true;
15954 
15955   // Capture global variables if it is required to use private copy of this
15956   // variable.
15957   bool IsGlobal = !Var->hasLocalStorage();
15958   if (IsGlobal &&
15959       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
15960                                                 MaxFunctionScopesIndex)))
15961     return true;
15962   Var = Var->getCanonicalDecl();
15963 
15964   // Walk up the stack to determine whether we can capture the variable,
15965   // performing the "simple" checks that don't depend on type. We stop when
15966   // we've either hit the declared scope of the variable or find an existing
15967   // capture of that variable.  We start from the innermost capturing-entity
15968   // (the DC) and ensure that all intervening capturing-entities
15969   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15970   // declcontext can either capture the variable or have already captured
15971   // the variable.
15972   CaptureType = Var->getType();
15973   DeclRefType = CaptureType.getNonReferenceType();
15974   bool Nested = false;
15975   bool Explicit = (Kind != TryCapture_Implicit);
15976   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15977   do {
15978     // Only block literals, captured statements, and lambda expressions can
15979     // capture; other scopes don't work.
15980     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15981                                                               ExprLoc,
15982                                                               BuildAndDiagnose,
15983                                                               *this);
15984     // We need to check for the parent *first* because, if we *have*
15985     // private-captured a global variable, we need to recursively capture it in
15986     // intermediate blocks, lambdas, etc.
15987     if (!ParentDC) {
15988       if (IsGlobal) {
15989         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15990         break;
15991       }
15992       return true;
15993     }
15994 
15995     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15996     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15997 
15998 
15999     // Check whether we've already captured it.
16000     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16001                                              DeclRefType)) {
16002       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16003       break;
16004     }
16005     // If we are instantiating a generic lambda call operator body,
16006     // we do not want to capture new variables.  What was captured
16007     // during either a lambdas transformation or initial parsing
16008     // should be used.
16009     if (isGenericLambdaCallOperatorSpecialization(DC)) {
16010       if (BuildAndDiagnose) {
16011         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16012         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16013           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16014           Diag(Var->getLocation(), diag::note_previous_decl)
16015              << Var->getDeclName();
16016           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16017         } else
16018           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16019       }
16020       return true;
16021     }
16022 
16023     // Try to capture variable-length arrays types.
16024     if (Var->getType()->isVariablyModifiedType()) {
16025       // We're going to walk down into the type and look for VLA
16026       // expressions.
16027       QualType QTy = Var->getType();
16028       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16029         QTy = PVD->getOriginalType();
16030       captureVariablyModifiedType(Context, QTy, CSI);
16031     }
16032 
16033     if (getLangOpts().OpenMP) {
16034       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16035         // OpenMP private variables should not be captured in outer scope, so
16036         // just break here. Similarly, global variables that are captured in a
16037         // target region should not be captured outside the scope of the region.
16038         if (RSI->CapRegionKind == CR_OpenMP) {
16039           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16040           auto IsTargetCap = !IsOpenMPPrivateDecl &&
16041                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16042           // When we detect target captures we are looking from inside the
16043           // target region, therefore we need to propagate the capture from the
16044           // enclosing region. Therefore, the capture is not initially nested.
16045           if (IsTargetCap)
16046             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16047 
16048           if (IsTargetCap || IsOpenMPPrivateDecl) {
16049             Nested = !IsTargetCap;
16050             DeclRefType = DeclRefType.getUnqualifiedType();
16051             CaptureType = Context.getLValueReferenceType(DeclRefType);
16052             break;
16053           }
16054         }
16055       }
16056     }
16057     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16058       // No capture-default, and this is not an explicit capture
16059       // so cannot capture this variable.
16060       if (BuildAndDiagnose) {
16061         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16062         Diag(Var->getLocation(), diag::note_previous_decl)
16063           << Var->getDeclName();
16064         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16065           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16066                diag::note_lambda_decl);
16067         // FIXME: If we error out because an outer lambda can not implicitly
16068         // capture a variable that an inner lambda explicitly captures, we
16069         // should have the inner lambda do the explicit capture - because
16070         // it makes for cleaner diagnostics later.  This would purely be done
16071         // so that the diagnostic does not misleadingly claim that a variable
16072         // can not be captured by a lambda implicitly even though it is captured
16073         // explicitly.  Suggestion:
16074         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16075         //    at the function head
16076         //  - cache the StartingDeclContext - this must be a lambda
16077         //  - captureInLambda in the innermost lambda the variable.
16078       }
16079       return true;
16080     }
16081 
16082     FunctionScopesIndex--;
16083     DC = ParentDC;
16084     Explicit = false;
16085   } while (!VarDC->Equals(DC));
16086 
16087   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16088   // computing the type of the capture at each step, checking type-specific
16089   // requirements, and adding captures if requested.
16090   // If the variable had already been captured previously, we start capturing
16091   // at the lambda nested within that one.
16092   bool Invalid = false;
16093   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16094        ++I) {
16095     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16096 
16097     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16098     // certain types of variables (unnamed, variably modified types etc.)
16099     // so check for eligibility.
16100     if (!Invalid)
16101       Invalid =
16102           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16103 
16104     // After encountering an error, if we're actually supposed to capture, keep
16105     // capturing in nested contexts to suppress any follow-on diagnostics.
16106     if (Invalid && !BuildAndDiagnose)
16107       return true;
16108 
16109     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16110       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16111                                DeclRefType, Nested, *this, Invalid);
16112       Nested = true;
16113     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16114       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16115                                          CaptureType, DeclRefType, Nested,
16116                                          *this, Invalid);
16117       Nested = true;
16118     } else {
16119       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16120       Invalid =
16121           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16122                            DeclRefType, Nested, Kind, EllipsisLoc,
16123                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16124       Nested = true;
16125     }
16126 
16127     if (Invalid && !BuildAndDiagnose)
16128       return true;
16129   }
16130   return Invalid;
16131 }
16132 
16133 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16134                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16135   QualType CaptureType;
16136   QualType DeclRefType;
16137   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16138                             /*BuildAndDiagnose=*/true, CaptureType,
16139                             DeclRefType, nullptr);
16140 }
16141 
16142 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16143   QualType CaptureType;
16144   QualType DeclRefType;
16145   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16146                              /*BuildAndDiagnose=*/false, CaptureType,
16147                              DeclRefType, nullptr);
16148 }
16149 
16150 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16151   QualType CaptureType;
16152   QualType DeclRefType;
16153 
16154   // Determine whether we can capture this variable.
16155   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16156                          /*BuildAndDiagnose=*/false, CaptureType,
16157                          DeclRefType, nullptr))
16158     return QualType();
16159 
16160   return DeclRefType;
16161 }
16162 
16163 namespace {
16164 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16165 // The produced TemplateArgumentListInfo* points to data stored within this
16166 // object, so should only be used in contexts where the pointer will not be
16167 // used after the CopiedTemplateArgs object is destroyed.
16168 class CopiedTemplateArgs {
16169   bool HasArgs;
16170   TemplateArgumentListInfo TemplateArgStorage;
16171 public:
16172   template<typename RefExpr>
16173   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16174     if (HasArgs)
16175       E->copyTemplateArgumentsInto(TemplateArgStorage);
16176   }
16177   operator TemplateArgumentListInfo*()
16178 #ifdef __has_cpp_attribute
16179 #if __has_cpp_attribute(clang::lifetimebound)
16180   [[clang::lifetimebound]]
16181 #endif
16182 #endif
16183   {
16184     return HasArgs ? &TemplateArgStorage : nullptr;
16185   }
16186 };
16187 }
16188 
16189 /// Walk the set of potential results of an expression and mark them all as
16190 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16191 ///
16192 /// \return A new expression if we found any potential results, ExprEmpty() if
16193 ///         not, and ExprError() if we diagnosed an error.
16194 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16195                                                       NonOdrUseReason NOUR) {
16196   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16197   // an object that satisfies the requirements for appearing in a
16198   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16199   // is immediately applied."  This function handles the lvalue-to-rvalue
16200   // conversion part.
16201   //
16202   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16203   // transform it into the relevant kind of non-odr-use node and rebuild the
16204   // tree of nodes leading to it.
16205   //
16206   // This is a mini-TreeTransform that only transforms a restricted subset of
16207   // nodes (and only certain operands of them).
16208 
16209   // Rebuild a subexpression.
16210   auto Rebuild = [&](Expr *Sub) {
16211     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16212   };
16213 
16214   // Check whether a potential result satisfies the requirements of NOUR.
16215   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16216     // Any entity other than a VarDecl is always odr-used whenever it's named
16217     // in a potentially-evaluated expression.
16218     auto *VD = dyn_cast<VarDecl>(D);
16219     if (!VD)
16220       return true;
16221 
16222     // C++2a [basic.def.odr]p4:
16223     //   A variable x whose name appears as a potentially-evalauted expression
16224     //   e is odr-used by e unless
16225     //   -- x is a reference that is usable in constant expressions, or
16226     //   -- x is a variable of non-reference type that is usable in constant
16227     //      expressions and has no mutable subobjects, and e is an element of
16228     //      the set of potential results of an expression of
16229     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16230     //      conversion is applied, or
16231     //   -- x is a variable of non-reference type, and e is an element of the
16232     //      set of potential results of a discarded-value expression to which
16233     //      the lvalue-to-rvalue conversion is not applied
16234     //
16235     // We check the first bullet and the "potentially-evaluated" condition in
16236     // BuildDeclRefExpr. We check the type requirements in the second bullet
16237     // in CheckLValueToRValueConversionOperand below.
16238     switch (NOUR) {
16239     case NOUR_None:
16240     case NOUR_Unevaluated:
16241       llvm_unreachable("unexpected non-odr-use-reason");
16242 
16243     case NOUR_Constant:
16244       // Constant references were handled when they were built.
16245       if (VD->getType()->isReferenceType())
16246         return true;
16247       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16248         if (RD->hasMutableFields())
16249           return true;
16250       if (!VD->isUsableInConstantExpressions(S.Context))
16251         return true;
16252       break;
16253 
16254     case NOUR_Discarded:
16255       if (VD->getType()->isReferenceType())
16256         return true;
16257       break;
16258     }
16259     return false;
16260   };
16261 
16262   // Mark that this expression does not constitute an odr-use.
16263   auto MarkNotOdrUsed = [&] {
16264     S.MaybeODRUseExprs.erase(E);
16265     if (LambdaScopeInfo *LSI = S.getCurLambda())
16266       LSI->markVariableExprAsNonODRUsed(E);
16267   };
16268 
16269   // C++2a [basic.def.odr]p2:
16270   //   The set of potential results of an expression e is defined as follows:
16271   switch (E->getStmtClass()) {
16272   //   -- If e is an id-expression, ...
16273   case Expr::DeclRefExprClass: {
16274     auto *DRE = cast<DeclRefExpr>(E);
16275     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16276       break;
16277 
16278     // Rebuild as a non-odr-use DeclRefExpr.
16279     MarkNotOdrUsed();
16280     return DeclRefExpr::Create(
16281         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16282         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16283         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16284         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16285   }
16286 
16287   case Expr::FunctionParmPackExprClass: {
16288     auto *FPPE = cast<FunctionParmPackExpr>(E);
16289     // If any of the declarations in the pack is odr-used, then the expression
16290     // as a whole constitutes an odr-use.
16291     for (VarDecl *D : *FPPE)
16292       if (IsPotentialResultOdrUsed(D))
16293         return ExprEmpty();
16294 
16295     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16296     // nothing cares about whether we marked this as an odr-use, but it might
16297     // be useful for non-compiler tools.
16298     MarkNotOdrUsed();
16299     break;
16300   }
16301 
16302   //   -- If e is a subscripting operation with an array operand...
16303   case Expr::ArraySubscriptExprClass: {
16304     auto *ASE = cast<ArraySubscriptExpr>(E);
16305     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16306     if (!OldBase->getType()->isArrayType())
16307       break;
16308     ExprResult Base = Rebuild(OldBase);
16309     if (!Base.isUsable())
16310       return Base;
16311     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16312     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16313     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16314     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16315                                      ASE->getRBracketLoc());
16316   }
16317 
16318   case Expr::MemberExprClass: {
16319     auto *ME = cast<MemberExpr>(E);
16320     // -- If e is a class member access expression [...] naming a non-static
16321     //    data member...
16322     if (isa<FieldDecl>(ME->getMemberDecl())) {
16323       ExprResult Base = Rebuild(ME->getBase());
16324       if (!Base.isUsable())
16325         return Base;
16326       return MemberExpr::Create(
16327           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16328           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16329           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16330           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16331           ME->getObjectKind(), ME->isNonOdrUse());
16332     }
16333 
16334     if (ME->getMemberDecl()->isCXXInstanceMember())
16335       break;
16336 
16337     // -- If e is a class member access expression naming a static data member,
16338     //    ...
16339     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16340       break;
16341 
16342     // Rebuild as a non-odr-use MemberExpr.
16343     MarkNotOdrUsed();
16344     return MemberExpr::Create(
16345         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16346         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16347         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16348         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16349     return ExprEmpty();
16350   }
16351 
16352   case Expr::BinaryOperatorClass: {
16353     auto *BO = cast<BinaryOperator>(E);
16354     Expr *LHS = BO->getLHS();
16355     Expr *RHS = BO->getRHS();
16356     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16357     if (BO->getOpcode() == BO_PtrMemD) {
16358       ExprResult Sub = Rebuild(LHS);
16359       if (!Sub.isUsable())
16360         return Sub;
16361       LHS = Sub.get();
16362     //   -- If e is a comma expression, ...
16363     } else if (BO->getOpcode() == BO_Comma) {
16364       ExprResult Sub = Rebuild(RHS);
16365       if (!Sub.isUsable())
16366         return Sub;
16367       RHS = Sub.get();
16368     } else {
16369       break;
16370     }
16371     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16372                         LHS, RHS);
16373   }
16374 
16375   //   -- If e has the form (e1)...
16376   case Expr::ParenExprClass: {
16377     auto *PE = cast<ParenExpr>(E);
16378     ExprResult Sub = Rebuild(PE->getSubExpr());
16379     if (!Sub.isUsable())
16380       return Sub;
16381     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16382   }
16383 
16384   //   -- If e is a glvalue conditional expression, ...
16385   // We don't apply this to a binary conditional operator. FIXME: Should we?
16386   case Expr::ConditionalOperatorClass: {
16387     auto *CO = cast<ConditionalOperator>(E);
16388     ExprResult LHS = Rebuild(CO->getLHS());
16389     if (LHS.isInvalid())
16390       return ExprError();
16391     ExprResult RHS = Rebuild(CO->getRHS());
16392     if (RHS.isInvalid())
16393       return ExprError();
16394     if (!LHS.isUsable() && !RHS.isUsable())
16395       return ExprEmpty();
16396     if (!LHS.isUsable())
16397       LHS = CO->getLHS();
16398     if (!RHS.isUsable())
16399       RHS = CO->getRHS();
16400     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16401                                 CO->getCond(), LHS.get(), RHS.get());
16402   }
16403 
16404   // [Clang extension]
16405   //   -- If e has the form __extension__ e1...
16406   case Expr::UnaryOperatorClass: {
16407     auto *UO = cast<UnaryOperator>(E);
16408     if (UO->getOpcode() != UO_Extension)
16409       break;
16410     ExprResult Sub = Rebuild(UO->getSubExpr());
16411     if (!Sub.isUsable())
16412       return Sub;
16413     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16414                           Sub.get());
16415   }
16416 
16417   // [Clang extension]
16418   //   -- If e has the form _Generic(...), the set of potential results is the
16419   //      union of the sets of potential results of the associated expressions.
16420   case Expr::GenericSelectionExprClass: {
16421     auto *GSE = cast<GenericSelectionExpr>(E);
16422 
16423     SmallVector<Expr *, 4> AssocExprs;
16424     bool AnyChanged = false;
16425     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16426       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16427       if (AssocExpr.isInvalid())
16428         return ExprError();
16429       if (AssocExpr.isUsable()) {
16430         AssocExprs.push_back(AssocExpr.get());
16431         AnyChanged = true;
16432       } else {
16433         AssocExprs.push_back(OrigAssocExpr);
16434       }
16435     }
16436 
16437     return AnyChanged ? S.CreateGenericSelectionExpr(
16438                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16439                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16440                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16441                       : ExprEmpty();
16442   }
16443 
16444   // [Clang extension]
16445   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16446   //      results is the union of the sets of potential results of the
16447   //      second and third subexpressions.
16448   case Expr::ChooseExprClass: {
16449     auto *CE = cast<ChooseExpr>(E);
16450 
16451     ExprResult LHS = Rebuild(CE->getLHS());
16452     if (LHS.isInvalid())
16453       return ExprError();
16454 
16455     ExprResult RHS = Rebuild(CE->getLHS());
16456     if (RHS.isInvalid())
16457       return ExprError();
16458 
16459     if (!LHS.get() && !RHS.get())
16460       return ExprEmpty();
16461     if (!LHS.isUsable())
16462       LHS = CE->getLHS();
16463     if (!RHS.isUsable())
16464       RHS = CE->getRHS();
16465 
16466     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16467                              RHS.get(), CE->getRParenLoc());
16468   }
16469 
16470   // Step through non-syntactic nodes.
16471   case Expr::ConstantExprClass: {
16472     auto *CE = cast<ConstantExpr>(E);
16473     ExprResult Sub = Rebuild(CE->getSubExpr());
16474     if (!Sub.isUsable())
16475       return Sub;
16476     return ConstantExpr::Create(S.Context, Sub.get());
16477   }
16478 
16479   // We could mostly rely on the recursive rebuilding to rebuild implicit
16480   // casts, but not at the top level, so rebuild them here.
16481   case Expr::ImplicitCastExprClass: {
16482     auto *ICE = cast<ImplicitCastExpr>(E);
16483     // Only step through the narrow set of cast kinds we expect to encounter.
16484     // Anything else suggests we've left the region in which potential results
16485     // can be found.
16486     switch (ICE->getCastKind()) {
16487     case CK_NoOp:
16488     case CK_DerivedToBase:
16489     case CK_UncheckedDerivedToBase: {
16490       ExprResult Sub = Rebuild(ICE->getSubExpr());
16491       if (!Sub.isUsable())
16492         return Sub;
16493       CXXCastPath Path(ICE->path());
16494       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16495                                  ICE->getValueKind(), &Path);
16496     }
16497 
16498     default:
16499       break;
16500     }
16501     break;
16502   }
16503 
16504   default:
16505     break;
16506   }
16507 
16508   // Can't traverse through this node. Nothing to do.
16509   return ExprEmpty();
16510 }
16511 
16512 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16513   // Check whether the operand is or contains an object of non-trivial C union
16514   // type.
16515   if (E->getType().isVolatileQualified() &&
16516       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16517        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16518     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16519                           Sema::NTCUC_LValueToRValueVolatile,
16520                           NTCUK_Destruct|NTCUK_Copy);
16521 
16522   // C++2a [basic.def.odr]p4:
16523   //   [...] an expression of non-volatile-qualified non-class type to which
16524   //   the lvalue-to-rvalue conversion is applied [...]
16525   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16526     return E;
16527 
16528   ExprResult Result =
16529       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16530   if (Result.isInvalid())
16531     return ExprError();
16532   return Result.get() ? Result : E;
16533 }
16534 
16535 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16536   Res = CorrectDelayedTyposInExpr(Res);
16537 
16538   if (!Res.isUsable())
16539     return Res;
16540 
16541   // If a constant-expression is a reference to a variable where we delay
16542   // deciding whether it is an odr-use, just assume we will apply the
16543   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16544   // (a non-type template argument), we have special handling anyway.
16545   return CheckLValueToRValueConversionOperand(Res.get());
16546 }
16547 
16548 void Sema::CleanupVarDeclMarking() {
16549   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16550   // call.
16551   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16552   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16553 
16554   for (Expr *E : LocalMaybeODRUseExprs) {
16555     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16556       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16557                          DRE->getLocation(), *this);
16558     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16559       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16560                          *this);
16561     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16562       for (VarDecl *VD : *FP)
16563         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16564     } else {
16565       llvm_unreachable("Unexpected expression");
16566     }
16567   }
16568 
16569   assert(MaybeODRUseExprs.empty() &&
16570          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16571 }
16572 
16573 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16574                                     VarDecl *Var, Expr *E) {
16575   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16576           isa<FunctionParmPackExpr>(E)) &&
16577          "Invalid Expr argument to DoMarkVarDeclReferenced");
16578   Var->setReferenced();
16579 
16580   if (Var->isInvalidDecl())
16581     return;
16582 
16583   auto *MSI = Var->getMemberSpecializationInfo();
16584   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16585                                        : Var->getTemplateSpecializationKind();
16586 
16587   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16588   bool UsableInConstantExpr =
16589       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16590 
16591   // C++20 [expr.const]p12:
16592   //   A variable [...] is needed for constant evaluation if it is [...] a
16593   //   variable whose name appears as a potentially constant evaluated
16594   //   expression that is either a contexpr variable or is of non-volatile
16595   //   const-qualified integral type or of reference type
16596   bool NeededForConstantEvaluation =
16597       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16598 
16599   bool NeedDefinition =
16600       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16601 
16602   VarTemplateSpecializationDecl *VarSpec =
16603       dyn_cast<VarTemplateSpecializationDecl>(Var);
16604   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16605          "Can't instantiate a partial template specialization.");
16606 
16607   // If this might be a member specialization of a static data member, check
16608   // the specialization is visible. We already did the checks for variable
16609   // template specializations when we created them.
16610   if (NeedDefinition && TSK != TSK_Undeclared &&
16611       !isa<VarTemplateSpecializationDecl>(Var))
16612     SemaRef.checkSpecializationVisibility(Loc, Var);
16613 
16614   // Perform implicit instantiation of static data members, static data member
16615   // templates of class templates, and variable template specializations. Delay
16616   // instantiations of variable templates, except for those that could be used
16617   // in a constant expression.
16618   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16619     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16620     // instantiation declaration if a variable is usable in a constant
16621     // expression (among other cases).
16622     bool TryInstantiating =
16623         TSK == TSK_ImplicitInstantiation ||
16624         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16625 
16626     if (TryInstantiating) {
16627       SourceLocation PointOfInstantiation =
16628           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16629       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16630       if (FirstInstantiation) {
16631         PointOfInstantiation = Loc;
16632         if (MSI)
16633           MSI->setPointOfInstantiation(PointOfInstantiation);
16634         else
16635           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16636       }
16637 
16638       bool InstantiationDependent = false;
16639       bool IsNonDependent =
16640           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16641                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16642                   : true;
16643 
16644       // Do not instantiate specializations that are still type-dependent.
16645       if (IsNonDependent) {
16646         if (UsableInConstantExpr) {
16647           // Do not defer instantiations of variables that could be used in a
16648           // constant expression.
16649           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16650             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16651           });
16652         } else if (FirstInstantiation ||
16653                    isa<VarTemplateSpecializationDecl>(Var)) {
16654           // FIXME: For a specialization of a variable template, we don't
16655           // distinguish between "declaration and type implicitly instantiated"
16656           // and "implicit instantiation of definition requested", so we have
16657           // no direct way to avoid enqueueing the pending instantiation
16658           // multiple times.
16659           SemaRef.PendingInstantiations
16660               .push_back(std::make_pair(Var, PointOfInstantiation));
16661         }
16662       }
16663     }
16664   }
16665 
16666   // C++2a [basic.def.odr]p4:
16667   //   A variable x whose name appears as a potentially-evaluated expression e
16668   //   is odr-used by e unless
16669   //   -- x is a reference that is usable in constant expressions
16670   //   -- x is a variable of non-reference type that is usable in constant
16671   //      expressions and has no mutable subobjects [FIXME], and e is an
16672   //      element of the set of potential results of an expression of
16673   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16674   //      conversion is applied
16675   //   -- x is a variable of non-reference type, and e is an element of the set
16676   //      of potential results of a discarded-value expression to which the
16677   //      lvalue-to-rvalue conversion is not applied [FIXME]
16678   //
16679   // We check the first part of the second bullet here, and
16680   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16681   // FIXME: To get the third bullet right, we need to delay this even for
16682   // variables that are not usable in constant expressions.
16683 
16684   // If we already know this isn't an odr-use, there's nothing more to do.
16685   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16686     if (DRE->isNonOdrUse())
16687       return;
16688   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16689     if (ME->isNonOdrUse())
16690       return;
16691 
16692   switch (OdrUse) {
16693   case OdrUseContext::None:
16694     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16695            "missing non-odr-use marking for unevaluated decl ref");
16696     break;
16697 
16698   case OdrUseContext::FormallyOdrUsed:
16699     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16700     // behavior.
16701     break;
16702 
16703   case OdrUseContext::Used:
16704     // If we might later find that this expression isn't actually an odr-use,
16705     // delay the marking.
16706     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16707       SemaRef.MaybeODRUseExprs.insert(E);
16708     else
16709       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16710     break;
16711 
16712   case OdrUseContext::Dependent:
16713     // If this is a dependent context, we don't need to mark variables as
16714     // odr-used, but we may still need to track them for lambda capture.
16715     // FIXME: Do we also need to do this inside dependent typeid expressions
16716     // (which are modeled as unevaluated at this point)?
16717     const bool RefersToEnclosingScope =
16718         (SemaRef.CurContext != Var->getDeclContext() &&
16719          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16720     if (RefersToEnclosingScope) {
16721       LambdaScopeInfo *const LSI =
16722           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16723       if (LSI && (!LSI->CallOperator ||
16724                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16725         // If a variable could potentially be odr-used, defer marking it so
16726         // until we finish analyzing the full expression for any
16727         // lvalue-to-rvalue
16728         // or discarded value conversions that would obviate odr-use.
16729         // Add it to the list of potential captures that will be analyzed
16730         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16731         // unless the variable is a reference that was initialized by a constant
16732         // expression (this will never need to be captured or odr-used).
16733         //
16734         // FIXME: We can simplify this a lot after implementing P0588R1.
16735         assert(E && "Capture variable should be used in an expression.");
16736         if (!Var->getType()->isReferenceType() ||
16737             !Var->isUsableInConstantExpressions(SemaRef.Context))
16738           LSI->addPotentialCapture(E->IgnoreParens());
16739       }
16740     }
16741     break;
16742   }
16743 }
16744 
16745 /// Mark a variable referenced, and check whether it is odr-used
16746 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16747 /// used directly for normal expressions referring to VarDecl.
16748 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16749   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16750 }
16751 
16752 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16753                                Decl *D, Expr *E, bool MightBeOdrUse) {
16754   if (SemaRef.isInOpenMPDeclareTargetContext())
16755     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16756 
16757   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16758     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16759     return;
16760   }
16761 
16762   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16763 
16764   // If this is a call to a method via a cast, also mark the method in the
16765   // derived class used in case codegen can devirtualize the call.
16766   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16767   if (!ME)
16768     return;
16769   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16770   if (!MD)
16771     return;
16772   // Only attempt to devirtualize if this is truly a virtual call.
16773   bool IsVirtualCall = MD->isVirtual() &&
16774                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16775   if (!IsVirtualCall)
16776     return;
16777 
16778   // If it's possible to devirtualize the call, mark the called function
16779   // referenced.
16780   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16781       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16782   if (DM)
16783     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16784 }
16785 
16786 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16787 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16788   // TODO: update this with DR# once a defect report is filed.
16789   // C++11 defect. The address of a pure member should not be an ODR use, even
16790   // if it's a qualified reference.
16791   bool OdrUse = true;
16792   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16793     if (Method->isVirtual() &&
16794         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16795       OdrUse = false;
16796   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16797 }
16798 
16799 /// Perform reference-marking and odr-use handling for a MemberExpr.
16800 void Sema::MarkMemberReferenced(MemberExpr *E) {
16801   // C++11 [basic.def.odr]p2:
16802   //   A non-overloaded function whose name appears as a potentially-evaluated
16803   //   expression or a member of a set of candidate functions, if selected by
16804   //   overload resolution when referred to from a potentially-evaluated
16805   //   expression, is odr-used, unless it is a pure virtual function and its
16806   //   name is not explicitly qualified.
16807   bool MightBeOdrUse = true;
16808   if (E->performsVirtualDispatch(getLangOpts())) {
16809     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16810       if (Method->isPure())
16811         MightBeOdrUse = false;
16812   }
16813   SourceLocation Loc =
16814       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16815   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16816 }
16817 
16818 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16819 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16820   for (VarDecl *VD : *E)
16821     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16822 }
16823 
16824 /// Perform marking for a reference to an arbitrary declaration.  It
16825 /// marks the declaration referenced, and performs odr-use checking for
16826 /// functions and variables. This method should not be used when building a
16827 /// normal expression which refers to a variable.
16828 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16829                                  bool MightBeOdrUse) {
16830   if (MightBeOdrUse) {
16831     if (auto *VD = dyn_cast<VarDecl>(D)) {
16832       MarkVariableReferenced(Loc, VD);
16833       return;
16834     }
16835   }
16836   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16837     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16838     return;
16839   }
16840   D->setReferenced();
16841 }
16842 
16843 namespace {
16844   // Mark all of the declarations used by a type as referenced.
16845   // FIXME: Not fully implemented yet! We need to have a better understanding
16846   // of when we're entering a context we should not recurse into.
16847   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16848   // TreeTransforms rebuilding the type in a new context. Rather than
16849   // duplicating the TreeTransform logic, we should consider reusing it here.
16850   // Currently that causes problems when rebuilding LambdaExprs.
16851   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16852     Sema &S;
16853     SourceLocation Loc;
16854 
16855   public:
16856     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16857 
16858     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16859 
16860     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16861   };
16862 }
16863 
16864 bool MarkReferencedDecls::TraverseTemplateArgument(
16865     const TemplateArgument &Arg) {
16866   {
16867     // A non-type template argument is a constant-evaluated context.
16868     EnterExpressionEvaluationContext Evaluated(
16869         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16870     if (Arg.getKind() == TemplateArgument::Declaration) {
16871       if (Decl *D = Arg.getAsDecl())
16872         S.MarkAnyDeclReferenced(Loc, D, true);
16873     } else if (Arg.getKind() == TemplateArgument::Expression) {
16874       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16875     }
16876   }
16877 
16878   return Inherited::TraverseTemplateArgument(Arg);
16879 }
16880 
16881 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16882   MarkReferencedDecls Marker(*this, Loc);
16883   Marker.TraverseType(T);
16884 }
16885 
16886 namespace {
16887   /// Helper class that marks all of the declarations referenced by
16888   /// potentially-evaluated subexpressions as "referenced".
16889   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16890     Sema &S;
16891     bool SkipLocalVariables;
16892 
16893   public:
16894     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16895 
16896     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16897       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16898 
16899     void VisitDeclRefExpr(DeclRefExpr *E) {
16900       // If we were asked not to visit local variables, don't.
16901       if (SkipLocalVariables) {
16902         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16903           if (VD->hasLocalStorage())
16904             return;
16905       }
16906 
16907       S.MarkDeclRefReferenced(E);
16908     }
16909 
16910     void VisitMemberExpr(MemberExpr *E) {
16911       S.MarkMemberReferenced(E);
16912       Inherited::VisitMemberExpr(E);
16913     }
16914 
16915     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16916       S.MarkFunctionReferenced(
16917           E->getBeginLoc(),
16918           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16919       Visit(E->getSubExpr());
16920     }
16921 
16922     void VisitCXXNewExpr(CXXNewExpr *E) {
16923       if (E->getOperatorNew())
16924         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16925       if (E->getOperatorDelete())
16926         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16927       Inherited::VisitCXXNewExpr(E);
16928     }
16929 
16930     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16931       if (E->getOperatorDelete())
16932         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16933       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16934       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16935         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16936         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16937       }
16938 
16939       Inherited::VisitCXXDeleteExpr(E);
16940     }
16941 
16942     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16943       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16944       Inherited::VisitCXXConstructExpr(E);
16945     }
16946 
16947     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16948       Visit(E->getExpr());
16949     }
16950   };
16951 }
16952 
16953 /// Mark any declarations that appear within this expression or any
16954 /// potentially-evaluated subexpressions as "referenced".
16955 ///
16956 /// \param SkipLocalVariables If true, don't mark local variables as
16957 /// 'referenced'.
16958 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16959                                             bool SkipLocalVariables) {
16960   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16961 }
16962 
16963 /// Emit a diagnostic that describes an effect on the run-time behavior
16964 /// of the program being compiled.
16965 ///
16966 /// This routine emits the given diagnostic when the code currently being
16967 /// type-checked is "potentially evaluated", meaning that there is a
16968 /// possibility that the code will actually be executable. Code in sizeof()
16969 /// expressions, code used only during overload resolution, etc., are not
16970 /// potentially evaluated. This routine will suppress such diagnostics or,
16971 /// in the absolutely nutty case of potentially potentially evaluated
16972 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16973 /// later.
16974 ///
16975 /// This routine should be used for all diagnostics that describe the run-time
16976 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16977 /// Failure to do so will likely result in spurious diagnostics or failures
16978 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16979 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
16980                                const PartialDiagnostic &PD) {
16981   switch (ExprEvalContexts.back().Context) {
16982   case ExpressionEvaluationContext::Unevaluated:
16983   case ExpressionEvaluationContext::UnevaluatedList:
16984   case ExpressionEvaluationContext::UnevaluatedAbstract:
16985   case ExpressionEvaluationContext::DiscardedStatement:
16986     // The argument will never be evaluated, so don't complain.
16987     break;
16988 
16989   case ExpressionEvaluationContext::ConstantEvaluated:
16990     // Relevant diagnostics should be produced by constant evaluation.
16991     break;
16992 
16993   case ExpressionEvaluationContext::PotentiallyEvaluated:
16994   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16995     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
16996       FunctionScopes.back()->PossiblyUnreachableDiags.
16997         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
16998       return true;
16999     }
17000 
17001     // The initializer of a constexpr variable or of the first declaration of a
17002     // static data member is not syntactically a constant evaluated constant,
17003     // but nonetheless is always required to be a constant expression, so we
17004     // can skip diagnosing.
17005     // FIXME: Using the mangling context here is a hack.
17006     if (auto *VD = dyn_cast_or_null<VarDecl>(
17007             ExprEvalContexts.back().ManglingContextDecl)) {
17008       if (VD->isConstexpr() ||
17009           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17010         break;
17011       // FIXME: For any other kind of variable, we should build a CFG for its
17012       // initializer and check whether the context in question is reachable.
17013     }
17014 
17015     Diag(Loc, PD);
17016     return true;
17017   }
17018 
17019   return false;
17020 }
17021 
17022 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17023                                const PartialDiagnostic &PD) {
17024   return DiagRuntimeBehavior(
17025       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17026 }
17027 
17028 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17029                                CallExpr *CE, FunctionDecl *FD) {
17030   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17031     return false;
17032 
17033   // If we're inside a decltype's expression, don't check for a valid return
17034   // type or construct temporaries until we know whether this is the last call.
17035   if (ExprEvalContexts.back().ExprContext ==
17036       ExpressionEvaluationContextRecord::EK_Decltype) {
17037     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17038     return false;
17039   }
17040 
17041   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17042     FunctionDecl *FD;
17043     CallExpr *CE;
17044 
17045   public:
17046     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17047       : FD(FD), CE(CE) { }
17048 
17049     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17050       if (!FD) {
17051         S.Diag(Loc, diag::err_call_incomplete_return)
17052           << T << CE->getSourceRange();
17053         return;
17054       }
17055 
17056       S.Diag(Loc, diag::err_call_function_incomplete_return)
17057         << CE->getSourceRange() << FD->getDeclName() << T;
17058       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17059           << FD->getDeclName();
17060     }
17061   } Diagnoser(FD, CE);
17062 
17063   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17064     return true;
17065 
17066   return false;
17067 }
17068 
17069 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17070 // will prevent this condition from triggering, which is what we want.
17071 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17072   SourceLocation Loc;
17073 
17074   unsigned diagnostic = diag::warn_condition_is_assignment;
17075   bool IsOrAssign = false;
17076 
17077   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17078     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17079       return;
17080 
17081     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17082 
17083     // Greylist some idioms by putting them into a warning subcategory.
17084     if (ObjCMessageExpr *ME
17085           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17086       Selector Sel = ME->getSelector();
17087 
17088       // self = [<foo> init...]
17089       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17090         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17091 
17092       // <foo> = [<bar> nextObject]
17093       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17094         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17095     }
17096 
17097     Loc = Op->getOperatorLoc();
17098   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17099     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17100       return;
17101 
17102     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17103     Loc = Op->getOperatorLoc();
17104   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17105     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17106   else {
17107     // Not an assignment.
17108     return;
17109   }
17110 
17111   Diag(Loc, diagnostic) << E->getSourceRange();
17112 
17113   SourceLocation Open = E->getBeginLoc();
17114   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17115   Diag(Loc, diag::note_condition_assign_silence)
17116         << FixItHint::CreateInsertion(Open, "(")
17117         << FixItHint::CreateInsertion(Close, ")");
17118 
17119   if (IsOrAssign)
17120     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17121       << FixItHint::CreateReplacement(Loc, "!=");
17122   else
17123     Diag(Loc, diag::note_condition_assign_to_comparison)
17124       << FixItHint::CreateReplacement(Loc, "==");
17125 }
17126 
17127 /// Redundant parentheses over an equality comparison can indicate
17128 /// that the user intended an assignment used as condition.
17129 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17130   // Don't warn if the parens came from a macro.
17131   SourceLocation parenLoc = ParenE->getBeginLoc();
17132   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17133     return;
17134   // Don't warn for dependent expressions.
17135   if (ParenE->isTypeDependent())
17136     return;
17137 
17138   Expr *E = ParenE->IgnoreParens();
17139 
17140   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17141     if (opE->getOpcode() == BO_EQ &&
17142         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17143                                                            == Expr::MLV_Valid) {
17144       SourceLocation Loc = opE->getOperatorLoc();
17145 
17146       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17147       SourceRange ParenERange = ParenE->getSourceRange();
17148       Diag(Loc, diag::note_equality_comparison_silence)
17149         << FixItHint::CreateRemoval(ParenERange.getBegin())
17150         << FixItHint::CreateRemoval(ParenERange.getEnd());
17151       Diag(Loc, diag::note_equality_comparison_to_assign)
17152         << FixItHint::CreateReplacement(Loc, "=");
17153     }
17154 }
17155 
17156 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17157                                        bool IsConstexpr) {
17158   DiagnoseAssignmentAsCondition(E);
17159   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17160     DiagnoseEqualityWithExtraParens(parenE);
17161 
17162   ExprResult result = CheckPlaceholderExpr(E);
17163   if (result.isInvalid()) return ExprError();
17164   E = result.get();
17165 
17166   if (!E->isTypeDependent()) {
17167     if (getLangOpts().CPlusPlus)
17168       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17169 
17170     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17171     if (ERes.isInvalid())
17172       return ExprError();
17173     E = ERes.get();
17174 
17175     QualType T = E->getType();
17176     if (!T->isScalarType()) { // C99 6.8.4.1p1
17177       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17178         << T << E->getSourceRange();
17179       return ExprError();
17180     }
17181     CheckBoolLikeConversion(E, Loc);
17182   }
17183 
17184   return E;
17185 }
17186 
17187 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17188                                            Expr *SubExpr, ConditionKind CK) {
17189   // Empty conditions are valid in for-statements.
17190   if (!SubExpr)
17191     return ConditionResult();
17192 
17193   ExprResult Cond;
17194   switch (CK) {
17195   case ConditionKind::Boolean:
17196     Cond = CheckBooleanCondition(Loc, SubExpr);
17197     break;
17198 
17199   case ConditionKind::ConstexprIf:
17200     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17201     break;
17202 
17203   case ConditionKind::Switch:
17204     Cond = CheckSwitchCondition(Loc, SubExpr);
17205     break;
17206   }
17207   if (Cond.isInvalid())
17208     return ConditionError();
17209 
17210   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17211   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17212   if (!FullExpr.get())
17213     return ConditionError();
17214 
17215   return ConditionResult(*this, nullptr, FullExpr,
17216                          CK == ConditionKind::ConstexprIf);
17217 }
17218 
17219 namespace {
17220   /// A visitor for rebuilding a call to an __unknown_any expression
17221   /// to have an appropriate type.
17222   struct RebuildUnknownAnyFunction
17223     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17224 
17225     Sema &S;
17226 
17227     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17228 
17229     ExprResult VisitStmt(Stmt *S) {
17230       llvm_unreachable("unexpected statement!");
17231     }
17232 
17233     ExprResult VisitExpr(Expr *E) {
17234       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17235         << E->getSourceRange();
17236       return ExprError();
17237     }
17238 
17239     /// Rebuild an expression which simply semantically wraps another
17240     /// expression which it shares the type and value kind of.
17241     template <class T> ExprResult rebuildSugarExpr(T *E) {
17242       ExprResult SubResult = Visit(E->getSubExpr());
17243       if (SubResult.isInvalid()) return ExprError();
17244 
17245       Expr *SubExpr = SubResult.get();
17246       E->setSubExpr(SubExpr);
17247       E->setType(SubExpr->getType());
17248       E->setValueKind(SubExpr->getValueKind());
17249       assert(E->getObjectKind() == OK_Ordinary);
17250       return E;
17251     }
17252 
17253     ExprResult VisitParenExpr(ParenExpr *E) {
17254       return rebuildSugarExpr(E);
17255     }
17256 
17257     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17258       return rebuildSugarExpr(E);
17259     }
17260 
17261     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17262       ExprResult SubResult = Visit(E->getSubExpr());
17263       if (SubResult.isInvalid()) return ExprError();
17264 
17265       Expr *SubExpr = SubResult.get();
17266       E->setSubExpr(SubExpr);
17267       E->setType(S.Context.getPointerType(SubExpr->getType()));
17268       assert(E->getValueKind() == VK_RValue);
17269       assert(E->getObjectKind() == OK_Ordinary);
17270       return E;
17271     }
17272 
17273     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17274       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17275 
17276       E->setType(VD->getType());
17277 
17278       assert(E->getValueKind() == VK_RValue);
17279       if (S.getLangOpts().CPlusPlus &&
17280           !(isa<CXXMethodDecl>(VD) &&
17281             cast<CXXMethodDecl>(VD)->isInstance()))
17282         E->setValueKind(VK_LValue);
17283 
17284       return E;
17285     }
17286 
17287     ExprResult VisitMemberExpr(MemberExpr *E) {
17288       return resolveDecl(E, E->getMemberDecl());
17289     }
17290 
17291     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17292       return resolveDecl(E, E->getDecl());
17293     }
17294   };
17295 }
17296 
17297 /// Given a function expression of unknown-any type, try to rebuild it
17298 /// to have a function type.
17299 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17300   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17301   if (Result.isInvalid()) return ExprError();
17302   return S.DefaultFunctionArrayConversion(Result.get());
17303 }
17304 
17305 namespace {
17306   /// A visitor for rebuilding an expression of type __unknown_anytype
17307   /// into one which resolves the type directly on the referring
17308   /// expression.  Strict preservation of the original source
17309   /// structure is not a goal.
17310   struct RebuildUnknownAnyExpr
17311     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17312 
17313     Sema &S;
17314 
17315     /// The current destination type.
17316     QualType DestType;
17317 
17318     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17319       : S(S), DestType(CastType) {}
17320 
17321     ExprResult VisitStmt(Stmt *S) {
17322       llvm_unreachable("unexpected statement!");
17323     }
17324 
17325     ExprResult VisitExpr(Expr *E) {
17326       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17327         << E->getSourceRange();
17328       return ExprError();
17329     }
17330 
17331     ExprResult VisitCallExpr(CallExpr *E);
17332     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17333 
17334     /// Rebuild an expression which simply semantically wraps another
17335     /// expression which it shares the type and value kind of.
17336     template <class T> ExprResult rebuildSugarExpr(T *E) {
17337       ExprResult SubResult = Visit(E->getSubExpr());
17338       if (SubResult.isInvalid()) return ExprError();
17339       Expr *SubExpr = SubResult.get();
17340       E->setSubExpr(SubExpr);
17341       E->setType(SubExpr->getType());
17342       E->setValueKind(SubExpr->getValueKind());
17343       assert(E->getObjectKind() == OK_Ordinary);
17344       return E;
17345     }
17346 
17347     ExprResult VisitParenExpr(ParenExpr *E) {
17348       return rebuildSugarExpr(E);
17349     }
17350 
17351     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17352       return rebuildSugarExpr(E);
17353     }
17354 
17355     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17356       const PointerType *Ptr = DestType->getAs<PointerType>();
17357       if (!Ptr) {
17358         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17359           << E->getSourceRange();
17360         return ExprError();
17361       }
17362 
17363       if (isa<CallExpr>(E->getSubExpr())) {
17364         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17365           << E->getSourceRange();
17366         return ExprError();
17367       }
17368 
17369       assert(E->getValueKind() == VK_RValue);
17370       assert(E->getObjectKind() == OK_Ordinary);
17371       E->setType(DestType);
17372 
17373       // Build the sub-expression as if it were an object of the pointee type.
17374       DestType = Ptr->getPointeeType();
17375       ExprResult SubResult = Visit(E->getSubExpr());
17376       if (SubResult.isInvalid()) return ExprError();
17377       E->setSubExpr(SubResult.get());
17378       return E;
17379     }
17380 
17381     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17382 
17383     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17384 
17385     ExprResult VisitMemberExpr(MemberExpr *E) {
17386       return resolveDecl(E, E->getMemberDecl());
17387     }
17388 
17389     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17390       return resolveDecl(E, E->getDecl());
17391     }
17392   };
17393 }
17394 
17395 /// Rebuilds a call expression which yielded __unknown_anytype.
17396 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17397   Expr *CalleeExpr = E->getCallee();
17398 
17399   enum FnKind {
17400     FK_MemberFunction,
17401     FK_FunctionPointer,
17402     FK_BlockPointer
17403   };
17404 
17405   FnKind Kind;
17406   QualType CalleeType = CalleeExpr->getType();
17407   if (CalleeType == S.Context.BoundMemberTy) {
17408     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17409     Kind = FK_MemberFunction;
17410     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17411   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17412     CalleeType = Ptr->getPointeeType();
17413     Kind = FK_FunctionPointer;
17414   } else {
17415     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17416     Kind = FK_BlockPointer;
17417   }
17418   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17419 
17420   // Verify that this is a legal result type of a function.
17421   if (DestType->isArrayType() || DestType->isFunctionType()) {
17422     unsigned diagID = diag::err_func_returning_array_function;
17423     if (Kind == FK_BlockPointer)
17424       diagID = diag::err_block_returning_array_function;
17425 
17426     S.Diag(E->getExprLoc(), diagID)
17427       << DestType->isFunctionType() << DestType;
17428     return ExprError();
17429   }
17430 
17431   // Otherwise, go ahead and set DestType as the call's result.
17432   E->setType(DestType.getNonLValueExprType(S.Context));
17433   E->setValueKind(Expr::getValueKindForType(DestType));
17434   assert(E->getObjectKind() == OK_Ordinary);
17435 
17436   // Rebuild the function type, replacing the result type with DestType.
17437   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17438   if (Proto) {
17439     // __unknown_anytype(...) is a special case used by the debugger when
17440     // it has no idea what a function's signature is.
17441     //
17442     // We want to build this call essentially under the K&R
17443     // unprototyped rules, but making a FunctionNoProtoType in C++
17444     // would foul up all sorts of assumptions.  However, we cannot
17445     // simply pass all arguments as variadic arguments, nor can we
17446     // portably just call the function under a non-variadic type; see
17447     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17448     // However, it turns out that in practice it is generally safe to
17449     // call a function declared as "A foo(B,C,D);" under the prototype
17450     // "A foo(B,C,D,...);".  The only known exception is with the
17451     // Windows ABI, where any variadic function is implicitly cdecl
17452     // regardless of its normal CC.  Therefore we change the parameter
17453     // types to match the types of the arguments.
17454     //
17455     // This is a hack, but it is far superior to moving the
17456     // corresponding target-specific code from IR-gen to Sema/AST.
17457 
17458     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17459     SmallVector<QualType, 8> ArgTypes;
17460     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17461       ArgTypes.reserve(E->getNumArgs());
17462       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17463         Expr *Arg = E->getArg(i);
17464         QualType ArgType = Arg->getType();
17465         if (E->isLValue()) {
17466           ArgType = S.Context.getLValueReferenceType(ArgType);
17467         } else if (E->isXValue()) {
17468           ArgType = S.Context.getRValueReferenceType(ArgType);
17469         }
17470         ArgTypes.push_back(ArgType);
17471       }
17472       ParamTypes = ArgTypes;
17473     }
17474     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17475                                          Proto->getExtProtoInfo());
17476   } else {
17477     DestType = S.Context.getFunctionNoProtoType(DestType,
17478                                                 FnType->getExtInfo());
17479   }
17480 
17481   // Rebuild the appropriate pointer-to-function type.
17482   switch (Kind) {
17483   case FK_MemberFunction:
17484     // Nothing to do.
17485     break;
17486 
17487   case FK_FunctionPointer:
17488     DestType = S.Context.getPointerType(DestType);
17489     break;
17490 
17491   case FK_BlockPointer:
17492     DestType = S.Context.getBlockPointerType(DestType);
17493     break;
17494   }
17495 
17496   // Finally, we can recurse.
17497   ExprResult CalleeResult = Visit(CalleeExpr);
17498   if (!CalleeResult.isUsable()) return ExprError();
17499   E->setCallee(CalleeResult.get());
17500 
17501   // Bind a temporary if necessary.
17502   return S.MaybeBindToTemporary(E);
17503 }
17504 
17505 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17506   // Verify that this is a legal result type of a call.
17507   if (DestType->isArrayType() || DestType->isFunctionType()) {
17508     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17509       << DestType->isFunctionType() << DestType;
17510     return ExprError();
17511   }
17512 
17513   // Rewrite the method result type if available.
17514   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17515     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17516     Method->setReturnType(DestType);
17517   }
17518 
17519   // Change the type of the message.
17520   E->setType(DestType.getNonReferenceType());
17521   E->setValueKind(Expr::getValueKindForType(DestType));
17522 
17523   return S.MaybeBindToTemporary(E);
17524 }
17525 
17526 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17527   // The only case we should ever see here is a function-to-pointer decay.
17528   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17529     assert(E->getValueKind() == VK_RValue);
17530     assert(E->getObjectKind() == OK_Ordinary);
17531 
17532     E->setType(DestType);
17533 
17534     // Rebuild the sub-expression as the pointee (function) type.
17535     DestType = DestType->castAs<PointerType>()->getPointeeType();
17536 
17537     ExprResult Result = Visit(E->getSubExpr());
17538     if (!Result.isUsable()) return ExprError();
17539 
17540     E->setSubExpr(Result.get());
17541     return E;
17542   } else if (E->getCastKind() == CK_LValueToRValue) {
17543     assert(E->getValueKind() == VK_RValue);
17544     assert(E->getObjectKind() == OK_Ordinary);
17545 
17546     assert(isa<BlockPointerType>(E->getType()));
17547 
17548     E->setType(DestType);
17549 
17550     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17551     DestType = S.Context.getLValueReferenceType(DestType);
17552 
17553     ExprResult Result = Visit(E->getSubExpr());
17554     if (!Result.isUsable()) return ExprError();
17555 
17556     E->setSubExpr(Result.get());
17557     return E;
17558   } else {
17559     llvm_unreachable("Unhandled cast type!");
17560   }
17561 }
17562 
17563 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17564   ExprValueKind ValueKind = VK_LValue;
17565   QualType Type = DestType;
17566 
17567   // We know how to make this work for certain kinds of decls:
17568 
17569   //  - functions
17570   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17571     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17572       DestType = Ptr->getPointeeType();
17573       ExprResult Result = resolveDecl(E, VD);
17574       if (Result.isInvalid()) return ExprError();
17575       return S.ImpCastExprToType(Result.get(), Type,
17576                                  CK_FunctionToPointerDecay, VK_RValue);
17577     }
17578 
17579     if (!Type->isFunctionType()) {
17580       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17581         << VD << E->getSourceRange();
17582       return ExprError();
17583     }
17584     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17585       // We must match the FunctionDecl's type to the hack introduced in
17586       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17587       // type. See the lengthy commentary in that routine.
17588       QualType FDT = FD->getType();
17589       const FunctionType *FnType = FDT->castAs<FunctionType>();
17590       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17591       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17592       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17593         SourceLocation Loc = FD->getLocation();
17594         FunctionDecl *NewFD = FunctionDecl::Create(
17595             S.Context, FD->getDeclContext(), Loc, Loc,
17596             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17597             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17598             /*ConstexprKind*/ CSK_unspecified);
17599 
17600         if (FD->getQualifier())
17601           NewFD->setQualifierInfo(FD->getQualifierLoc());
17602 
17603         SmallVector<ParmVarDecl*, 16> Params;
17604         for (const auto &AI : FT->param_types()) {
17605           ParmVarDecl *Param =
17606             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17607           Param->setScopeInfo(0, Params.size());
17608           Params.push_back(Param);
17609         }
17610         NewFD->setParams(Params);
17611         DRE->setDecl(NewFD);
17612         VD = DRE->getDecl();
17613       }
17614     }
17615 
17616     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17617       if (MD->isInstance()) {
17618         ValueKind = VK_RValue;
17619         Type = S.Context.BoundMemberTy;
17620       }
17621 
17622     // Function references aren't l-values in C.
17623     if (!S.getLangOpts().CPlusPlus)
17624       ValueKind = VK_RValue;
17625 
17626   //  - variables
17627   } else if (isa<VarDecl>(VD)) {
17628     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17629       Type = RefTy->getPointeeType();
17630     } else if (Type->isFunctionType()) {
17631       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17632         << VD << E->getSourceRange();
17633       return ExprError();
17634     }
17635 
17636   //  - nothing else
17637   } else {
17638     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17639       << VD << E->getSourceRange();
17640     return ExprError();
17641   }
17642 
17643   // Modifying the declaration like this is friendly to IR-gen but
17644   // also really dangerous.
17645   VD->setType(DestType);
17646   E->setType(Type);
17647   E->setValueKind(ValueKind);
17648   return E;
17649 }
17650 
17651 /// Check a cast of an unknown-any type.  We intentionally only
17652 /// trigger this for C-style casts.
17653 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17654                                      Expr *CastExpr, CastKind &CastKind,
17655                                      ExprValueKind &VK, CXXCastPath &Path) {
17656   // The type we're casting to must be either void or complete.
17657   if (!CastType->isVoidType() &&
17658       RequireCompleteType(TypeRange.getBegin(), CastType,
17659                           diag::err_typecheck_cast_to_incomplete))
17660     return ExprError();
17661 
17662   // Rewrite the casted expression from scratch.
17663   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17664   if (!result.isUsable()) return ExprError();
17665 
17666   CastExpr = result.get();
17667   VK = CastExpr->getValueKind();
17668   CastKind = CK_NoOp;
17669 
17670   return CastExpr;
17671 }
17672 
17673 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17674   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17675 }
17676 
17677 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17678                                     Expr *arg, QualType &paramType) {
17679   // If the syntactic form of the argument is not an explicit cast of
17680   // any sort, just do default argument promotion.
17681   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17682   if (!castArg) {
17683     ExprResult result = DefaultArgumentPromotion(arg);
17684     if (result.isInvalid()) return ExprError();
17685     paramType = result.get()->getType();
17686     return result;
17687   }
17688 
17689   // Otherwise, use the type that was written in the explicit cast.
17690   assert(!arg->hasPlaceholderType());
17691   paramType = castArg->getTypeAsWritten();
17692 
17693   // Copy-initialize a parameter of that type.
17694   InitializedEntity entity =
17695     InitializedEntity::InitializeParameter(Context, paramType,
17696                                            /*consumed*/ false);
17697   return PerformCopyInitialization(entity, callLoc, arg);
17698 }
17699 
17700 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17701   Expr *orig = E;
17702   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17703   while (true) {
17704     E = E->IgnoreParenImpCasts();
17705     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17706       E = call->getCallee();
17707       diagID = diag::err_uncasted_call_of_unknown_any;
17708     } else {
17709       break;
17710     }
17711   }
17712 
17713   SourceLocation loc;
17714   NamedDecl *d;
17715   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17716     loc = ref->getLocation();
17717     d = ref->getDecl();
17718   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17719     loc = mem->getMemberLoc();
17720     d = mem->getMemberDecl();
17721   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17722     diagID = diag::err_uncasted_call_of_unknown_any;
17723     loc = msg->getSelectorStartLoc();
17724     d = msg->getMethodDecl();
17725     if (!d) {
17726       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17727         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17728         << orig->getSourceRange();
17729       return ExprError();
17730     }
17731   } else {
17732     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17733       << E->getSourceRange();
17734     return ExprError();
17735   }
17736 
17737   S.Diag(loc, diagID) << d << orig->getSourceRange();
17738 
17739   // Never recoverable.
17740   return ExprError();
17741 }
17742 
17743 /// Check for operands with placeholder types and complain if found.
17744 /// Returns ExprError() if there was an error and no recovery was possible.
17745 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17746   if (!getLangOpts().CPlusPlus) {
17747     // C cannot handle TypoExpr nodes on either side of a binop because it
17748     // doesn't handle dependent types properly, so make sure any TypoExprs have
17749     // been dealt with before checking the operands.
17750     ExprResult Result = CorrectDelayedTyposInExpr(E);
17751     if (!Result.isUsable()) return ExprError();
17752     E = Result.get();
17753   }
17754 
17755   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17756   if (!placeholderType) return E;
17757 
17758   switch (placeholderType->getKind()) {
17759 
17760   // Overloaded expressions.
17761   case BuiltinType::Overload: {
17762     // Try to resolve a single function template specialization.
17763     // This is obligatory.
17764     ExprResult Result = E;
17765     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17766       return Result;
17767 
17768     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17769     // leaves Result unchanged on failure.
17770     Result = E;
17771     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17772       return Result;
17773 
17774     // If that failed, try to recover with a call.
17775     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17776                          /*complain*/ true);
17777     return Result;
17778   }
17779 
17780   // Bound member functions.
17781   case BuiltinType::BoundMember: {
17782     ExprResult result = E;
17783     const Expr *BME = E->IgnoreParens();
17784     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17785     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17786     if (isa<CXXPseudoDestructorExpr>(BME)) {
17787       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17788     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17789       if (ME->getMemberNameInfo().getName().getNameKind() ==
17790           DeclarationName::CXXDestructorName)
17791         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17792     }
17793     tryToRecoverWithCall(result, PD,
17794                          /*complain*/ true);
17795     return result;
17796   }
17797 
17798   // ARC unbridged casts.
17799   case BuiltinType::ARCUnbridgedCast: {
17800     Expr *realCast = stripARCUnbridgedCast(E);
17801     diagnoseARCUnbridgedCast(realCast);
17802     return realCast;
17803   }
17804 
17805   // Expressions of unknown type.
17806   case BuiltinType::UnknownAny:
17807     return diagnoseUnknownAnyExpr(*this, E);
17808 
17809   // Pseudo-objects.
17810   case BuiltinType::PseudoObject:
17811     return checkPseudoObjectRValue(E);
17812 
17813   case BuiltinType::BuiltinFn: {
17814     // Accept __noop without parens by implicitly converting it to a call expr.
17815     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17816     if (DRE) {
17817       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17818       if (FD->getBuiltinID() == Builtin::BI__noop) {
17819         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17820                               CK_BuiltinFnToFnPtr)
17821                 .get();
17822         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17823                                 VK_RValue, SourceLocation());
17824       }
17825     }
17826 
17827     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17828     return ExprError();
17829   }
17830 
17831   // Expressions of unknown type.
17832   case BuiltinType::OMPArraySection:
17833     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17834     return ExprError();
17835 
17836   // Everything else should be impossible.
17837 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17838   case BuiltinType::Id:
17839 #include "clang/Basic/OpenCLImageTypes.def"
17840 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17841   case BuiltinType::Id:
17842 #include "clang/Basic/OpenCLExtensionTypes.def"
17843 #define SVE_TYPE(Name, Id, SingletonId) \
17844   case BuiltinType::Id:
17845 #include "clang/Basic/AArch64SVEACLETypes.def"
17846 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17847 #define PLACEHOLDER_TYPE(Id, SingletonId)
17848 #include "clang/AST/BuiltinTypes.def"
17849     break;
17850   }
17851 
17852   llvm_unreachable("invalid placeholder type!");
17853 }
17854 
17855 bool Sema::CheckCaseExpression(Expr *E) {
17856   if (E->isTypeDependent())
17857     return true;
17858   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17859     return E->getType()->isIntegralOrEnumerationType();
17860   return false;
17861 }
17862 
17863 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17864 ExprResult
17865 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17866   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17867          "Unknown Objective-C Boolean value!");
17868   QualType BoolT = Context.ObjCBuiltinBoolTy;
17869   if (!Context.getBOOLDecl()) {
17870     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17871                         Sema::LookupOrdinaryName);
17872     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17873       NamedDecl *ND = Result.getFoundDecl();
17874       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17875         Context.setBOOLDecl(TD);
17876     }
17877   }
17878   if (Context.getBOOLDecl())
17879     BoolT = Context.getBOOLType();
17880   return new (Context)
17881       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17882 }
17883 
17884 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17885     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17886     SourceLocation RParen) {
17887 
17888   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17889 
17890   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17891     return Spec.getPlatform() == Platform;
17892   });
17893 
17894   VersionTuple Version;
17895   if (Spec != AvailSpecs.end())
17896     Version = Spec->getVersion();
17897 
17898   // The use of `@available` in the enclosing function should be analyzed to
17899   // warn when it's used inappropriately (i.e. not if(@available)).
17900   if (getCurFunctionOrMethodDecl())
17901     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17902   else if (getCurBlock() || getCurLambda())
17903     getCurFunction()->HasPotentialAvailabilityViolations = true;
17904 
17905   return new (Context)
17906       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
17907 }
17908