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, ArrayType::Normal,
3211                                            /*IndexTypeQuals*/ 0);
3212       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3213                                  /*Pascal*/ false, ResTy, Loc);
3214     } else {
3215       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3216       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3217                                            /*IndexTypeQuals*/ 0);
3218       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3219                                  /*Pascal*/ false, ResTy, Loc);
3220     }
3221   }
3222 
3223   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3224 }
3225 
3226 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3227   PredefinedExpr::IdentKind IK;
3228 
3229   switch (Kind) {
3230   default: llvm_unreachable("Unknown simple primary expr!");
3231   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3232   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3233   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3234   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3235   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3236   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3237   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3238   }
3239 
3240   return BuildPredefinedExpr(Loc, IK);
3241 }
3242 
3243 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3244   SmallString<16> CharBuffer;
3245   bool Invalid = false;
3246   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3247   if (Invalid)
3248     return ExprError();
3249 
3250   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3251                             PP, Tok.getKind());
3252   if (Literal.hadError())
3253     return ExprError();
3254 
3255   QualType Ty;
3256   if (Literal.isWide())
3257     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3258   else if (Literal.isUTF8() && getLangOpts().Char8)
3259     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3260   else if (Literal.isUTF16())
3261     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3262   else if (Literal.isUTF32())
3263     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3264   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3265     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3266   else
3267     Ty = Context.CharTy;  // 'x' -> char in C++
3268 
3269   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3270   if (Literal.isWide())
3271     Kind = CharacterLiteral::Wide;
3272   else if (Literal.isUTF16())
3273     Kind = CharacterLiteral::UTF16;
3274   else if (Literal.isUTF32())
3275     Kind = CharacterLiteral::UTF32;
3276   else if (Literal.isUTF8())
3277     Kind = CharacterLiteral::UTF8;
3278 
3279   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3280                                              Tok.getLocation());
3281 
3282   if (Literal.getUDSuffix().empty())
3283     return Lit;
3284 
3285   // We're building a user-defined literal.
3286   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3287   SourceLocation UDSuffixLoc =
3288     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3289 
3290   // Make sure we're allowed user-defined literals here.
3291   if (!UDLScope)
3292     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3293 
3294   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3295   //   operator "" X (ch)
3296   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3297                                         Lit, Tok.getLocation());
3298 }
3299 
3300 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3301   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3302   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3303                                 Context.IntTy, Loc);
3304 }
3305 
3306 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3307                                   QualType Ty, SourceLocation Loc) {
3308   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3309 
3310   using llvm::APFloat;
3311   APFloat Val(Format);
3312 
3313   APFloat::opStatus result = Literal.GetFloatValue(Val);
3314 
3315   // Overflow is always an error, but underflow is only an error if
3316   // we underflowed to zero (APFloat reports denormals as underflow).
3317   if ((result & APFloat::opOverflow) ||
3318       ((result & APFloat::opUnderflow) && Val.isZero())) {
3319     unsigned diagnostic;
3320     SmallString<20> buffer;
3321     if (result & APFloat::opOverflow) {
3322       diagnostic = diag::warn_float_overflow;
3323       APFloat::getLargest(Format).toString(buffer);
3324     } else {
3325       diagnostic = diag::warn_float_underflow;
3326       APFloat::getSmallest(Format).toString(buffer);
3327     }
3328 
3329     S.Diag(Loc, diagnostic)
3330       << Ty
3331       << StringRef(buffer.data(), buffer.size());
3332   }
3333 
3334   bool isExact = (result == APFloat::opOK);
3335   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3336 }
3337 
3338 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3339   assert(E && "Invalid expression");
3340 
3341   if (E->isValueDependent())
3342     return false;
3343 
3344   QualType QT = E->getType();
3345   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3346     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3347     return true;
3348   }
3349 
3350   llvm::APSInt ValueAPS;
3351   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3352 
3353   if (R.isInvalid())
3354     return true;
3355 
3356   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3357   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3358     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3359         << ValueAPS.toString(10) << ValueIsPositive;
3360     return true;
3361   }
3362 
3363   return false;
3364 }
3365 
3366 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3367   // Fast path for a single digit (which is quite common).  A single digit
3368   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3369   if (Tok.getLength() == 1) {
3370     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3371     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3372   }
3373 
3374   SmallString<128> SpellingBuffer;
3375   // NumericLiteralParser wants to overread by one character.  Add padding to
3376   // the buffer in case the token is copied to the buffer.  If getSpelling()
3377   // returns a StringRef to the memory buffer, it should have a null char at
3378   // the EOF, so it is also safe.
3379   SpellingBuffer.resize(Tok.getLength() + 1);
3380 
3381   // Get the spelling of the token, which eliminates trigraphs, etc.
3382   bool Invalid = false;
3383   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3384   if (Invalid)
3385     return ExprError();
3386 
3387   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3388   if (Literal.hadError)
3389     return ExprError();
3390 
3391   if (Literal.hasUDSuffix()) {
3392     // We're building a user-defined literal.
3393     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3394     SourceLocation UDSuffixLoc =
3395       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3396 
3397     // Make sure we're allowed user-defined literals here.
3398     if (!UDLScope)
3399       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3400 
3401     QualType CookedTy;
3402     if (Literal.isFloatingLiteral()) {
3403       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3404       // long double, the literal is treated as a call of the form
3405       //   operator "" X (f L)
3406       CookedTy = Context.LongDoubleTy;
3407     } else {
3408       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3409       // unsigned long long, the literal is treated as a call of the form
3410       //   operator "" X (n ULL)
3411       CookedTy = Context.UnsignedLongLongTy;
3412     }
3413 
3414     DeclarationName OpName =
3415       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3416     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3417     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3418 
3419     SourceLocation TokLoc = Tok.getLocation();
3420 
3421     // Perform literal operator lookup to determine if we're building a raw
3422     // literal or a cooked one.
3423     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3424     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3425                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3426                                   /*AllowStringTemplate*/ false,
3427                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3428     case LOLR_ErrorNoDiagnostic:
3429       // Lookup failure for imaginary constants isn't fatal, there's still the
3430       // GNU extension producing _Complex types.
3431       break;
3432     case LOLR_Error:
3433       return ExprError();
3434     case LOLR_Cooked: {
3435       Expr *Lit;
3436       if (Literal.isFloatingLiteral()) {
3437         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3438       } else {
3439         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3440         if (Literal.GetIntegerValue(ResultVal))
3441           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3442               << /* Unsigned */ 1;
3443         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3444                                      Tok.getLocation());
3445       }
3446       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3447     }
3448 
3449     case LOLR_Raw: {
3450       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3451       // literal is treated as a call of the form
3452       //   operator "" X ("n")
3453       unsigned Length = Literal.getUDSuffixOffset();
3454       QualType StrTy = Context.getConstantArrayType(
3455           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3456           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3457       Expr *Lit = StringLiteral::Create(
3458           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3459           /*Pascal*/false, StrTy, &TokLoc, 1);
3460       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3461     }
3462 
3463     case LOLR_Template: {
3464       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3465       // template), L is treated as a call fo the form
3466       //   operator "" X <'c1', 'c2', ... 'ck'>()
3467       // where n is the source character sequence c1 c2 ... ck.
3468       TemplateArgumentListInfo ExplicitArgs;
3469       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3470       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3471       llvm::APSInt Value(CharBits, CharIsUnsigned);
3472       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3473         Value = TokSpelling[I];
3474         TemplateArgument Arg(Context, Value, Context.CharTy);
3475         TemplateArgumentLocInfo ArgInfo;
3476         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3477       }
3478       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3479                                       &ExplicitArgs);
3480     }
3481     case LOLR_StringTemplate:
3482       llvm_unreachable("unexpected literal operator lookup result");
3483     }
3484   }
3485 
3486   Expr *Res;
3487 
3488   if (Literal.isFixedPointLiteral()) {
3489     QualType Ty;
3490 
3491     if (Literal.isAccum) {
3492       if (Literal.isHalf) {
3493         Ty = Context.ShortAccumTy;
3494       } else if (Literal.isLong) {
3495         Ty = Context.LongAccumTy;
3496       } else {
3497         Ty = Context.AccumTy;
3498       }
3499     } else if (Literal.isFract) {
3500       if (Literal.isHalf) {
3501         Ty = Context.ShortFractTy;
3502       } else if (Literal.isLong) {
3503         Ty = Context.LongFractTy;
3504       } else {
3505         Ty = Context.FractTy;
3506       }
3507     }
3508 
3509     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3510 
3511     bool isSigned = !Literal.isUnsigned;
3512     unsigned scale = Context.getFixedPointScale(Ty);
3513     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3514 
3515     llvm::APInt Val(bit_width, 0, isSigned);
3516     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3517     bool ValIsZero = Val.isNullValue() && !Overflowed;
3518 
3519     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3520     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3521       // Clause 6.4.4 - The value of a constant shall be in the range of
3522       // representable values for its type, with exception for constants of a
3523       // fract type with a value of exactly 1; such a constant shall denote
3524       // the maximal value for the type.
3525       --Val;
3526     else if (Val.ugt(MaxVal) || Overflowed)
3527       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3528 
3529     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3530                                               Tok.getLocation(), scale);
3531   } else if (Literal.isFloatingLiteral()) {
3532     QualType Ty;
3533     if (Literal.isHalf){
3534       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3535         Ty = Context.HalfTy;
3536       else {
3537         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3538         return ExprError();
3539       }
3540     } else if (Literal.isFloat)
3541       Ty = Context.FloatTy;
3542     else if (Literal.isLong)
3543       Ty = Context.LongDoubleTy;
3544     else if (Literal.isFloat16)
3545       Ty = Context.Float16Ty;
3546     else if (Literal.isFloat128)
3547       Ty = Context.Float128Ty;
3548     else
3549       Ty = Context.DoubleTy;
3550 
3551     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3552 
3553     if (Ty == Context.DoubleTy) {
3554       if (getLangOpts().SinglePrecisionConstants) {
3555         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3556         if (BTy->getKind() != BuiltinType::Float) {
3557           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3558         }
3559       } else if (getLangOpts().OpenCL &&
3560                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3561         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3562         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3563         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3564       }
3565     }
3566   } else if (!Literal.isIntegerLiteral()) {
3567     return ExprError();
3568   } else {
3569     QualType Ty;
3570 
3571     // 'long long' is a C99 or C++11 feature.
3572     if (!getLangOpts().C99 && Literal.isLongLong) {
3573       if (getLangOpts().CPlusPlus)
3574         Diag(Tok.getLocation(),
3575              getLangOpts().CPlusPlus11 ?
3576              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3577       else
3578         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3579     }
3580 
3581     // Get the value in the widest-possible width.
3582     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3583     llvm::APInt ResultVal(MaxWidth, 0);
3584 
3585     if (Literal.GetIntegerValue(ResultVal)) {
3586       // If this value didn't fit into uintmax_t, error and force to ull.
3587       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3588           << /* Unsigned */ 1;
3589       Ty = Context.UnsignedLongLongTy;
3590       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3591              "long long is not intmax_t?");
3592     } else {
3593       // If this value fits into a ULL, try to figure out what else it fits into
3594       // according to the rules of C99 6.4.4.1p5.
3595 
3596       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3597       // be an unsigned int.
3598       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3599 
3600       // Check from smallest to largest, picking the smallest type we can.
3601       unsigned Width = 0;
3602 
3603       // Microsoft specific integer suffixes are explicitly sized.
3604       if (Literal.MicrosoftInteger) {
3605         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3606           Width = 8;
3607           Ty = Context.CharTy;
3608         } else {
3609           Width = Literal.MicrosoftInteger;
3610           Ty = Context.getIntTypeForBitwidth(Width,
3611                                              /*Signed=*/!Literal.isUnsigned);
3612         }
3613       }
3614 
3615       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3616         // Are int/unsigned possibilities?
3617         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3618 
3619         // Does it fit in a unsigned int?
3620         if (ResultVal.isIntN(IntSize)) {
3621           // Does it fit in a signed int?
3622           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3623             Ty = Context.IntTy;
3624           else if (AllowUnsigned)
3625             Ty = Context.UnsignedIntTy;
3626           Width = IntSize;
3627         }
3628       }
3629 
3630       // Are long/unsigned long possibilities?
3631       if (Ty.isNull() && !Literal.isLongLong) {
3632         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3633 
3634         // Does it fit in a unsigned long?
3635         if (ResultVal.isIntN(LongSize)) {
3636           // Does it fit in a signed long?
3637           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3638             Ty = Context.LongTy;
3639           else if (AllowUnsigned)
3640             Ty = Context.UnsignedLongTy;
3641           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3642           // is compatible.
3643           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3644             const unsigned LongLongSize =
3645                 Context.getTargetInfo().getLongLongWidth();
3646             Diag(Tok.getLocation(),
3647                  getLangOpts().CPlusPlus
3648                      ? Literal.isLong
3649                            ? diag::warn_old_implicitly_unsigned_long_cxx
3650                            : /*C++98 UB*/ diag::
3651                                  ext_old_implicitly_unsigned_long_cxx
3652                      : diag::warn_old_implicitly_unsigned_long)
3653                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3654                                             : /*will be ill-formed*/ 1);
3655             Ty = Context.UnsignedLongTy;
3656           }
3657           Width = LongSize;
3658         }
3659       }
3660 
3661       // Check long long if needed.
3662       if (Ty.isNull()) {
3663         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3664 
3665         // Does it fit in a unsigned long long?
3666         if (ResultVal.isIntN(LongLongSize)) {
3667           // Does it fit in a signed long long?
3668           // To be compatible with MSVC, hex integer literals ending with the
3669           // LL or i64 suffix are always signed in Microsoft mode.
3670           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3671               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3672             Ty = Context.LongLongTy;
3673           else if (AllowUnsigned)
3674             Ty = Context.UnsignedLongLongTy;
3675           Width = LongLongSize;
3676         }
3677       }
3678 
3679       // If we still couldn't decide a type, we probably have something that
3680       // does not fit in a signed long long, but has no U suffix.
3681       if (Ty.isNull()) {
3682         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3683         Ty = Context.UnsignedLongLongTy;
3684         Width = Context.getTargetInfo().getLongLongWidth();
3685       }
3686 
3687       if (ResultVal.getBitWidth() != Width)
3688         ResultVal = ResultVal.trunc(Width);
3689     }
3690     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3691   }
3692 
3693   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3694   if (Literal.isImaginary) {
3695     Res = new (Context) ImaginaryLiteral(Res,
3696                                         Context.getComplexType(Res->getType()));
3697 
3698     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3699   }
3700   return Res;
3701 }
3702 
3703 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3704   assert(E && "ActOnParenExpr() missing expr");
3705   return new (Context) ParenExpr(L, R, E);
3706 }
3707 
3708 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3709                                          SourceLocation Loc,
3710                                          SourceRange ArgRange) {
3711   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3712   // scalar or vector data type argument..."
3713   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3714   // type (C99 6.2.5p18) or void.
3715   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3716     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3717       << T << ArgRange;
3718     return true;
3719   }
3720 
3721   assert((T->isVoidType() || !T->isIncompleteType()) &&
3722          "Scalar types should always be complete");
3723   return false;
3724 }
3725 
3726 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3727                                            SourceLocation Loc,
3728                                            SourceRange ArgRange,
3729                                            UnaryExprOrTypeTrait TraitKind) {
3730   // Invalid types must be hard errors for SFINAE in C++.
3731   if (S.LangOpts.CPlusPlus)
3732     return true;
3733 
3734   // C99 6.5.3.4p1:
3735   if (T->isFunctionType() &&
3736       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3737        TraitKind == UETT_PreferredAlignOf)) {
3738     // sizeof(function)/alignof(function) is allowed as an extension.
3739     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3740       << TraitKind << ArgRange;
3741     return false;
3742   }
3743 
3744   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3745   // this is an error (OpenCL v1.1 s6.3.k)
3746   if (T->isVoidType()) {
3747     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3748                                         : diag::ext_sizeof_alignof_void_type;
3749     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3750     return false;
3751   }
3752 
3753   return true;
3754 }
3755 
3756 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3757                                              SourceLocation Loc,
3758                                              SourceRange ArgRange,
3759                                              UnaryExprOrTypeTrait TraitKind) {
3760   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3761   // runtime doesn't allow it.
3762   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3763     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3764       << T << (TraitKind == UETT_SizeOf)
3765       << ArgRange;
3766     return true;
3767   }
3768 
3769   return false;
3770 }
3771 
3772 /// Check whether E is a pointer from a decayed array type (the decayed
3773 /// pointer type is equal to T) and emit a warning if it is.
3774 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3775                                      Expr *E) {
3776   // Don't warn if the operation changed the type.
3777   if (T != E->getType())
3778     return;
3779 
3780   // Now look for array decays.
3781   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3782   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3783     return;
3784 
3785   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3786                                              << ICE->getType()
3787                                              << ICE->getSubExpr()->getType();
3788 }
3789 
3790 /// Check the constraints on expression operands to unary type expression
3791 /// and type traits.
3792 ///
3793 /// Completes any types necessary and validates the constraints on the operand
3794 /// expression. The logic mostly mirrors the type-based overload, but may modify
3795 /// the expression as it completes the type for that expression through template
3796 /// instantiation, etc.
3797 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3798                                             UnaryExprOrTypeTrait ExprKind) {
3799   QualType ExprTy = E->getType();
3800   assert(!ExprTy->isReferenceType());
3801 
3802   if (ExprKind == UETT_VecStep)
3803     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3804                                         E->getSourceRange());
3805 
3806   // Whitelist some types as extensions
3807   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3808                                       E->getSourceRange(), ExprKind))
3809     return false;
3810 
3811   // 'alignof' applied to an expression only requires the base element type of
3812   // the expression to be complete. 'sizeof' requires the expression's type to
3813   // be complete (and will attempt to complete it if it's an array of unknown
3814   // bound).
3815   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3816     if (RequireCompleteType(E->getExprLoc(),
3817                             Context.getBaseElementType(E->getType()),
3818                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3819                             E->getSourceRange()))
3820       return true;
3821   } else {
3822     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3823                                 ExprKind, E->getSourceRange()))
3824       return true;
3825   }
3826 
3827   // Completing the expression's type may have changed it.
3828   ExprTy = E->getType();
3829   assert(!ExprTy->isReferenceType());
3830 
3831   if (ExprTy->isFunctionType()) {
3832     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3833       << ExprKind << E->getSourceRange();
3834     return true;
3835   }
3836 
3837   // The operand for sizeof and alignof is in an unevaluated expression context,
3838   // so side effects could result in unintended consequences.
3839   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3840        ExprKind == UETT_PreferredAlignOf) &&
3841       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3842     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3843 
3844   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3845                                        E->getSourceRange(), ExprKind))
3846     return true;
3847 
3848   if (ExprKind == UETT_SizeOf) {
3849     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3850       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3851         QualType OType = PVD->getOriginalType();
3852         QualType Type = PVD->getType();
3853         if (Type->isPointerType() && OType->isArrayType()) {
3854           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3855             << Type << OType;
3856           Diag(PVD->getLocation(), diag::note_declared_at);
3857         }
3858       }
3859     }
3860 
3861     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3862     // decays into a pointer and returns an unintended result. This is most
3863     // likely a typo for "sizeof(array) op x".
3864     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3865       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3866                                BO->getLHS());
3867       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3868                                BO->getRHS());
3869     }
3870   }
3871 
3872   return false;
3873 }
3874 
3875 /// Check the constraints on operands to unary expression and type
3876 /// traits.
3877 ///
3878 /// This will complete any types necessary, and validate the various constraints
3879 /// on those operands.
3880 ///
3881 /// The UsualUnaryConversions() function is *not* called by this routine.
3882 /// C99 6.3.2.1p[2-4] all state:
3883 ///   Except when it is the operand of the sizeof operator ...
3884 ///
3885 /// C++ [expr.sizeof]p4
3886 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3887 ///   standard conversions are not applied to the operand of sizeof.
3888 ///
3889 /// This policy is followed for all of the unary trait expressions.
3890 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3891                                             SourceLocation OpLoc,
3892                                             SourceRange ExprRange,
3893                                             UnaryExprOrTypeTrait ExprKind) {
3894   if (ExprType->isDependentType())
3895     return false;
3896 
3897   // C++ [expr.sizeof]p2:
3898   //     When applied to a reference or a reference type, the result
3899   //     is the size of the referenced type.
3900   // C++11 [expr.alignof]p3:
3901   //     When alignof is applied to a reference type, the result
3902   //     shall be the alignment of the referenced type.
3903   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3904     ExprType = Ref->getPointeeType();
3905 
3906   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3907   //   When alignof or _Alignof is applied to an array type, the result
3908   //   is the alignment of the element type.
3909   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3910       ExprKind == UETT_OpenMPRequiredSimdAlign)
3911     ExprType = Context.getBaseElementType(ExprType);
3912 
3913   if (ExprKind == UETT_VecStep)
3914     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3915 
3916   // Whitelist some types as extensions
3917   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3918                                       ExprKind))
3919     return false;
3920 
3921   if (RequireCompleteType(OpLoc, ExprType,
3922                           diag::err_sizeof_alignof_incomplete_type,
3923                           ExprKind, ExprRange))
3924     return true;
3925 
3926   if (ExprType->isFunctionType()) {
3927     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3928       << ExprKind << ExprRange;
3929     return true;
3930   }
3931 
3932   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3933                                        ExprKind))
3934     return true;
3935 
3936   return false;
3937 }
3938 
3939 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3940   E = E->IgnoreParens();
3941 
3942   // Cannot know anything else if the expression is dependent.
3943   if (E->isTypeDependent())
3944     return false;
3945 
3946   if (E->getObjectKind() == OK_BitField) {
3947     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3948        << 1 << E->getSourceRange();
3949     return true;
3950   }
3951 
3952   ValueDecl *D = nullptr;
3953   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3954     D = DRE->getDecl();
3955   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3956     D = ME->getMemberDecl();
3957   }
3958 
3959   // If it's a field, require the containing struct to have a
3960   // complete definition so that we can compute the layout.
3961   //
3962   // This can happen in C++11 onwards, either by naming the member
3963   // in a way that is not transformed into a member access expression
3964   // (in an unevaluated operand, for instance), or by naming the member
3965   // in a trailing-return-type.
3966   //
3967   // For the record, since __alignof__ on expressions is a GCC
3968   // extension, GCC seems to permit this but always gives the
3969   // nonsensical answer 0.
3970   //
3971   // We don't really need the layout here --- we could instead just
3972   // directly check for all the appropriate alignment-lowing
3973   // attributes --- but that would require duplicating a lot of
3974   // logic that just isn't worth duplicating for such a marginal
3975   // use-case.
3976   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3977     // Fast path this check, since we at least know the record has a
3978     // definition if we can find a member of it.
3979     if (!FD->getParent()->isCompleteDefinition()) {
3980       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3981         << E->getSourceRange();
3982       return true;
3983     }
3984 
3985     // Otherwise, if it's a field, and the field doesn't have
3986     // reference type, then it must have a complete type (or be a
3987     // flexible array member, which we explicitly want to
3988     // white-list anyway), which makes the following checks trivial.
3989     if (!FD->getType()->isReferenceType())
3990       return false;
3991   }
3992 
3993   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3994 }
3995 
3996 bool Sema::CheckVecStepExpr(Expr *E) {
3997   E = E->IgnoreParens();
3998 
3999   // Cannot know anything else if the expression is dependent.
4000   if (E->isTypeDependent())
4001     return false;
4002 
4003   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4004 }
4005 
4006 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4007                                         CapturingScopeInfo *CSI) {
4008   assert(T->isVariablyModifiedType());
4009   assert(CSI != nullptr);
4010 
4011   // We're going to walk down into the type and look for VLA expressions.
4012   do {
4013     const Type *Ty = T.getTypePtr();
4014     switch (Ty->getTypeClass()) {
4015 #define TYPE(Class, Base)
4016 #define ABSTRACT_TYPE(Class, Base)
4017 #define NON_CANONICAL_TYPE(Class, Base)
4018 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4019 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4020 #include "clang/AST/TypeNodes.def"
4021       T = QualType();
4022       break;
4023     // These types are never variably-modified.
4024     case Type::Builtin:
4025     case Type::Complex:
4026     case Type::Vector:
4027     case Type::ExtVector:
4028     case Type::Record:
4029     case Type::Enum:
4030     case Type::Elaborated:
4031     case Type::TemplateSpecialization:
4032     case Type::ObjCObject:
4033     case Type::ObjCInterface:
4034     case Type::ObjCObjectPointer:
4035     case Type::ObjCTypeParam:
4036     case Type::Pipe:
4037       llvm_unreachable("type class is never variably-modified!");
4038     case Type::Adjusted:
4039       T = cast<AdjustedType>(Ty)->getOriginalType();
4040       break;
4041     case Type::Decayed:
4042       T = cast<DecayedType>(Ty)->getPointeeType();
4043       break;
4044     case Type::Pointer:
4045       T = cast<PointerType>(Ty)->getPointeeType();
4046       break;
4047     case Type::BlockPointer:
4048       T = cast<BlockPointerType>(Ty)->getPointeeType();
4049       break;
4050     case Type::LValueReference:
4051     case Type::RValueReference:
4052       T = cast<ReferenceType>(Ty)->getPointeeType();
4053       break;
4054     case Type::MemberPointer:
4055       T = cast<MemberPointerType>(Ty)->getPointeeType();
4056       break;
4057     case Type::ConstantArray:
4058     case Type::IncompleteArray:
4059       // Losing element qualification here is fine.
4060       T = cast<ArrayType>(Ty)->getElementType();
4061       break;
4062     case Type::VariableArray: {
4063       // Losing element qualification here is fine.
4064       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4065 
4066       // Unknown size indication requires no size computation.
4067       // Otherwise, evaluate and record it.
4068       auto Size = VAT->getSizeExpr();
4069       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4070           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4071         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4072 
4073       T = VAT->getElementType();
4074       break;
4075     }
4076     case Type::FunctionProto:
4077     case Type::FunctionNoProto:
4078       T = cast<FunctionType>(Ty)->getReturnType();
4079       break;
4080     case Type::Paren:
4081     case Type::TypeOf:
4082     case Type::UnaryTransform:
4083     case Type::Attributed:
4084     case Type::SubstTemplateTypeParm:
4085     case Type::PackExpansion:
4086     case Type::MacroQualified:
4087       // Keep walking after single level desugaring.
4088       T = T.getSingleStepDesugaredType(Context);
4089       break;
4090     case Type::Typedef:
4091       T = cast<TypedefType>(Ty)->desugar();
4092       break;
4093     case Type::Decltype:
4094       T = cast<DecltypeType>(Ty)->desugar();
4095       break;
4096     case Type::Auto:
4097     case Type::DeducedTemplateSpecialization:
4098       T = cast<DeducedType>(Ty)->getDeducedType();
4099       break;
4100     case Type::TypeOfExpr:
4101       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4102       break;
4103     case Type::Atomic:
4104       T = cast<AtomicType>(Ty)->getValueType();
4105       break;
4106     }
4107   } while (!T.isNull() && T->isVariablyModifiedType());
4108 }
4109 
4110 /// Build a sizeof or alignof expression given a type operand.
4111 ExprResult
4112 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4113                                      SourceLocation OpLoc,
4114                                      UnaryExprOrTypeTrait ExprKind,
4115                                      SourceRange R) {
4116   if (!TInfo)
4117     return ExprError();
4118 
4119   QualType T = TInfo->getType();
4120 
4121   if (!T->isDependentType() &&
4122       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4123     return ExprError();
4124 
4125   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4126     if (auto *TT = T->getAs<TypedefType>()) {
4127       for (auto I = FunctionScopes.rbegin(),
4128                 E = std::prev(FunctionScopes.rend());
4129            I != E; ++I) {
4130         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4131         if (CSI == nullptr)
4132           break;
4133         DeclContext *DC = nullptr;
4134         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4135           DC = LSI->CallOperator;
4136         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4137           DC = CRSI->TheCapturedDecl;
4138         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4139           DC = BSI->TheDecl;
4140         if (DC) {
4141           if (DC->containsDecl(TT->getDecl()))
4142             break;
4143           captureVariablyModifiedType(Context, T, CSI);
4144         }
4145       }
4146     }
4147   }
4148 
4149   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4150   return new (Context) UnaryExprOrTypeTraitExpr(
4151       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4152 }
4153 
4154 /// Build a sizeof or alignof expression given an expression
4155 /// operand.
4156 ExprResult
4157 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4158                                      UnaryExprOrTypeTrait ExprKind) {
4159   ExprResult PE = CheckPlaceholderExpr(E);
4160   if (PE.isInvalid())
4161     return ExprError();
4162 
4163   E = PE.get();
4164 
4165   // Verify that the operand is valid.
4166   bool isInvalid = false;
4167   if (E->isTypeDependent()) {
4168     // Delay type-checking for type-dependent expressions.
4169   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4170     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4171   } else if (ExprKind == UETT_VecStep) {
4172     isInvalid = CheckVecStepExpr(E);
4173   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4174       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4175       isInvalid = true;
4176   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4177     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4178     isInvalid = true;
4179   } else {
4180     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4181   }
4182 
4183   if (isInvalid)
4184     return ExprError();
4185 
4186   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4187     PE = TransformToPotentiallyEvaluated(E);
4188     if (PE.isInvalid()) return ExprError();
4189     E = PE.get();
4190   }
4191 
4192   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4193   return new (Context) UnaryExprOrTypeTraitExpr(
4194       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4195 }
4196 
4197 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4198 /// expr and the same for @c alignof and @c __alignof
4199 /// Note that the ArgRange is invalid if isType is false.
4200 ExprResult
4201 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4202                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4203                                     void *TyOrEx, SourceRange ArgRange) {
4204   // If error parsing type, ignore.
4205   if (!TyOrEx) return ExprError();
4206 
4207   if (IsType) {
4208     TypeSourceInfo *TInfo;
4209     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4210     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4211   }
4212 
4213   Expr *ArgEx = (Expr *)TyOrEx;
4214   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4215   return Result;
4216 }
4217 
4218 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4219                                      bool IsReal) {
4220   if (V.get()->isTypeDependent())
4221     return S.Context.DependentTy;
4222 
4223   // _Real and _Imag are only l-values for normal l-values.
4224   if (V.get()->getObjectKind() != OK_Ordinary) {
4225     V = S.DefaultLvalueConversion(V.get());
4226     if (V.isInvalid())
4227       return QualType();
4228   }
4229 
4230   // These operators return the element type of a complex type.
4231   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4232     return CT->getElementType();
4233 
4234   // Otherwise they pass through real integer and floating point types here.
4235   if (V.get()->getType()->isArithmeticType())
4236     return V.get()->getType();
4237 
4238   // Test for placeholders.
4239   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4240   if (PR.isInvalid()) return QualType();
4241   if (PR.get() != V.get()) {
4242     V = PR;
4243     return CheckRealImagOperand(S, V, Loc, IsReal);
4244   }
4245 
4246   // Reject anything else.
4247   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4248     << (IsReal ? "__real" : "__imag");
4249   return QualType();
4250 }
4251 
4252 
4253 
4254 ExprResult
4255 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4256                           tok::TokenKind Kind, Expr *Input) {
4257   UnaryOperatorKind Opc;
4258   switch (Kind) {
4259   default: llvm_unreachable("Unknown unary op!");
4260   case tok::plusplus:   Opc = UO_PostInc; break;
4261   case tok::minusminus: Opc = UO_PostDec; break;
4262   }
4263 
4264   // Since this might is a postfix expression, get rid of ParenListExprs.
4265   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4266   if (Result.isInvalid()) return ExprError();
4267   Input = Result.get();
4268 
4269   return BuildUnaryOp(S, OpLoc, Opc, Input);
4270 }
4271 
4272 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4273 ///
4274 /// \return true on error
4275 static bool checkArithmeticOnObjCPointer(Sema &S,
4276                                          SourceLocation opLoc,
4277                                          Expr *op) {
4278   assert(op->getType()->isObjCObjectPointerType());
4279   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4280       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4281     return false;
4282 
4283   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4284     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4285     << op->getSourceRange();
4286   return true;
4287 }
4288 
4289 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4290   auto *BaseNoParens = Base->IgnoreParens();
4291   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4292     return MSProp->getPropertyDecl()->getType()->isArrayType();
4293   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4294 }
4295 
4296 ExprResult
4297 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4298                               Expr *idx, SourceLocation rbLoc) {
4299   if (base && !base->getType().isNull() &&
4300       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4301     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4302                                     /*Length=*/nullptr, rbLoc);
4303 
4304   // Since this might be a postfix expression, get rid of ParenListExprs.
4305   if (isa<ParenListExpr>(base)) {
4306     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4307     if (result.isInvalid()) return ExprError();
4308     base = result.get();
4309   }
4310 
4311   // A comma-expression as the index is deprecated in C++2a onwards.
4312   if (getLangOpts().CPlusPlus2a &&
4313       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4314        (isa<CXXOperatorCallExpr>(idx) &&
4315         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4316     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4317       << SourceRange(base->getBeginLoc(), rbLoc);
4318   }
4319 
4320   // Handle any non-overload placeholder types in the base and index
4321   // expressions.  We can't handle overloads here because the other
4322   // operand might be an overloadable type, in which case the overload
4323   // resolution for the operator overload should get the first crack
4324   // at the overload.
4325   bool IsMSPropertySubscript = false;
4326   if (base->getType()->isNonOverloadPlaceholderType()) {
4327     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4328     if (!IsMSPropertySubscript) {
4329       ExprResult result = CheckPlaceholderExpr(base);
4330       if (result.isInvalid())
4331         return ExprError();
4332       base = result.get();
4333     }
4334   }
4335   if (idx->getType()->isNonOverloadPlaceholderType()) {
4336     ExprResult result = CheckPlaceholderExpr(idx);
4337     if (result.isInvalid()) return ExprError();
4338     idx = result.get();
4339   }
4340 
4341   // Build an unanalyzed expression if either operand is type-dependent.
4342   if (getLangOpts().CPlusPlus &&
4343       (base->isTypeDependent() || idx->isTypeDependent())) {
4344     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4345                                             VK_LValue, OK_Ordinary, rbLoc);
4346   }
4347 
4348   // MSDN, property (C++)
4349   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4350   // This attribute can also be used in the declaration of an empty array in a
4351   // class or structure definition. For example:
4352   // __declspec(property(get=GetX, put=PutX)) int x[];
4353   // The above statement indicates that x[] can be used with one or more array
4354   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4355   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4356   if (IsMSPropertySubscript) {
4357     // Build MS property subscript expression if base is MS property reference
4358     // or MS property subscript.
4359     return new (Context) MSPropertySubscriptExpr(
4360         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4361   }
4362 
4363   // Use C++ overloaded-operator rules if either operand has record
4364   // type.  The spec says to do this if either type is *overloadable*,
4365   // but enum types can't declare subscript operators or conversion
4366   // operators, so there's nothing interesting for overload resolution
4367   // to do if there aren't any record types involved.
4368   //
4369   // ObjC pointers have their own subscripting logic that is not tied
4370   // to overload resolution and so should not take this path.
4371   if (getLangOpts().CPlusPlus &&
4372       (base->getType()->isRecordType() ||
4373        (!base->getType()->isObjCObjectPointerType() &&
4374         idx->getType()->isRecordType()))) {
4375     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4376   }
4377 
4378   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4379 
4380   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4381     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4382 
4383   return Res;
4384 }
4385 
4386 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4387   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4388   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4389 
4390   // For expressions like `&(*s).b`, the base is recorded and what should be
4391   // checked.
4392   const MemberExpr *Member = nullptr;
4393   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4394     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4395 
4396   LastRecord.PossibleDerefs.erase(StrippedExpr);
4397 }
4398 
4399 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4400   QualType ResultTy = E->getType();
4401   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4402 
4403   // Bail if the element is an array since it is not memory access.
4404   if (isa<ArrayType>(ResultTy))
4405     return;
4406 
4407   if (ResultTy->hasAttr(attr::NoDeref)) {
4408     LastRecord.PossibleDerefs.insert(E);
4409     return;
4410   }
4411 
4412   // Check if the base type is a pointer to a member access of a struct
4413   // marked with noderef.
4414   const Expr *Base = E->getBase();
4415   QualType BaseTy = Base->getType();
4416   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4417     // Not a pointer access
4418     return;
4419 
4420   const MemberExpr *Member = nullptr;
4421   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4422          Member->isArrow())
4423     Base = Member->getBase();
4424 
4425   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4426     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4427       LastRecord.PossibleDerefs.insert(E);
4428   }
4429 }
4430 
4431 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4432                                           Expr *LowerBound,
4433                                           SourceLocation ColonLoc, Expr *Length,
4434                                           SourceLocation RBLoc) {
4435   if (Base->getType()->isPlaceholderType() &&
4436       !Base->getType()->isSpecificPlaceholderType(
4437           BuiltinType::OMPArraySection)) {
4438     ExprResult Result = CheckPlaceholderExpr(Base);
4439     if (Result.isInvalid())
4440       return ExprError();
4441     Base = Result.get();
4442   }
4443   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4444     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4445     if (Result.isInvalid())
4446       return ExprError();
4447     Result = DefaultLvalueConversion(Result.get());
4448     if (Result.isInvalid())
4449       return ExprError();
4450     LowerBound = Result.get();
4451   }
4452   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4453     ExprResult Result = CheckPlaceholderExpr(Length);
4454     if (Result.isInvalid())
4455       return ExprError();
4456     Result = DefaultLvalueConversion(Result.get());
4457     if (Result.isInvalid())
4458       return ExprError();
4459     Length = Result.get();
4460   }
4461 
4462   // Build an unanalyzed expression if either operand is type-dependent.
4463   if (Base->isTypeDependent() ||
4464       (LowerBound &&
4465        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4466       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4467     return new (Context)
4468         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4469                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4470   }
4471 
4472   // Perform default conversions.
4473   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4474   QualType ResultTy;
4475   if (OriginalTy->isAnyPointerType()) {
4476     ResultTy = OriginalTy->getPointeeType();
4477   } else if (OriginalTy->isArrayType()) {
4478     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4479   } else {
4480     return ExprError(
4481         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4482         << Base->getSourceRange());
4483   }
4484   // C99 6.5.2.1p1
4485   if (LowerBound) {
4486     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4487                                                       LowerBound);
4488     if (Res.isInvalid())
4489       return ExprError(Diag(LowerBound->getExprLoc(),
4490                             diag::err_omp_typecheck_section_not_integer)
4491                        << 0 << LowerBound->getSourceRange());
4492     LowerBound = Res.get();
4493 
4494     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4495         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4496       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4497           << 0 << LowerBound->getSourceRange();
4498   }
4499   if (Length) {
4500     auto Res =
4501         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4502     if (Res.isInvalid())
4503       return ExprError(Diag(Length->getExprLoc(),
4504                             diag::err_omp_typecheck_section_not_integer)
4505                        << 1 << Length->getSourceRange());
4506     Length = Res.get();
4507 
4508     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4509         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4510       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4511           << 1 << Length->getSourceRange();
4512   }
4513 
4514   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4515   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4516   // type. Note that functions are not objects, and that (in C99 parlance)
4517   // incomplete types are not object types.
4518   if (ResultTy->isFunctionType()) {
4519     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4520         << ResultTy << Base->getSourceRange();
4521     return ExprError();
4522   }
4523 
4524   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4525                           diag::err_omp_section_incomplete_type, Base))
4526     return ExprError();
4527 
4528   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4529     Expr::EvalResult Result;
4530     if (LowerBound->EvaluateAsInt(Result, Context)) {
4531       // OpenMP 4.5, [2.4 Array Sections]
4532       // The array section must be a subset of the original array.
4533       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4534       if (LowerBoundValue.isNegative()) {
4535         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4536             << LowerBound->getSourceRange();
4537         return ExprError();
4538       }
4539     }
4540   }
4541 
4542   if (Length) {
4543     Expr::EvalResult Result;
4544     if (Length->EvaluateAsInt(Result, Context)) {
4545       // OpenMP 4.5, [2.4 Array Sections]
4546       // The length must evaluate to non-negative integers.
4547       llvm::APSInt LengthValue = Result.Val.getInt();
4548       if (LengthValue.isNegative()) {
4549         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4550             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4551             << Length->getSourceRange();
4552         return ExprError();
4553       }
4554     }
4555   } else if (ColonLoc.isValid() &&
4556              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4557                                       !OriginalTy->isVariableArrayType()))) {
4558     // OpenMP 4.5, [2.4 Array Sections]
4559     // When the size of the array dimension is not known, the length must be
4560     // specified explicitly.
4561     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4562         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4563     return ExprError();
4564   }
4565 
4566   if (!Base->getType()->isSpecificPlaceholderType(
4567           BuiltinType::OMPArraySection)) {
4568     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4569     if (Result.isInvalid())
4570       return ExprError();
4571     Base = Result.get();
4572   }
4573   return new (Context)
4574       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4575                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4576 }
4577 
4578 ExprResult
4579 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4580                                       Expr *Idx, SourceLocation RLoc) {
4581   Expr *LHSExp = Base;
4582   Expr *RHSExp = Idx;
4583 
4584   ExprValueKind VK = VK_LValue;
4585   ExprObjectKind OK = OK_Ordinary;
4586 
4587   // Per C++ core issue 1213, the result is an xvalue if either operand is
4588   // a non-lvalue array, and an lvalue otherwise.
4589   if (getLangOpts().CPlusPlus11) {
4590     for (auto *Op : {LHSExp, RHSExp}) {
4591       Op = Op->IgnoreImplicit();
4592       if (Op->getType()->isArrayType() && !Op->isLValue())
4593         VK = VK_XValue;
4594     }
4595   }
4596 
4597   // Perform default conversions.
4598   if (!LHSExp->getType()->getAs<VectorType>()) {
4599     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4600     if (Result.isInvalid())
4601       return ExprError();
4602     LHSExp = Result.get();
4603   }
4604   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4605   if (Result.isInvalid())
4606     return ExprError();
4607   RHSExp = Result.get();
4608 
4609   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4610 
4611   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4612   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4613   // in the subscript position. As a result, we need to derive the array base
4614   // and index from the expression types.
4615   Expr *BaseExpr, *IndexExpr;
4616   QualType ResultType;
4617   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4618     BaseExpr = LHSExp;
4619     IndexExpr = RHSExp;
4620     ResultType = Context.DependentTy;
4621   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4622     BaseExpr = LHSExp;
4623     IndexExpr = RHSExp;
4624     ResultType = PTy->getPointeeType();
4625   } else if (const ObjCObjectPointerType *PTy =
4626                LHSTy->getAs<ObjCObjectPointerType>()) {
4627     BaseExpr = LHSExp;
4628     IndexExpr = RHSExp;
4629 
4630     // Use custom logic if this should be the pseudo-object subscript
4631     // expression.
4632     if (!LangOpts.isSubscriptPointerArithmetic())
4633       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4634                                           nullptr);
4635 
4636     ResultType = PTy->getPointeeType();
4637   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4638      // Handle the uncommon case of "123[Ptr]".
4639     BaseExpr = RHSExp;
4640     IndexExpr = LHSExp;
4641     ResultType = PTy->getPointeeType();
4642   } else if (const ObjCObjectPointerType *PTy =
4643                RHSTy->getAs<ObjCObjectPointerType>()) {
4644      // Handle the uncommon case of "123[Ptr]".
4645     BaseExpr = RHSExp;
4646     IndexExpr = LHSExp;
4647     ResultType = PTy->getPointeeType();
4648     if (!LangOpts.isSubscriptPointerArithmetic()) {
4649       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4650         << ResultType << BaseExpr->getSourceRange();
4651       return ExprError();
4652     }
4653   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4654     BaseExpr = LHSExp;    // vectors: V[123]
4655     IndexExpr = RHSExp;
4656     // We apply C++ DR1213 to vector subscripting too.
4657     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4658       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4659       if (Materialized.isInvalid())
4660         return ExprError();
4661       LHSExp = Materialized.get();
4662     }
4663     VK = LHSExp->getValueKind();
4664     if (VK != VK_RValue)
4665       OK = OK_VectorComponent;
4666 
4667     ResultType = VTy->getElementType();
4668     QualType BaseType = BaseExpr->getType();
4669     Qualifiers BaseQuals = BaseType.getQualifiers();
4670     Qualifiers MemberQuals = ResultType.getQualifiers();
4671     Qualifiers Combined = BaseQuals + MemberQuals;
4672     if (Combined != MemberQuals)
4673       ResultType = Context.getQualifiedType(ResultType, Combined);
4674   } else if (LHSTy->isArrayType()) {
4675     // If we see an array that wasn't promoted by
4676     // DefaultFunctionArrayLvalueConversion, it must be an array that
4677     // wasn't promoted because of the C90 rule that doesn't
4678     // allow promoting non-lvalue arrays.  Warn, then
4679     // force the promotion here.
4680     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4681         << LHSExp->getSourceRange();
4682     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4683                                CK_ArrayToPointerDecay).get();
4684     LHSTy = LHSExp->getType();
4685 
4686     BaseExpr = LHSExp;
4687     IndexExpr = RHSExp;
4688     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4689   } else if (RHSTy->isArrayType()) {
4690     // Same as previous, except for 123[f().a] case
4691     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4692         << RHSExp->getSourceRange();
4693     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4694                                CK_ArrayToPointerDecay).get();
4695     RHSTy = RHSExp->getType();
4696 
4697     BaseExpr = RHSExp;
4698     IndexExpr = LHSExp;
4699     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4700   } else {
4701     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4702        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4703   }
4704   // C99 6.5.2.1p1
4705   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4706     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4707                      << IndexExpr->getSourceRange());
4708 
4709   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4710        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4711          && !IndexExpr->isTypeDependent())
4712     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4713 
4714   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4715   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4716   // type. Note that Functions are not objects, and that (in C99 parlance)
4717   // incomplete types are not object types.
4718   if (ResultType->isFunctionType()) {
4719     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4720         << ResultType << BaseExpr->getSourceRange();
4721     return ExprError();
4722   }
4723 
4724   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4725     // GNU extension: subscripting on pointer to void
4726     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4727       << BaseExpr->getSourceRange();
4728 
4729     // C forbids expressions of unqualified void type from being l-values.
4730     // See IsCForbiddenLValueType.
4731     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4732   } else if (!ResultType->isDependentType() &&
4733       RequireCompleteType(LLoc, ResultType,
4734                           diag::err_subscript_incomplete_type, BaseExpr))
4735     return ExprError();
4736 
4737   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4738          !ResultType.isCForbiddenLValueType());
4739 
4740   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4741       FunctionScopes.size() > 1) {
4742     if (auto *TT =
4743             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4744       for (auto I = FunctionScopes.rbegin(),
4745                 E = std::prev(FunctionScopes.rend());
4746            I != E; ++I) {
4747         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4748         if (CSI == nullptr)
4749           break;
4750         DeclContext *DC = nullptr;
4751         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4752           DC = LSI->CallOperator;
4753         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4754           DC = CRSI->TheCapturedDecl;
4755         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4756           DC = BSI->TheDecl;
4757         if (DC) {
4758           if (DC->containsDecl(TT->getDecl()))
4759             break;
4760           captureVariablyModifiedType(
4761               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4762         }
4763       }
4764     }
4765   }
4766 
4767   return new (Context)
4768       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4769 }
4770 
4771 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4772                                   ParmVarDecl *Param) {
4773   if (Param->hasUnparsedDefaultArg()) {
4774     Diag(CallLoc,
4775          diag::err_use_of_default_argument_to_function_declared_later) <<
4776       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4777     Diag(UnparsedDefaultArgLocs[Param],
4778          diag::note_default_argument_declared_here);
4779     return true;
4780   }
4781 
4782   if (Param->hasUninstantiatedDefaultArg()) {
4783     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4784 
4785     EnterExpressionEvaluationContext EvalContext(
4786         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4787 
4788     // Instantiate the expression.
4789     //
4790     // FIXME: Pass in a correct Pattern argument, otherwise
4791     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4792     //
4793     // template<typename T>
4794     // struct A {
4795     //   static int FooImpl();
4796     //
4797     //   template<typename Tp>
4798     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4799     //   // template argument list [[T], [Tp]], should be [[Tp]].
4800     //   friend A<Tp> Foo(int a);
4801     // };
4802     //
4803     // template<typename T>
4804     // A<T> Foo(int a = A<T>::FooImpl());
4805     MultiLevelTemplateArgumentList MutiLevelArgList
4806       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4807 
4808     InstantiatingTemplate Inst(*this, CallLoc, Param,
4809                                MutiLevelArgList.getInnermost());
4810     if (Inst.isInvalid())
4811       return true;
4812     if (Inst.isAlreadyInstantiating()) {
4813       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4814       Param->setInvalidDecl();
4815       return true;
4816     }
4817 
4818     ExprResult Result;
4819     {
4820       // C++ [dcl.fct.default]p5:
4821       //   The names in the [default argument] expression are bound, and
4822       //   the semantic constraints are checked, at the point where the
4823       //   default argument expression appears.
4824       ContextRAII SavedContext(*this, FD);
4825       LocalInstantiationScope Local(*this);
4826       runWithSufficientStackSpace(CallLoc, [&] {
4827         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4828                                   /*DirectInit*/false);
4829       });
4830     }
4831     if (Result.isInvalid())
4832       return true;
4833 
4834     // Check the expression as an initializer for the parameter.
4835     InitializedEntity Entity
4836       = InitializedEntity::InitializeParameter(Context, Param);
4837     InitializationKind Kind = InitializationKind::CreateCopy(
4838         Param->getLocation(),
4839         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4840     Expr *ResultE = Result.getAs<Expr>();
4841 
4842     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4843     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4844     if (Result.isInvalid())
4845       return true;
4846 
4847     Result =
4848         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4849                             /*DiscardedValue*/ false);
4850     if (Result.isInvalid())
4851       return true;
4852 
4853     // Remember the instantiated default argument.
4854     Param->setDefaultArg(Result.getAs<Expr>());
4855     if (ASTMutationListener *L = getASTMutationListener()) {
4856       L->DefaultArgumentInstantiated(Param);
4857     }
4858   }
4859 
4860   // If the default argument expression is not set yet, we are building it now.
4861   if (!Param->hasInit()) {
4862     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4863     Param->setInvalidDecl();
4864     return true;
4865   }
4866 
4867   // If the default expression creates temporaries, we need to
4868   // push them to the current stack of expression temporaries so they'll
4869   // be properly destroyed.
4870   // FIXME: We should really be rebuilding the default argument with new
4871   // bound temporaries; see the comment in PR5810.
4872   // We don't need to do that with block decls, though, because
4873   // blocks in default argument expression can never capture anything.
4874   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4875     // Set the "needs cleanups" bit regardless of whether there are
4876     // any explicit objects.
4877     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4878 
4879     // Append all the objects to the cleanup list.  Right now, this
4880     // should always be a no-op, because blocks in default argument
4881     // expressions should never be able to capture anything.
4882     assert(!Init->getNumObjects() &&
4883            "default argument expression has capturing blocks?");
4884   }
4885 
4886   // We already type-checked the argument, so we know it works.
4887   // Just mark all of the declarations in this potentially-evaluated expression
4888   // as being "referenced".
4889   EnterExpressionEvaluationContext EvalContext(
4890       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4891   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4892                                    /*SkipLocalVariables=*/true);
4893   return false;
4894 }
4895 
4896 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4897                                         FunctionDecl *FD, ParmVarDecl *Param) {
4898   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4899     return ExprError();
4900   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4901 }
4902 
4903 Sema::VariadicCallType
4904 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4905                           Expr *Fn) {
4906   if (Proto && Proto->isVariadic()) {
4907     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4908       return VariadicConstructor;
4909     else if (Fn && Fn->getType()->isBlockPointerType())
4910       return VariadicBlock;
4911     else if (FDecl) {
4912       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4913         if (Method->isInstance())
4914           return VariadicMethod;
4915     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4916       return VariadicMethod;
4917     return VariadicFunction;
4918   }
4919   return VariadicDoesNotApply;
4920 }
4921 
4922 namespace {
4923 class FunctionCallCCC final : public FunctionCallFilterCCC {
4924 public:
4925   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4926                   unsigned NumArgs, MemberExpr *ME)
4927       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4928         FunctionName(FuncName) {}
4929 
4930   bool ValidateCandidate(const TypoCorrection &candidate) override {
4931     if (!candidate.getCorrectionSpecifier() ||
4932         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4933       return false;
4934     }
4935 
4936     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4937   }
4938 
4939   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4940     return std::make_unique<FunctionCallCCC>(*this);
4941   }
4942 
4943 private:
4944   const IdentifierInfo *const FunctionName;
4945 };
4946 }
4947 
4948 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4949                                                FunctionDecl *FDecl,
4950                                                ArrayRef<Expr *> Args) {
4951   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4952   DeclarationName FuncName = FDecl->getDeclName();
4953   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4954 
4955   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4956   if (TypoCorrection Corrected = S.CorrectTypo(
4957           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4958           S.getScopeForContext(S.CurContext), nullptr, CCC,
4959           Sema::CTK_ErrorRecovery)) {
4960     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4961       if (Corrected.isOverloaded()) {
4962         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4963         OverloadCandidateSet::iterator Best;
4964         for (NamedDecl *CD : Corrected) {
4965           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4966             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4967                                    OCS);
4968         }
4969         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4970         case OR_Success:
4971           ND = Best->FoundDecl;
4972           Corrected.setCorrectionDecl(ND);
4973           break;
4974         default:
4975           break;
4976         }
4977       }
4978       ND = ND->getUnderlyingDecl();
4979       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4980         return Corrected;
4981     }
4982   }
4983   return TypoCorrection();
4984 }
4985 
4986 /// ConvertArgumentsForCall - Converts the arguments specified in
4987 /// Args/NumArgs to the parameter types of the function FDecl with
4988 /// function prototype Proto. Call is the call expression itself, and
4989 /// Fn is the function expression. For a C++ member function, this
4990 /// routine does not attempt to convert the object argument. Returns
4991 /// true if the call is ill-formed.
4992 bool
4993 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4994                               FunctionDecl *FDecl,
4995                               const FunctionProtoType *Proto,
4996                               ArrayRef<Expr *> Args,
4997                               SourceLocation RParenLoc,
4998                               bool IsExecConfig) {
4999   // Bail out early if calling a builtin with custom typechecking.
5000   if (FDecl)
5001     if (unsigned ID = FDecl->getBuiltinID())
5002       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5003         return false;
5004 
5005   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5006   // assignment, to the types of the corresponding parameter, ...
5007   unsigned NumParams = Proto->getNumParams();
5008   bool Invalid = false;
5009   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5010   unsigned FnKind = Fn->getType()->isBlockPointerType()
5011                        ? 1 /* block */
5012                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5013                                        : 0 /* function */);
5014 
5015   // If too few arguments are available (and we don't have default
5016   // arguments for the remaining parameters), don't make the call.
5017   if (Args.size() < NumParams) {
5018     if (Args.size() < MinArgs) {
5019       TypoCorrection TC;
5020       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5021         unsigned diag_id =
5022             MinArgs == NumParams && !Proto->isVariadic()
5023                 ? diag::err_typecheck_call_too_few_args_suggest
5024                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5025         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5026                                         << static_cast<unsigned>(Args.size())
5027                                         << TC.getCorrectionRange());
5028       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5029         Diag(RParenLoc,
5030              MinArgs == NumParams && !Proto->isVariadic()
5031                  ? diag::err_typecheck_call_too_few_args_one
5032                  : diag::err_typecheck_call_too_few_args_at_least_one)
5033             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5034       else
5035         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5036                             ? diag::err_typecheck_call_too_few_args
5037                             : diag::err_typecheck_call_too_few_args_at_least)
5038             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5039             << Fn->getSourceRange();
5040 
5041       // Emit the location of the prototype.
5042       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5043         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5044 
5045       return true;
5046     }
5047     // We reserve space for the default arguments when we create
5048     // the call expression, before calling ConvertArgumentsForCall.
5049     assert((Call->getNumArgs() == NumParams) &&
5050            "We should have reserved space for the default arguments before!");
5051   }
5052 
5053   // If too many are passed and not variadic, error on the extras and drop
5054   // them.
5055   if (Args.size() > NumParams) {
5056     if (!Proto->isVariadic()) {
5057       TypoCorrection TC;
5058       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5059         unsigned diag_id =
5060             MinArgs == NumParams && !Proto->isVariadic()
5061                 ? diag::err_typecheck_call_too_many_args_suggest
5062                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5063         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5064                                         << static_cast<unsigned>(Args.size())
5065                                         << TC.getCorrectionRange());
5066       } else if (NumParams == 1 && FDecl &&
5067                  FDecl->getParamDecl(0)->getDeclName())
5068         Diag(Args[NumParams]->getBeginLoc(),
5069              MinArgs == NumParams
5070                  ? diag::err_typecheck_call_too_many_args_one
5071                  : diag::err_typecheck_call_too_many_args_at_most_one)
5072             << FnKind << FDecl->getParamDecl(0)
5073             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5074             << SourceRange(Args[NumParams]->getBeginLoc(),
5075                            Args.back()->getEndLoc());
5076       else
5077         Diag(Args[NumParams]->getBeginLoc(),
5078              MinArgs == NumParams
5079                  ? diag::err_typecheck_call_too_many_args
5080                  : diag::err_typecheck_call_too_many_args_at_most)
5081             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5082             << Fn->getSourceRange()
5083             << SourceRange(Args[NumParams]->getBeginLoc(),
5084                            Args.back()->getEndLoc());
5085 
5086       // Emit the location of the prototype.
5087       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5088         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5089 
5090       // This deletes the extra arguments.
5091       Call->shrinkNumArgs(NumParams);
5092       return true;
5093     }
5094   }
5095   SmallVector<Expr *, 8> AllArgs;
5096   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5097 
5098   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5099                                    AllArgs, CallType);
5100   if (Invalid)
5101     return true;
5102   unsigned TotalNumArgs = AllArgs.size();
5103   for (unsigned i = 0; i < TotalNumArgs; ++i)
5104     Call->setArg(i, AllArgs[i]);
5105 
5106   return false;
5107 }
5108 
5109 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5110                                   const FunctionProtoType *Proto,
5111                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5112                                   SmallVectorImpl<Expr *> &AllArgs,
5113                                   VariadicCallType CallType, bool AllowExplicit,
5114                                   bool IsListInitialization) {
5115   unsigned NumParams = Proto->getNumParams();
5116   bool Invalid = false;
5117   size_t ArgIx = 0;
5118   // Continue to check argument types (even if we have too few/many args).
5119   for (unsigned i = FirstParam; i < NumParams; i++) {
5120     QualType ProtoArgType = Proto->getParamType(i);
5121 
5122     Expr *Arg;
5123     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5124     if (ArgIx < Args.size()) {
5125       Arg = Args[ArgIx++];
5126 
5127       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5128                               diag::err_call_incomplete_argument, Arg))
5129         return true;
5130 
5131       // Strip the unbridged-cast placeholder expression off, if applicable.
5132       bool CFAudited = false;
5133       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5134           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5135           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5136         Arg = stripARCUnbridgedCast(Arg);
5137       else if (getLangOpts().ObjCAutoRefCount &&
5138                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5139                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5140         CFAudited = true;
5141 
5142       if (Proto->getExtParameterInfo(i).isNoEscape())
5143         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5144           BE->getBlockDecl()->setDoesNotEscape();
5145 
5146       InitializedEntity Entity =
5147           Param ? InitializedEntity::InitializeParameter(Context, Param,
5148                                                          ProtoArgType)
5149                 : InitializedEntity::InitializeParameter(
5150                       Context, ProtoArgType, Proto->isParamConsumed(i));
5151 
5152       // Remember that parameter belongs to a CF audited API.
5153       if (CFAudited)
5154         Entity.setParameterCFAudited();
5155 
5156       ExprResult ArgE = PerformCopyInitialization(
5157           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5158       if (ArgE.isInvalid())
5159         return true;
5160 
5161       Arg = ArgE.getAs<Expr>();
5162     } else {
5163       assert(Param && "can't use default arguments without a known callee");
5164 
5165       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5166       if (ArgExpr.isInvalid())
5167         return true;
5168 
5169       Arg = ArgExpr.getAs<Expr>();
5170     }
5171 
5172     // Check for array bounds violations for each argument to the call. This
5173     // check only triggers warnings when the argument isn't a more complex Expr
5174     // with its own checking, such as a BinaryOperator.
5175     CheckArrayAccess(Arg);
5176 
5177     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5178     CheckStaticArrayArgument(CallLoc, Param, Arg);
5179 
5180     AllArgs.push_back(Arg);
5181   }
5182 
5183   // If this is a variadic call, handle args passed through "...".
5184   if (CallType != VariadicDoesNotApply) {
5185     // Assume that extern "C" functions with variadic arguments that
5186     // return __unknown_anytype aren't *really* variadic.
5187     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5188         FDecl->isExternC()) {
5189       for (Expr *A : Args.slice(ArgIx)) {
5190         QualType paramType; // ignored
5191         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5192         Invalid |= arg.isInvalid();
5193         AllArgs.push_back(arg.get());
5194       }
5195 
5196     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5197     } else {
5198       for (Expr *A : Args.slice(ArgIx)) {
5199         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5200         Invalid |= Arg.isInvalid();
5201         AllArgs.push_back(Arg.get());
5202       }
5203     }
5204 
5205     // Check for array bounds violations.
5206     for (Expr *A : Args.slice(ArgIx))
5207       CheckArrayAccess(A);
5208   }
5209   return Invalid;
5210 }
5211 
5212 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5213   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5214   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5215     TL = DTL.getOriginalLoc();
5216   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5217     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5218       << ATL.getLocalSourceRange();
5219 }
5220 
5221 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5222 /// array parameter, check that it is non-null, and that if it is formed by
5223 /// array-to-pointer decay, the underlying array is sufficiently large.
5224 ///
5225 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5226 /// array type derivation, then for each call to the function, the value of the
5227 /// corresponding actual argument shall provide access to the first element of
5228 /// an array with at least as many elements as specified by the size expression.
5229 void
5230 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5231                                ParmVarDecl *Param,
5232                                const Expr *ArgExpr) {
5233   // Static array parameters are not supported in C++.
5234   if (!Param || getLangOpts().CPlusPlus)
5235     return;
5236 
5237   QualType OrigTy = Param->getOriginalType();
5238 
5239   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5240   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5241     return;
5242 
5243   if (ArgExpr->isNullPointerConstant(Context,
5244                                      Expr::NPC_NeverValueDependent)) {
5245     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5246     DiagnoseCalleeStaticArrayParam(*this, Param);
5247     return;
5248   }
5249 
5250   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5251   if (!CAT)
5252     return;
5253 
5254   const ConstantArrayType *ArgCAT =
5255     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5256   if (!ArgCAT)
5257     return;
5258 
5259   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5260                                              ArgCAT->getElementType())) {
5261     if (ArgCAT->getSize().ult(CAT->getSize())) {
5262       Diag(CallLoc, diag::warn_static_array_too_small)
5263           << ArgExpr->getSourceRange()
5264           << (unsigned)ArgCAT->getSize().getZExtValue()
5265           << (unsigned)CAT->getSize().getZExtValue() << 0;
5266       DiagnoseCalleeStaticArrayParam(*this, Param);
5267     }
5268     return;
5269   }
5270 
5271   Optional<CharUnits> ArgSize =
5272       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5273   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5274   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5275     Diag(CallLoc, diag::warn_static_array_too_small)
5276         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5277         << (unsigned)ParmSize->getQuantity() << 1;
5278     DiagnoseCalleeStaticArrayParam(*this, Param);
5279   }
5280 }
5281 
5282 /// Given a function expression of unknown-any type, try to rebuild it
5283 /// to have a function type.
5284 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5285 
5286 /// Is the given type a placeholder that we need to lower out
5287 /// immediately during argument processing?
5288 static bool isPlaceholderToRemoveAsArg(QualType type) {
5289   // Placeholders are never sugared.
5290   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5291   if (!placeholder) return false;
5292 
5293   switch (placeholder->getKind()) {
5294   // Ignore all the non-placeholder types.
5295 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5296   case BuiltinType::Id:
5297 #include "clang/Basic/OpenCLImageTypes.def"
5298 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5299   case BuiltinType::Id:
5300 #include "clang/Basic/OpenCLExtensionTypes.def"
5301   // In practice we'll never use this, since all SVE types are sugared
5302   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5303 #define SVE_TYPE(Name, Id, SingletonId) \
5304   case BuiltinType::Id:
5305 #include "clang/Basic/AArch64SVEACLETypes.def"
5306 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5307 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5308 #include "clang/AST/BuiltinTypes.def"
5309     return false;
5310 
5311   // We cannot lower out overload sets; they might validly be resolved
5312   // by the call machinery.
5313   case BuiltinType::Overload:
5314     return false;
5315 
5316   // Unbridged casts in ARC can be handled in some call positions and
5317   // should be left in place.
5318   case BuiltinType::ARCUnbridgedCast:
5319     return false;
5320 
5321   // Pseudo-objects should be converted as soon as possible.
5322   case BuiltinType::PseudoObject:
5323     return true;
5324 
5325   // The debugger mode could theoretically but currently does not try
5326   // to resolve unknown-typed arguments based on known parameter types.
5327   case BuiltinType::UnknownAny:
5328     return true;
5329 
5330   // These are always invalid as call arguments and should be reported.
5331   case BuiltinType::BoundMember:
5332   case BuiltinType::BuiltinFn:
5333   case BuiltinType::OMPArraySection:
5334     return true;
5335 
5336   }
5337   llvm_unreachable("bad builtin type kind");
5338 }
5339 
5340 /// Check an argument list for placeholders that we won't try to
5341 /// handle later.
5342 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5343   // Apply this processing to all the arguments at once instead of
5344   // dying at the first failure.
5345   bool hasInvalid = false;
5346   for (size_t i = 0, e = args.size(); i != e; i++) {
5347     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5348       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5349       if (result.isInvalid()) hasInvalid = true;
5350       else args[i] = result.get();
5351     } else if (hasInvalid) {
5352       (void)S.CorrectDelayedTyposInExpr(args[i]);
5353     }
5354   }
5355   return hasInvalid;
5356 }
5357 
5358 /// If a builtin function has a pointer argument with no explicit address
5359 /// space, then it should be able to accept a pointer to any address
5360 /// space as input.  In order to do this, we need to replace the
5361 /// standard builtin declaration with one that uses the same address space
5362 /// as the call.
5363 ///
5364 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5365 ///                  it does not contain any pointer arguments without
5366 ///                  an address space qualifer.  Otherwise the rewritten
5367 ///                  FunctionDecl is returned.
5368 /// TODO: Handle pointer return types.
5369 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5370                                                 FunctionDecl *FDecl,
5371                                                 MultiExprArg ArgExprs) {
5372 
5373   QualType DeclType = FDecl->getType();
5374   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5375 
5376   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5377       ArgExprs.size() < FT->getNumParams())
5378     return nullptr;
5379 
5380   bool NeedsNewDecl = false;
5381   unsigned i = 0;
5382   SmallVector<QualType, 8> OverloadParams;
5383 
5384   for (QualType ParamType : FT->param_types()) {
5385 
5386     // Convert array arguments to pointer to simplify type lookup.
5387     ExprResult ArgRes =
5388         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5389     if (ArgRes.isInvalid())
5390       return nullptr;
5391     Expr *Arg = ArgRes.get();
5392     QualType ArgType = Arg->getType();
5393     if (!ParamType->isPointerType() ||
5394         ParamType.getQualifiers().hasAddressSpace() ||
5395         !ArgType->isPointerType() ||
5396         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5397       OverloadParams.push_back(ParamType);
5398       continue;
5399     }
5400 
5401     QualType PointeeType = ParamType->getPointeeType();
5402     if (PointeeType.getQualifiers().hasAddressSpace())
5403       continue;
5404 
5405     NeedsNewDecl = true;
5406     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5407 
5408     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5409     OverloadParams.push_back(Context.getPointerType(PointeeType));
5410   }
5411 
5412   if (!NeedsNewDecl)
5413     return nullptr;
5414 
5415   FunctionProtoType::ExtProtoInfo EPI;
5416   EPI.Variadic = FT->isVariadic();
5417   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5418                                                 OverloadParams, EPI);
5419   DeclContext *Parent = FDecl->getParent();
5420   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5421                                                     FDecl->getLocation(),
5422                                                     FDecl->getLocation(),
5423                                                     FDecl->getIdentifier(),
5424                                                     OverloadTy,
5425                                                     /*TInfo=*/nullptr,
5426                                                     SC_Extern, false,
5427                                                     /*hasPrototype=*/true);
5428   SmallVector<ParmVarDecl*, 16> Params;
5429   FT = cast<FunctionProtoType>(OverloadTy);
5430   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5431     QualType ParamType = FT->getParamType(i);
5432     ParmVarDecl *Parm =
5433         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5434                                 SourceLocation(), nullptr, ParamType,
5435                                 /*TInfo=*/nullptr, SC_None, nullptr);
5436     Parm->setScopeInfo(0, i);
5437     Params.push_back(Parm);
5438   }
5439   OverloadDecl->setParams(Params);
5440   return OverloadDecl;
5441 }
5442 
5443 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5444                                     FunctionDecl *Callee,
5445                                     MultiExprArg ArgExprs) {
5446   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5447   // similar attributes) really don't like it when functions are called with an
5448   // invalid number of args.
5449   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5450                          /*PartialOverloading=*/false) &&
5451       !Callee->isVariadic())
5452     return;
5453   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5454     return;
5455 
5456   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5457     S.Diag(Fn->getBeginLoc(),
5458            isa<CXXMethodDecl>(Callee)
5459                ? diag::err_ovl_no_viable_member_function_in_call
5460                : diag::err_ovl_no_viable_function_in_call)
5461         << Callee << Callee->getSourceRange();
5462     S.Diag(Callee->getLocation(),
5463            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5464         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5465     return;
5466   }
5467 }
5468 
5469 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5470     const UnresolvedMemberExpr *const UME, Sema &S) {
5471 
5472   const auto GetFunctionLevelDCIfCXXClass =
5473       [](Sema &S) -> const CXXRecordDecl * {
5474     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5475     if (!DC || !DC->getParent())
5476       return nullptr;
5477 
5478     // If the call to some member function was made from within a member
5479     // function body 'M' return return 'M's parent.
5480     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5481       return MD->getParent()->getCanonicalDecl();
5482     // else the call was made from within a default member initializer of a
5483     // class, so return the class.
5484     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5485       return RD->getCanonicalDecl();
5486     return nullptr;
5487   };
5488   // If our DeclContext is neither a member function nor a class (in the
5489   // case of a lambda in a default member initializer), we can't have an
5490   // enclosing 'this'.
5491 
5492   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5493   if (!CurParentClass)
5494     return false;
5495 
5496   // The naming class for implicit member functions call is the class in which
5497   // name lookup starts.
5498   const CXXRecordDecl *const NamingClass =
5499       UME->getNamingClass()->getCanonicalDecl();
5500   assert(NamingClass && "Must have naming class even for implicit access");
5501 
5502   // If the unresolved member functions were found in a 'naming class' that is
5503   // related (either the same or derived from) to the class that contains the
5504   // member function that itself contained the implicit member access.
5505 
5506   return CurParentClass == NamingClass ||
5507          CurParentClass->isDerivedFrom(NamingClass);
5508 }
5509 
5510 static void
5511 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5512     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5513 
5514   if (!UME)
5515     return;
5516 
5517   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5518   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5519   // already been captured, or if this is an implicit member function call (if
5520   // it isn't, an attempt to capture 'this' should already have been made).
5521   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5522       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5523     return;
5524 
5525   // Check if the naming class in which the unresolved members were found is
5526   // related (same as or is a base of) to the enclosing class.
5527 
5528   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5529     return;
5530 
5531 
5532   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5533   // If the enclosing function is not dependent, then this lambda is
5534   // capture ready, so if we can capture this, do so.
5535   if (!EnclosingFunctionCtx->isDependentContext()) {
5536     // If the current lambda and all enclosing lambdas can capture 'this' -
5537     // then go ahead and capture 'this' (since our unresolved overload set
5538     // contains at least one non-static member function).
5539     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5540       S.CheckCXXThisCapture(CallLoc);
5541   } else if (S.CurContext->isDependentContext()) {
5542     // ... since this is an implicit member reference, that might potentially
5543     // involve a 'this' capture, mark 'this' for potential capture in
5544     // enclosing lambdas.
5545     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5546       CurLSI->addPotentialThisCapture(CallLoc);
5547   }
5548 }
5549 
5550 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5551                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5552                                Expr *ExecConfig) {
5553   ExprResult Call =
5554       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5555   if (Call.isInvalid())
5556     return Call;
5557 
5558   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5559   // language modes.
5560   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5561     if (ULE->hasExplicitTemplateArgs() &&
5562         ULE->decls_begin() == ULE->decls_end()) {
5563       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5564                                  ? diag::warn_cxx17_compat_adl_only_template_id
5565                                  : diag::ext_adl_only_template_id)
5566           << ULE->getName();
5567     }
5568   }
5569 
5570   return Call;
5571 }
5572 
5573 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5574 /// This provides the location of the left/right parens and a list of comma
5575 /// locations.
5576 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5577                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5578                                Expr *ExecConfig, bool IsExecConfig) {
5579   // Since this might be a postfix expression, get rid of ParenListExprs.
5580   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5581   if (Result.isInvalid()) return ExprError();
5582   Fn = Result.get();
5583 
5584   if (checkArgsForPlaceholders(*this, ArgExprs))
5585     return ExprError();
5586 
5587   if (getLangOpts().CPlusPlus) {
5588     // If this is a pseudo-destructor expression, build the call immediately.
5589     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5590       if (!ArgExprs.empty()) {
5591         // Pseudo-destructor calls should not have any arguments.
5592         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5593             << FixItHint::CreateRemoval(
5594                    SourceRange(ArgExprs.front()->getBeginLoc(),
5595                                ArgExprs.back()->getEndLoc()));
5596       }
5597 
5598       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5599                               VK_RValue, RParenLoc);
5600     }
5601     if (Fn->getType() == Context.PseudoObjectTy) {
5602       ExprResult result = CheckPlaceholderExpr(Fn);
5603       if (result.isInvalid()) return ExprError();
5604       Fn = result.get();
5605     }
5606 
5607     // Determine whether this is a dependent call inside a C++ template,
5608     // in which case we won't do any semantic analysis now.
5609     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5610       if (ExecConfig) {
5611         return CUDAKernelCallExpr::Create(
5612             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5613             Context.DependentTy, VK_RValue, RParenLoc);
5614       } else {
5615 
5616         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5617             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5618             Fn->getBeginLoc());
5619 
5620         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5621                                 VK_RValue, RParenLoc);
5622       }
5623     }
5624 
5625     // Determine whether this is a call to an object (C++ [over.call.object]).
5626     if (Fn->getType()->isRecordType())
5627       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5628                                           RParenLoc);
5629 
5630     if (Fn->getType() == Context.UnknownAnyTy) {
5631       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5632       if (result.isInvalid()) return ExprError();
5633       Fn = result.get();
5634     }
5635 
5636     if (Fn->getType() == Context.BoundMemberTy) {
5637       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5638                                        RParenLoc);
5639     }
5640   }
5641 
5642   // Check for overloaded calls.  This can happen even in C due to extensions.
5643   if (Fn->getType() == Context.OverloadTy) {
5644     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5645 
5646     // We aren't supposed to apply this logic if there's an '&' involved.
5647     if (!find.HasFormOfMemberPointer) {
5648       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5649         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5650                                 VK_RValue, RParenLoc);
5651       OverloadExpr *ovl = find.Expression;
5652       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5653         return BuildOverloadedCallExpr(
5654             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5655             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5656       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5657                                        RParenLoc);
5658     }
5659   }
5660 
5661   // If we're directly calling a function, get the appropriate declaration.
5662   if (Fn->getType() == Context.UnknownAnyTy) {
5663     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5664     if (result.isInvalid()) return ExprError();
5665     Fn = result.get();
5666   }
5667 
5668   Expr *NakedFn = Fn->IgnoreParens();
5669 
5670   bool CallingNDeclIndirectly = false;
5671   NamedDecl *NDecl = nullptr;
5672   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5673     if (UnOp->getOpcode() == UO_AddrOf) {
5674       CallingNDeclIndirectly = true;
5675       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5676     }
5677   }
5678 
5679   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5680     NDecl = DRE->getDecl();
5681 
5682     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5683     if (FDecl && FDecl->getBuiltinID()) {
5684       // Rewrite the function decl for this builtin by replacing parameters
5685       // with no explicit address space with the address space of the arguments
5686       // in ArgExprs.
5687       if ((FDecl =
5688                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5689         NDecl = FDecl;
5690         Fn = DeclRefExpr::Create(
5691             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5692             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5693             nullptr, DRE->isNonOdrUse());
5694       }
5695     }
5696   } else if (isa<MemberExpr>(NakedFn))
5697     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5698 
5699   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5700     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5701                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5702       return ExprError();
5703 
5704     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5705       return ExprError();
5706 
5707     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5708   }
5709 
5710   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5711                                ExecConfig, IsExecConfig);
5712 }
5713 
5714 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5715 ///
5716 /// __builtin_astype( value, dst type )
5717 ///
5718 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5719                                  SourceLocation BuiltinLoc,
5720                                  SourceLocation RParenLoc) {
5721   ExprValueKind VK = VK_RValue;
5722   ExprObjectKind OK = OK_Ordinary;
5723   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5724   QualType SrcTy = E->getType();
5725   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5726     return ExprError(Diag(BuiltinLoc,
5727                           diag::err_invalid_astype_of_different_size)
5728                      << DstTy
5729                      << SrcTy
5730                      << E->getSourceRange());
5731   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5732 }
5733 
5734 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5735 /// provided arguments.
5736 ///
5737 /// __builtin_convertvector( value, dst type )
5738 ///
5739 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5740                                         SourceLocation BuiltinLoc,
5741                                         SourceLocation RParenLoc) {
5742   TypeSourceInfo *TInfo;
5743   GetTypeFromParser(ParsedDestTy, &TInfo);
5744   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5745 }
5746 
5747 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5748 /// i.e. an expression not of \p OverloadTy.  The expression should
5749 /// unary-convert to an expression of function-pointer or
5750 /// block-pointer type.
5751 ///
5752 /// \param NDecl the declaration being called, if available
5753 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5754                                        SourceLocation LParenLoc,
5755                                        ArrayRef<Expr *> Args,
5756                                        SourceLocation RParenLoc, Expr *Config,
5757                                        bool IsExecConfig, ADLCallKind UsesADL) {
5758   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5759   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5760 
5761   // Functions with 'interrupt' attribute cannot be called directly.
5762   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5763     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5764     return ExprError();
5765   }
5766 
5767   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5768   // so there's some risk when calling out to non-interrupt handler functions
5769   // that the callee might not preserve them. This is easy to diagnose here,
5770   // but can be very challenging to debug.
5771   if (auto *Caller = getCurFunctionDecl())
5772     if (Caller->hasAttr<ARMInterruptAttr>()) {
5773       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5774       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5775         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5776     }
5777 
5778   // Promote the function operand.
5779   // We special-case function promotion here because we only allow promoting
5780   // builtin functions to function pointers in the callee of a call.
5781   ExprResult Result;
5782   QualType ResultTy;
5783   if (BuiltinID &&
5784       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5785     // Extract the return type from the (builtin) function pointer type.
5786     // FIXME Several builtins still have setType in
5787     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5788     // Builtins.def to ensure they are correct before removing setType calls.
5789     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5790     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5791     ResultTy = FDecl->getCallResultType();
5792   } else {
5793     Result = CallExprUnaryConversions(Fn);
5794     ResultTy = Context.BoolTy;
5795   }
5796   if (Result.isInvalid())
5797     return ExprError();
5798   Fn = Result.get();
5799 
5800   // Check for a valid function type, but only if it is not a builtin which
5801   // requires custom type checking. These will be handled by
5802   // CheckBuiltinFunctionCall below just after creation of the call expression.
5803   const FunctionType *FuncT = nullptr;
5804   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5805   retry:
5806     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5807       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5808       // have type pointer to function".
5809       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5810       if (!FuncT)
5811         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5812                          << Fn->getType() << Fn->getSourceRange());
5813     } else if (const BlockPointerType *BPT =
5814                    Fn->getType()->getAs<BlockPointerType>()) {
5815       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5816     } else {
5817       // Handle calls to expressions of unknown-any type.
5818       if (Fn->getType() == Context.UnknownAnyTy) {
5819         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5820         if (rewrite.isInvalid())
5821           return ExprError();
5822         Fn = rewrite.get();
5823         goto retry;
5824       }
5825 
5826       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5827                        << Fn->getType() << Fn->getSourceRange());
5828     }
5829   }
5830 
5831   // Get the number of parameters in the function prototype, if any.
5832   // We will allocate space for max(Args.size(), NumParams) arguments
5833   // in the call expression.
5834   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5835   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5836 
5837   CallExpr *TheCall;
5838   if (Config) {
5839     assert(UsesADL == ADLCallKind::NotADL &&
5840            "CUDAKernelCallExpr should not use ADL");
5841     TheCall =
5842         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5843                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5844   } else {
5845     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5846                                RParenLoc, NumParams, UsesADL);
5847   }
5848 
5849   if (!getLangOpts().CPlusPlus) {
5850     // Forget about the nulled arguments since typo correction
5851     // do not handle them well.
5852     TheCall->shrinkNumArgs(Args.size());
5853     // C cannot always handle TypoExpr nodes in builtin calls and direct
5854     // function calls as their argument checking don't necessarily handle
5855     // dependent types properly, so make sure any TypoExprs have been
5856     // dealt with.
5857     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5858     if (!Result.isUsable()) return ExprError();
5859     CallExpr *TheOldCall = TheCall;
5860     TheCall = dyn_cast<CallExpr>(Result.get());
5861     bool CorrectedTypos = TheCall != TheOldCall;
5862     if (!TheCall) return Result;
5863     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5864 
5865     // A new call expression node was created if some typos were corrected.
5866     // However it may not have been constructed with enough storage. In this
5867     // case, rebuild the node with enough storage. The waste of space is
5868     // immaterial since this only happens when some typos were corrected.
5869     if (CorrectedTypos && Args.size() < NumParams) {
5870       if (Config)
5871         TheCall = CUDAKernelCallExpr::Create(
5872             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5873             RParenLoc, NumParams);
5874       else
5875         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5876                                    RParenLoc, NumParams, UsesADL);
5877     }
5878     // We can now handle the nulled arguments for the default arguments.
5879     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5880   }
5881 
5882   // Bail out early if calling a builtin with custom type checking.
5883   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5884     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5885 
5886   if (getLangOpts().CUDA) {
5887     if (Config) {
5888       // CUDA: Kernel calls must be to global functions
5889       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5890         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5891             << FDecl << Fn->getSourceRange());
5892 
5893       // CUDA: Kernel function must have 'void' return type
5894       if (!FuncT->getReturnType()->isVoidType() &&
5895           !FuncT->getReturnType()->getAs<AutoType>() &&
5896           !FuncT->getReturnType()->isInstantiationDependentType())
5897         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5898             << Fn->getType() << Fn->getSourceRange());
5899     } else {
5900       // CUDA: Calls to global functions must be configured
5901       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5902         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5903             << FDecl << Fn->getSourceRange());
5904     }
5905   }
5906 
5907   // Check for a valid return type
5908   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5909                           FDecl))
5910     return ExprError();
5911 
5912   // We know the result type of the call, set it.
5913   TheCall->setType(FuncT->getCallResultType(Context));
5914   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5915 
5916   if (Proto) {
5917     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5918                                 IsExecConfig))
5919       return ExprError();
5920   } else {
5921     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5922 
5923     if (FDecl) {
5924       // Check if we have too few/too many template arguments, based
5925       // on our knowledge of the function definition.
5926       const FunctionDecl *Def = nullptr;
5927       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5928         Proto = Def->getType()->getAs<FunctionProtoType>();
5929        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5930           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5931           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5932       }
5933 
5934       // If the function we're calling isn't a function prototype, but we have
5935       // a function prototype from a prior declaratiom, use that prototype.
5936       if (!FDecl->hasPrototype())
5937         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5938     }
5939 
5940     // Promote the arguments (C99 6.5.2.2p6).
5941     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5942       Expr *Arg = Args[i];
5943 
5944       if (Proto && i < Proto->getNumParams()) {
5945         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5946             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5947         ExprResult ArgE =
5948             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5949         if (ArgE.isInvalid())
5950           return true;
5951 
5952         Arg = ArgE.getAs<Expr>();
5953 
5954       } else {
5955         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5956 
5957         if (ArgE.isInvalid())
5958           return true;
5959 
5960         Arg = ArgE.getAs<Expr>();
5961       }
5962 
5963       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5964                               diag::err_call_incomplete_argument, Arg))
5965         return ExprError();
5966 
5967       TheCall->setArg(i, Arg);
5968     }
5969   }
5970 
5971   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5972     if (!Method->isStatic())
5973       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5974         << Fn->getSourceRange());
5975 
5976   // Check for sentinels
5977   if (NDecl)
5978     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5979 
5980   // Do special checking on direct calls to functions.
5981   if (FDecl) {
5982     if (CheckFunctionCall(FDecl, TheCall, Proto))
5983       return ExprError();
5984 
5985     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5986 
5987     if (BuiltinID)
5988       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5989   } else if (NDecl) {
5990     if (CheckPointerCall(NDecl, TheCall, Proto))
5991       return ExprError();
5992   } else {
5993     if (CheckOtherCall(TheCall, Proto))
5994       return ExprError();
5995   }
5996 
5997   return MaybeBindToTemporary(TheCall);
5998 }
5999 
6000 ExprResult
6001 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6002                            SourceLocation RParenLoc, Expr *InitExpr) {
6003   assert(Ty && "ActOnCompoundLiteral(): missing type");
6004   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6005 
6006   TypeSourceInfo *TInfo;
6007   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6008   if (!TInfo)
6009     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6010 
6011   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6012 }
6013 
6014 ExprResult
6015 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6016                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6017   QualType literalType = TInfo->getType();
6018 
6019   if (literalType->isArrayType()) {
6020     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6021           diag::err_illegal_decl_array_incomplete_type,
6022           SourceRange(LParenLoc,
6023                       LiteralExpr->getSourceRange().getEnd())))
6024       return ExprError();
6025     if (literalType->isVariableArrayType())
6026       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6027         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6028   } else if (!literalType->isDependentType() &&
6029              RequireCompleteType(LParenLoc, literalType,
6030                diag::err_typecheck_decl_incomplete_type,
6031                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6032     return ExprError();
6033 
6034   InitializedEntity Entity
6035     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6036   InitializationKind Kind
6037     = InitializationKind::CreateCStyleCast(LParenLoc,
6038                                            SourceRange(LParenLoc, RParenLoc),
6039                                            /*InitList=*/true);
6040   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6041   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6042                                       &literalType);
6043   if (Result.isInvalid())
6044     return ExprError();
6045   LiteralExpr = Result.get();
6046 
6047   bool isFileScope = !CurContext->isFunctionOrMethod();
6048 
6049   // In C, compound literals are l-values for some reason.
6050   // For GCC compatibility, in C++, file-scope array compound literals with
6051   // constant initializers are also l-values, and compound literals are
6052   // otherwise prvalues.
6053   //
6054   // (GCC also treats C++ list-initialized file-scope array prvalues with
6055   // constant initializers as l-values, but that's non-conforming, so we don't
6056   // follow it there.)
6057   //
6058   // FIXME: It would be better to handle the lvalue cases as materializing and
6059   // lifetime-extending a temporary object, but our materialized temporaries
6060   // representation only supports lifetime extension from a variable, not "out
6061   // of thin air".
6062   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6063   // is bound to the result of applying array-to-pointer decay to the compound
6064   // literal.
6065   // FIXME: GCC supports compound literals of reference type, which should
6066   // obviously have a value kind derived from the kind of reference involved.
6067   ExprValueKind VK =
6068       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6069           ? VK_RValue
6070           : VK_LValue;
6071 
6072   if (isFileScope)
6073     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6074       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6075         Expr *Init = ILE->getInit(i);
6076         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6077       }
6078 
6079   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6080                                               VK, LiteralExpr, isFileScope);
6081   if (isFileScope) {
6082     if (!LiteralExpr->isTypeDependent() &&
6083         !LiteralExpr->isValueDependent() &&
6084         !literalType->isDependentType()) // C99 6.5.2.5p3
6085       if (CheckForConstantInitializer(LiteralExpr, literalType))
6086         return ExprError();
6087   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6088              literalType.getAddressSpace() != LangAS::Default) {
6089     // Embedded-C extensions to C99 6.5.2.5:
6090     //   "If the compound literal occurs inside the body of a function, the
6091     //   type name shall not be qualified by an address-space qualifier."
6092     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6093       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6094     return ExprError();
6095   }
6096 
6097   // Compound literals that have automatic storage duration are destroyed at
6098   // the end of the scope. Emit diagnostics if it is or contains a C union type
6099   // that is non-trivial to destruct.
6100   if (!isFileScope)
6101     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6102       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6103                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6104 
6105   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6106       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6107     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6108                                        E->getInitializer()->getExprLoc());
6109 
6110   return MaybeBindToTemporary(E);
6111 }
6112 
6113 ExprResult
6114 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6115                     SourceLocation RBraceLoc) {
6116   // Only produce each kind of designated initialization diagnostic once.
6117   SourceLocation FirstDesignator;
6118   bool DiagnosedArrayDesignator = false;
6119   bool DiagnosedNestedDesignator = false;
6120   bool DiagnosedMixedDesignator = false;
6121 
6122   // Check that any designated initializers are syntactically valid in the
6123   // current language mode.
6124   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6125     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6126       if (FirstDesignator.isInvalid())
6127         FirstDesignator = DIE->getBeginLoc();
6128 
6129       if (!getLangOpts().CPlusPlus)
6130         break;
6131 
6132       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6133         DiagnosedNestedDesignator = true;
6134         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6135           << DIE->getDesignatorsSourceRange();
6136       }
6137 
6138       for (auto &Desig : DIE->designators()) {
6139         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6140           DiagnosedArrayDesignator = true;
6141           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6142             << Desig.getSourceRange();
6143         }
6144       }
6145 
6146       if (!DiagnosedMixedDesignator &&
6147           !isa<DesignatedInitExpr>(InitArgList[0])) {
6148         DiagnosedMixedDesignator = true;
6149         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6150           << DIE->getSourceRange();
6151         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6152           << InitArgList[0]->getSourceRange();
6153       }
6154     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6155                isa<DesignatedInitExpr>(InitArgList[0])) {
6156       DiagnosedMixedDesignator = true;
6157       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6158       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6159         << DIE->getSourceRange();
6160       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6161         << InitArgList[I]->getSourceRange();
6162     }
6163   }
6164 
6165   if (FirstDesignator.isValid()) {
6166     // Only diagnose designated initiaization as a C++20 extension if we didn't
6167     // already diagnose use of (non-C++20) C99 designator syntax.
6168     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6169         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6170       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6171                                 ? diag::warn_cxx17_compat_designated_init
6172                                 : diag::ext_cxx_designated_init);
6173     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6174       Diag(FirstDesignator, diag::ext_designated_init);
6175     }
6176   }
6177 
6178   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6179 }
6180 
6181 ExprResult
6182 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6183                     SourceLocation RBraceLoc) {
6184   // Semantic analysis for initializers is done by ActOnDeclarator() and
6185   // CheckInitializer() - it requires knowledge of the object being initialized.
6186 
6187   // Immediately handle non-overload placeholders.  Overloads can be
6188   // resolved contextually, but everything else here can't.
6189   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6190     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6191       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6192 
6193       // Ignore failures; dropping the entire initializer list because
6194       // of one failure would be terrible for indexing/etc.
6195       if (result.isInvalid()) continue;
6196 
6197       InitArgList[I] = result.get();
6198     }
6199   }
6200 
6201   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6202                                                RBraceLoc);
6203   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6204   return E;
6205 }
6206 
6207 /// Do an explicit extend of the given block pointer if we're in ARC.
6208 void Sema::maybeExtendBlockObject(ExprResult &E) {
6209   assert(E.get()->getType()->isBlockPointerType());
6210   assert(E.get()->isRValue());
6211 
6212   // Only do this in an r-value context.
6213   if (!getLangOpts().ObjCAutoRefCount) return;
6214 
6215   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6216                                CK_ARCExtendBlockObject, E.get(),
6217                                /*base path*/ nullptr, VK_RValue);
6218   Cleanup.setExprNeedsCleanups(true);
6219 }
6220 
6221 /// Prepare a conversion of the given expression to an ObjC object
6222 /// pointer type.
6223 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6224   QualType type = E.get()->getType();
6225   if (type->isObjCObjectPointerType()) {
6226     return CK_BitCast;
6227   } else if (type->isBlockPointerType()) {
6228     maybeExtendBlockObject(E);
6229     return CK_BlockPointerToObjCPointerCast;
6230   } else {
6231     assert(type->isPointerType());
6232     return CK_CPointerToObjCPointerCast;
6233   }
6234 }
6235 
6236 /// Prepares for a scalar cast, performing all the necessary stages
6237 /// except the final cast and returning the kind required.
6238 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6239   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6240   // Also, callers should have filtered out the invalid cases with
6241   // pointers.  Everything else should be possible.
6242 
6243   QualType SrcTy = Src.get()->getType();
6244   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6245     return CK_NoOp;
6246 
6247   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6248   case Type::STK_MemberPointer:
6249     llvm_unreachable("member pointer type in C");
6250 
6251   case Type::STK_CPointer:
6252   case Type::STK_BlockPointer:
6253   case Type::STK_ObjCObjectPointer:
6254     switch (DestTy->getScalarTypeKind()) {
6255     case Type::STK_CPointer: {
6256       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6257       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6258       if (SrcAS != DestAS)
6259         return CK_AddressSpaceConversion;
6260       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6261         return CK_NoOp;
6262       return CK_BitCast;
6263     }
6264     case Type::STK_BlockPointer:
6265       return (SrcKind == Type::STK_BlockPointer
6266                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6267     case Type::STK_ObjCObjectPointer:
6268       if (SrcKind == Type::STK_ObjCObjectPointer)
6269         return CK_BitCast;
6270       if (SrcKind == Type::STK_CPointer)
6271         return CK_CPointerToObjCPointerCast;
6272       maybeExtendBlockObject(Src);
6273       return CK_BlockPointerToObjCPointerCast;
6274     case Type::STK_Bool:
6275       return CK_PointerToBoolean;
6276     case Type::STK_Integral:
6277       return CK_PointerToIntegral;
6278     case Type::STK_Floating:
6279     case Type::STK_FloatingComplex:
6280     case Type::STK_IntegralComplex:
6281     case Type::STK_MemberPointer:
6282     case Type::STK_FixedPoint:
6283       llvm_unreachable("illegal cast from pointer");
6284     }
6285     llvm_unreachable("Should have returned before this");
6286 
6287   case Type::STK_FixedPoint:
6288     switch (DestTy->getScalarTypeKind()) {
6289     case Type::STK_FixedPoint:
6290       return CK_FixedPointCast;
6291     case Type::STK_Bool:
6292       return CK_FixedPointToBoolean;
6293     case Type::STK_Integral:
6294       return CK_FixedPointToIntegral;
6295     case Type::STK_Floating:
6296     case Type::STK_IntegralComplex:
6297     case Type::STK_FloatingComplex:
6298       Diag(Src.get()->getExprLoc(),
6299            diag::err_unimplemented_conversion_with_fixed_point_type)
6300           << DestTy;
6301       return CK_IntegralCast;
6302     case Type::STK_CPointer:
6303     case Type::STK_ObjCObjectPointer:
6304     case Type::STK_BlockPointer:
6305     case Type::STK_MemberPointer:
6306       llvm_unreachable("illegal cast to pointer type");
6307     }
6308     llvm_unreachable("Should have returned before this");
6309 
6310   case Type::STK_Bool: // casting from bool is like casting from an integer
6311   case Type::STK_Integral:
6312     switch (DestTy->getScalarTypeKind()) {
6313     case Type::STK_CPointer:
6314     case Type::STK_ObjCObjectPointer:
6315     case Type::STK_BlockPointer:
6316       if (Src.get()->isNullPointerConstant(Context,
6317                                            Expr::NPC_ValueDependentIsNull))
6318         return CK_NullToPointer;
6319       return CK_IntegralToPointer;
6320     case Type::STK_Bool:
6321       return CK_IntegralToBoolean;
6322     case Type::STK_Integral:
6323       return CK_IntegralCast;
6324     case Type::STK_Floating:
6325       return CK_IntegralToFloating;
6326     case Type::STK_IntegralComplex:
6327       Src = ImpCastExprToType(Src.get(),
6328                       DestTy->castAs<ComplexType>()->getElementType(),
6329                       CK_IntegralCast);
6330       return CK_IntegralRealToComplex;
6331     case Type::STK_FloatingComplex:
6332       Src = ImpCastExprToType(Src.get(),
6333                       DestTy->castAs<ComplexType>()->getElementType(),
6334                       CK_IntegralToFloating);
6335       return CK_FloatingRealToComplex;
6336     case Type::STK_MemberPointer:
6337       llvm_unreachable("member pointer type in C");
6338     case Type::STK_FixedPoint:
6339       return CK_IntegralToFixedPoint;
6340     }
6341     llvm_unreachable("Should have returned before this");
6342 
6343   case Type::STK_Floating:
6344     switch (DestTy->getScalarTypeKind()) {
6345     case Type::STK_Floating:
6346       return CK_FloatingCast;
6347     case Type::STK_Bool:
6348       return CK_FloatingToBoolean;
6349     case Type::STK_Integral:
6350       return CK_FloatingToIntegral;
6351     case Type::STK_FloatingComplex:
6352       Src = ImpCastExprToType(Src.get(),
6353                               DestTy->castAs<ComplexType>()->getElementType(),
6354                               CK_FloatingCast);
6355       return CK_FloatingRealToComplex;
6356     case Type::STK_IntegralComplex:
6357       Src = ImpCastExprToType(Src.get(),
6358                               DestTy->castAs<ComplexType>()->getElementType(),
6359                               CK_FloatingToIntegral);
6360       return CK_IntegralRealToComplex;
6361     case Type::STK_CPointer:
6362     case Type::STK_ObjCObjectPointer:
6363     case Type::STK_BlockPointer:
6364       llvm_unreachable("valid float->pointer cast?");
6365     case Type::STK_MemberPointer:
6366       llvm_unreachable("member pointer type in C");
6367     case Type::STK_FixedPoint:
6368       Diag(Src.get()->getExprLoc(),
6369            diag::err_unimplemented_conversion_with_fixed_point_type)
6370           << SrcTy;
6371       return CK_IntegralCast;
6372     }
6373     llvm_unreachable("Should have returned before this");
6374 
6375   case Type::STK_FloatingComplex:
6376     switch (DestTy->getScalarTypeKind()) {
6377     case Type::STK_FloatingComplex:
6378       return CK_FloatingComplexCast;
6379     case Type::STK_IntegralComplex:
6380       return CK_FloatingComplexToIntegralComplex;
6381     case Type::STK_Floating: {
6382       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6383       if (Context.hasSameType(ET, DestTy))
6384         return CK_FloatingComplexToReal;
6385       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6386       return CK_FloatingCast;
6387     }
6388     case Type::STK_Bool:
6389       return CK_FloatingComplexToBoolean;
6390     case Type::STK_Integral:
6391       Src = ImpCastExprToType(Src.get(),
6392                               SrcTy->castAs<ComplexType>()->getElementType(),
6393                               CK_FloatingComplexToReal);
6394       return CK_FloatingToIntegral;
6395     case Type::STK_CPointer:
6396     case Type::STK_ObjCObjectPointer:
6397     case Type::STK_BlockPointer:
6398       llvm_unreachable("valid complex float->pointer cast?");
6399     case Type::STK_MemberPointer:
6400       llvm_unreachable("member pointer type in C");
6401     case Type::STK_FixedPoint:
6402       Diag(Src.get()->getExprLoc(),
6403            diag::err_unimplemented_conversion_with_fixed_point_type)
6404           << SrcTy;
6405       return CK_IntegralCast;
6406     }
6407     llvm_unreachable("Should have returned before this");
6408 
6409   case Type::STK_IntegralComplex:
6410     switch (DestTy->getScalarTypeKind()) {
6411     case Type::STK_FloatingComplex:
6412       return CK_IntegralComplexToFloatingComplex;
6413     case Type::STK_IntegralComplex:
6414       return CK_IntegralComplexCast;
6415     case Type::STK_Integral: {
6416       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6417       if (Context.hasSameType(ET, DestTy))
6418         return CK_IntegralComplexToReal;
6419       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6420       return CK_IntegralCast;
6421     }
6422     case Type::STK_Bool:
6423       return CK_IntegralComplexToBoolean;
6424     case Type::STK_Floating:
6425       Src = ImpCastExprToType(Src.get(),
6426                               SrcTy->castAs<ComplexType>()->getElementType(),
6427                               CK_IntegralComplexToReal);
6428       return CK_IntegralToFloating;
6429     case Type::STK_CPointer:
6430     case Type::STK_ObjCObjectPointer:
6431     case Type::STK_BlockPointer:
6432       llvm_unreachable("valid complex int->pointer cast?");
6433     case Type::STK_MemberPointer:
6434       llvm_unreachable("member pointer type in C");
6435     case Type::STK_FixedPoint:
6436       Diag(Src.get()->getExprLoc(),
6437            diag::err_unimplemented_conversion_with_fixed_point_type)
6438           << SrcTy;
6439       return CK_IntegralCast;
6440     }
6441     llvm_unreachable("Should have returned before this");
6442   }
6443 
6444   llvm_unreachable("Unhandled scalar cast");
6445 }
6446 
6447 static bool breakDownVectorType(QualType type, uint64_t &len,
6448                                 QualType &eltType) {
6449   // Vectors are simple.
6450   if (const VectorType *vecType = type->getAs<VectorType>()) {
6451     len = vecType->getNumElements();
6452     eltType = vecType->getElementType();
6453     assert(eltType->isScalarType());
6454     return true;
6455   }
6456 
6457   // We allow lax conversion to and from non-vector types, but only if
6458   // they're real types (i.e. non-complex, non-pointer scalar types).
6459   if (!type->isRealType()) return false;
6460 
6461   len = 1;
6462   eltType = type;
6463   return true;
6464 }
6465 
6466 /// Are the two types lax-compatible vector types?  That is, given
6467 /// that one of them is a vector, do they have equal storage sizes,
6468 /// where the storage size is the number of elements times the element
6469 /// size?
6470 ///
6471 /// This will also return false if either of the types is neither a
6472 /// vector nor a real type.
6473 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6474   assert(destTy->isVectorType() || srcTy->isVectorType());
6475 
6476   // Disallow lax conversions between scalars and ExtVectors (these
6477   // conversions are allowed for other vector types because common headers
6478   // depend on them).  Most scalar OP ExtVector cases are handled by the
6479   // splat path anyway, which does what we want (convert, not bitcast).
6480   // What this rules out for ExtVectors is crazy things like char4*float.
6481   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6482   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6483 
6484   uint64_t srcLen, destLen;
6485   QualType srcEltTy, destEltTy;
6486   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6487   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6488 
6489   // ASTContext::getTypeSize will return the size rounded up to a
6490   // power of 2, so instead of using that, we need to use the raw
6491   // element size multiplied by the element count.
6492   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6493   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6494 
6495   return (srcLen * srcEltSize == destLen * destEltSize);
6496 }
6497 
6498 /// Is this a legal conversion between two types, one of which is
6499 /// known to be a vector type?
6500 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6501   assert(destTy->isVectorType() || srcTy->isVectorType());
6502 
6503   switch (Context.getLangOpts().getLaxVectorConversions()) {
6504   case LangOptions::LaxVectorConversionKind::None:
6505     return false;
6506 
6507   case LangOptions::LaxVectorConversionKind::Integer:
6508     if (!srcTy->isIntegralOrEnumerationType()) {
6509       auto *Vec = srcTy->getAs<VectorType>();
6510       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6511         return false;
6512     }
6513     if (!destTy->isIntegralOrEnumerationType()) {
6514       auto *Vec = destTy->getAs<VectorType>();
6515       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6516         return false;
6517     }
6518     // OK, integer (vector) -> integer (vector) bitcast.
6519     break;
6520 
6521     case LangOptions::LaxVectorConversionKind::All:
6522     break;
6523   }
6524 
6525   return areLaxCompatibleVectorTypes(srcTy, destTy);
6526 }
6527 
6528 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6529                            CastKind &Kind) {
6530   assert(VectorTy->isVectorType() && "Not a vector type!");
6531 
6532   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6533     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6534       return Diag(R.getBegin(),
6535                   Ty->isVectorType() ?
6536                   diag::err_invalid_conversion_between_vectors :
6537                   diag::err_invalid_conversion_between_vector_and_integer)
6538         << VectorTy << Ty << R;
6539   } else
6540     return Diag(R.getBegin(),
6541                 diag::err_invalid_conversion_between_vector_and_scalar)
6542       << VectorTy << Ty << R;
6543 
6544   Kind = CK_BitCast;
6545   return false;
6546 }
6547 
6548 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6549   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6550 
6551   if (DestElemTy == SplattedExpr->getType())
6552     return SplattedExpr;
6553 
6554   assert(DestElemTy->isFloatingType() ||
6555          DestElemTy->isIntegralOrEnumerationType());
6556 
6557   CastKind CK;
6558   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6559     // OpenCL requires that we convert `true` boolean expressions to -1, but
6560     // only when splatting vectors.
6561     if (DestElemTy->isFloatingType()) {
6562       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6563       // in two steps: boolean to signed integral, then to floating.
6564       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6565                                                  CK_BooleanToSignedIntegral);
6566       SplattedExpr = CastExprRes.get();
6567       CK = CK_IntegralToFloating;
6568     } else {
6569       CK = CK_BooleanToSignedIntegral;
6570     }
6571   } else {
6572     ExprResult CastExprRes = SplattedExpr;
6573     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6574     if (CastExprRes.isInvalid())
6575       return ExprError();
6576     SplattedExpr = CastExprRes.get();
6577   }
6578   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6579 }
6580 
6581 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6582                                     Expr *CastExpr, CastKind &Kind) {
6583   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6584 
6585   QualType SrcTy = CastExpr->getType();
6586 
6587   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6588   // an ExtVectorType.
6589   // In OpenCL, casts between vectors of different types are not allowed.
6590   // (See OpenCL 6.2).
6591   if (SrcTy->isVectorType()) {
6592     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6593         (getLangOpts().OpenCL &&
6594          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6595       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6596         << DestTy << SrcTy << R;
6597       return ExprError();
6598     }
6599     Kind = CK_BitCast;
6600     return CastExpr;
6601   }
6602 
6603   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6604   // conversion will take place first from scalar to elt type, and then
6605   // splat from elt type to vector.
6606   if (SrcTy->isPointerType())
6607     return Diag(R.getBegin(),
6608                 diag::err_invalid_conversion_between_vector_and_scalar)
6609       << DestTy << SrcTy << R;
6610 
6611   Kind = CK_VectorSplat;
6612   return prepareVectorSplat(DestTy, CastExpr);
6613 }
6614 
6615 ExprResult
6616 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6617                     Declarator &D, ParsedType &Ty,
6618                     SourceLocation RParenLoc, Expr *CastExpr) {
6619   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6620          "ActOnCastExpr(): missing type or expr");
6621 
6622   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6623   if (D.isInvalidType())
6624     return ExprError();
6625 
6626   if (getLangOpts().CPlusPlus) {
6627     // Check that there are no default arguments (C++ only).
6628     CheckExtraCXXDefaultArguments(D);
6629   } else {
6630     // Make sure any TypoExprs have been dealt with.
6631     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6632     if (!Res.isUsable())
6633       return ExprError();
6634     CastExpr = Res.get();
6635   }
6636 
6637   checkUnusedDeclAttributes(D);
6638 
6639   QualType castType = castTInfo->getType();
6640   Ty = CreateParsedType(castType, castTInfo);
6641 
6642   bool isVectorLiteral = false;
6643 
6644   // Check for an altivec or OpenCL literal,
6645   // i.e. all the elements are integer constants.
6646   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6647   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6648   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6649        && castType->isVectorType() && (PE || PLE)) {
6650     if (PLE && PLE->getNumExprs() == 0) {
6651       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6652       return ExprError();
6653     }
6654     if (PE || PLE->getNumExprs() == 1) {
6655       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6656       if (!E->getType()->isVectorType())
6657         isVectorLiteral = true;
6658     }
6659     else
6660       isVectorLiteral = true;
6661   }
6662 
6663   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6664   // then handle it as such.
6665   if (isVectorLiteral)
6666     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6667 
6668   // If the Expr being casted is a ParenListExpr, handle it specially.
6669   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6670   // sequence of BinOp comma operators.
6671   if (isa<ParenListExpr>(CastExpr)) {
6672     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6673     if (Result.isInvalid()) return ExprError();
6674     CastExpr = Result.get();
6675   }
6676 
6677   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6678       !getSourceManager().isInSystemMacro(LParenLoc))
6679     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6680 
6681   CheckTollFreeBridgeCast(castType, CastExpr);
6682 
6683   CheckObjCBridgeRelatedCast(castType, CastExpr);
6684 
6685   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6686 
6687   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6688 }
6689 
6690 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6691                                     SourceLocation RParenLoc, Expr *E,
6692                                     TypeSourceInfo *TInfo) {
6693   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6694          "Expected paren or paren list expression");
6695 
6696   Expr **exprs;
6697   unsigned numExprs;
6698   Expr *subExpr;
6699   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6700   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6701     LiteralLParenLoc = PE->getLParenLoc();
6702     LiteralRParenLoc = PE->getRParenLoc();
6703     exprs = PE->getExprs();
6704     numExprs = PE->getNumExprs();
6705   } else { // isa<ParenExpr> by assertion at function entrance
6706     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6707     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6708     subExpr = cast<ParenExpr>(E)->getSubExpr();
6709     exprs = &subExpr;
6710     numExprs = 1;
6711   }
6712 
6713   QualType Ty = TInfo->getType();
6714   assert(Ty->isVectorType() && "Expected vector type");
6715 
6716   SmallVector<Expr *, 8> initExprs;
6717   const VectorType *VTy = Ty->castAs<VectorType>();
6718   unsigned numElems = VTy->getNumElements();
6719 
6720   // '(...)' form of vector initialization in AltiVec: the number of
6721   // initializers must be one or must match the size of the vector.
6722   // If a single value is specified in the initializer then it will be
6723   // replicated to all the components of the vector
6724   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6725     // The number of initializers must be one or must match the size of the
6726     // vector. If a single value is specified in the initializer then it will
6727     // be replicated to all the components of the vector
6728     if (numExprs == 1) {
6729       QualType ElemTy = VTy->getElementType();
6730       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6731       if (Literal.isInvalid())
6732         return ExprError();
6733       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6734                                   PrepareScalarCast(Literal, ElemTy));
6735       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6736     }
6737     else if (numExprs < numElems) {
6738       Diag(E->getExprLoc(),
6739            diag::err_incorrect_number_of_vector_initializers);
6740       return ExprError();
6741     }
6742     else
6743       initExprs.append(exprs, exprs + numExprs);
6744   }
6745   else {
6746     // For OpenCL, when the number of initializers is a single value,
6747     // it will be replicated to all components of the vector.
6748     if (getLangOpts().OpenCL &&
6749         VTy->getVectorKind() == VectorType::GenericVector &&
6750         numExprs == 1) {
6751         QualType ElemTy = VTy->getElementType();
6752         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6753         if (Literal.isInvalid())
6754           return ExprError();
6755         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6756                                     PrepareScalarCast(Literal, ElemTy));
6757         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6758     }
6759 
6760     initExprs.append(exprs, exprs + numExprs);
6761   }
6762   // FIXME: This means that pretty-printing the final AST will produce curly
6763   // braces instead of the original commas.
6764   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6765                                                    initExprs, LiteralRParenLoc);
6766   initE->setType(Ty);
6767   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6768 }
6769 
6770 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6771 /// the ParenListExpr into a sequence of comma binary operators.
6772 ExprResult
6773 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6774   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6775   if (!E)
6776     return OrigExpr;
6777 
6778   ExprResult Result(E->getExpr(0));
6779 
6780   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6781     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6782                         E->getExpr(i));
6783 
6784   if (Result.isInvalid()) return ExprError();
6785 
6786   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6787 }
6788 
6789 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6790                                     SourceLocation R,
6791                                     MultiExprArg Val) {
6792   return ParenListExpr::Create(Context, L, Val, R);
6793 }
6794 
6795 /// Emit a specialized diagnostic when one expression is a null pointer
6796 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6797 /// emitted.
6798 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6799                                       SourceLocation QuestionLoc) {
6800   Expr *NullExpr = LHSExpr;
6801   Expr *NonPointerExpr = RHSExpr;
6802   Expr::NullPointerConstantKind NullKind =
6803       NullExpr->isNullPointerConstant(Context,
6804                                       Expr::NPC_ValueDependentIsNotNull);
6805 
6806   if (NullKind == Expr::NPCK_NotNull) {
6807     NullExpr = RHSExpr;
6808     NonPointerExpr = LHSExpr;
6809     NullKind =
6810         NullExpr->isNullPointerConstant(Context,
6811                                         Expr::NPC_ValueDependentIsNotNull);
6812   }
6813 
6814   if (NullKind == Expr::NPCK_NotNull)
6815     return false;
6816 
6817   if (NullKind == Expr::NPCK_ZeroExpression)
6818     return false;
6819 
6820   if (NullKind == Expr::NPCK_ZeroLiteral) {
6821     // In this case, check to make sure that we got here from a "NULL"
6822     // string in the source code.
6823     NullExpr = NullExpr->IgnoreParenImpCasts();
6824     SourceLocation loc = NullExpr->getExprLoc();
6825     if (!findMacroSpelling(loc, "NULL"))
6826       return false;
6827   }
6828 
6829   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6830   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6831       << NonPointerExpr->getType() << DiagType
6832       << NonPointerExpr->getSourceRange();
6833   return true;
6834 }
6835 
6836 /// Return false if the condition expression is valid, true otherwise.
6837 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6838   QualType CondTy = Cond->getType();
6839 
6840   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6841   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6842     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6843       << CondTy << Cond->getSourceRange();
6844     return true;
6845   }
6846 
6847   // C99 6.5.15p2
6848   if (CondTy->isScalarType()) return false;
6849 
6850   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6851     << CondTy << Cond->getSourceRange();
6852   return true;
6853 }
6854 
6855 /// Handle when one or both operands are void type.
6856 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6857                                          ExprResult &RHS) {
6858     Expr *LHSExpr = LHS.get();
6859     Expr *RHSExpr = RHS.get();
6860 
6861     if (!LHSExpr->getType()->isVoidType())
6862       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6863           << RHSExpr->getSourceRange();
6864     if (!RHSExpr->getType()->isVoidType())
6865       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6866           << LHSExpr->getSourceRange();
6867     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6868     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6869     return S.Context.VoidTy;
6870 }
6871 
6872 /// Return false if the NullExpr can be promoted to PointerTy,
6873 /// true otherwise.
6874 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6875                                         QualType PointerTy) {
6876   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6877       !NullExpr.get()->isNullPointerConstant(S.Context,
6878                                             Expr::NPC_ValueDependentIsNull))
6879     return true;
6880 
6881   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6882   return false;
6883 }
6884 
6885 /// Checks compatibility between two pointers and return the resulting
6886 /// type.
6887 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6888                                                      ExprResult &RHS,
6889                                                      SourceLocation Loc) {
6890   QualType LHSTy = LHS.get()->getType();
6891   QualType RHSTy = RHS.get()->getType();
6892 
6893   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6894     // Two identical pointers types are always compatible.
6895     return LHSTy;
6896   }
6897 
6898   QualType lhptee, rhptee;
6899 
6900   // Get the pointee types.
6901   bool IsBlockPointer = false;
6902   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6903     lhptee = LHSBTy->getPointeeType();
6904     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6905     IsBlockPointer = true;
6906   } else {
6907     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6908     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6909   }
6910 
6911   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6912   // differently qualified versions of compatible types, the result type is
6913   // a pointer to an appropriately qualified version of the composite
6914   // type.
6915 
6916   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6917   // clause doesn't make sense for our extensions. E.g. address space 2 should
6918   // be incompatible with address space 3: they may live on different devices or
6919   // anything.
6920   Qualifiers lhQual = lhptee.getQualifiers();
6921   Qualifiers rhQual = rhptee.getQualifiers();
6922 
6923   LangAS ResultAddrSpace = LangAS::Default;
6924   LangAS LAddrSpace = lhQual.getAddressSpace();
6925   LangAS RAddrSpace = rhQual.getAddressSpace();
6926 
6927   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6928   // spaces is disallowed.
6929   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6930     ResultAddrSpace = LAddrSpace;
6931   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6932     ResultAddrSpace = RAddrSpace;
6933   else {
6934     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6935         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6936         << RHS.get()->getSourceRange();
6937     return QualType();
6938   }
6939 
6940   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6941   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6942   lhQual.removeCVRQualifiers();
6943   rhQual.removeCVRQualifiers();
6944 
6945   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6946   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6947   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6948   // qual types are compatible iff
6949   //  * corresponded types are compatible
6950   //  * CVR qualifiers are equal
6951   //  * address spaces are equal
6952   // Thus for conditional operator we merge CVR and address space unqualified
6953   // pointees and if there is a composite type we return a pointer to it with
6954   // merged qualifiers.
6955   LHSCastKind =
6956       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6957   RHSCastKind =
6958       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6959   lhQual.removeAddressSpace();
6960   rhQual.removeAddressSpace();
6961 
6962   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6963   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6964 
6965   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6966 
6967   if (CompositeTy.isNull()) {
6968     // In this situation, we assume void* type. No especially good
6969     // reason, but this is what gcc does, and we do have to pick
6970     // to get a consistent AST.
6971     QualType incompatTy;
6972     incompatTy = S.Context.getPointerType(
6973         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6974     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6975     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6976 
6977     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6978     // for casts between types with incompatible address space qualifiers.
6979     // For the following code the compiler produces casts between global and
6980     // local address spaces of the corresponded innermost pointees:
6981     // local int *global *a;
6982     // global int *global *b;
6983     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6984     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6985         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6986         << RHS.get()->getSourceRange();
6987 
6988     return incompatTy;
6989   }
6990 
6991   // The pointer types are compatible.
6992   // In case of OpenCL ResultTy should have the address space qualifier
6993   // which is a superset of address spaces of both the 2nd and the 3rd
6994   // operands of the conditional operator.
6995   QualType ResultTy = [&, ResultAddrSpace]() {
6996     if (S.getLangOpts().OpenCL) {
6997       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6998       CompositeQuals.setAddressSpace(ResultAddrSpace);
6999       return S.Context
7000           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7001           .withCVRQualifiers(MergedCVRQual);
7002     }
7003     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7004   }();
7005   if (IsBlockPointer)
7006     ResultTy = S.Context.getBlockPointerType(ResultTy);
7007   else
7008     ResultTy = S.Context.getPointerType(ResultTy);
7009 
7010   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7011   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7012   return ResultTy;
7013 }
7014 
7015 /// Return the resulting type when the operands are both block pointers.
7016 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7017                                                           ExprResult &LHS,
7018                                                           ExprResult &RHS,
7019                                                           SourceLocation Loc) {
7020   QualType LHSTy = LHS.get()->getType();
7021   QualType RHSTy = RHS.get()->getType();
7022 
7023   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7024     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7025       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7026       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7027       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7028       return destType;
7029     }
7030     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7031       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7032       << RHS.get()->getSourceRange();
7033     return QualType();
7034   }
7035 
7036   // We have 2 block pointer types.
7037   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7038 }
7039 
7040 /// Return the resulting type when the operands are both pointers.
7041 static QualType
7042 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7043                                             ExprResult &RHS,
7044                                             SourceLocation Loc) {
7045   // get the pointer types
7046   QualType LHSTy = LHS.get()->getType();
7047   QualType RHSTy = RHS.get()->getType();
7048 
7049   // get the "pointed to" types
7050   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7051   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7052 
7053   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7054   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7055     // Figure out necessary qualifiers (C99 6.5.15p6)
7056     QualType destPointee
7057       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7058     QualType destType = S.Context.getPointerType(destPointee);
7059     // Add qualifiers if necessary.
7060     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7061     // Promote to void*.
7062     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7063     return destType;
7064   }
7065   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7066     QualType destPointee
7067       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7068     QualType destType = S.Context.getPointerType(destPointee);
7069     // Add qualifiers if necessary.
7070     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7071     // Promote to void*.
7072     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7073     return destType;
7074   }
7075 
7076   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7077 }
7078 
7079 /// Return false if the first expression is not an integer and the second
7080 /// expression is not a pointer, true otherwise.
7081 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7082                                         Expr* PointerExpr, SourceLocation Loc,
7083                                         bool IsIntFirstExpr) {
7084   if (!PointerExpr->getType()->isPointerType() ||
7085       !Int.get()->getType()->isIntegerType())
7086     return false;
7087 
7088   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7089   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7090 
7091   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7092     << Expr1->getType() << Expr2->getType()
7093     << Expr1->getSourceRange() << Expr2->getSourceRange();
7094   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7095                             CK_IntegralToPointer);
7096   return true;
7097 }
7098 
7099 /// Simple conversion between integer and floating point types.
7100 ///
7101 /// Used when handling the OpenCL conditional operator where the
7102 /// condition is a vector while the other operands are scalar.
7103 ///
7104 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7105 /// types are either integer or floating type. Between the two
7106 /// operands, the type with the higher rank is defined as the "result
7107 /// type". The other operand needs to be promoted to the same type. No
7108 /// other type promotion is allowed. We cannot use
7109 /// UsualArithmeticConversions() for this purpose, since it always
7110 /// promotes promotable types.
7111 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7112                                             ExprResult &RHS,
7113                                             SourceLocation QuestionLoc) {
7114   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7115   if (LHS.isInvalid())
7116     return QualType();
7117   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7118   if (RHS.isInvalid())
7119     return QualType();
7120 
7121   // For conversion purposes, we ignore any qualifiers.
7122   // For example, "const float" and "float" are equivalent.
7123   QualType LHSType =
7124     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7125   QualType RHSType =
7126     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7127 
7128   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7129     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7130       << LHSType << LHS.get()->getSourceRange();
7131     return QualType();
7132   }
7133 
7134   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7135     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7136       << RHSType << RHS.get()->getSourceRange();
7137     return QualType();
7138   }
7139 
7140   // If both types are identical, no conversion is needed.
7141   if (LHSType == RHSType)
7142     return LHSType;
7143 
7144   // Now handle "real" floating types (i.e. float, double, long double).
7145   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7146     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7147                                  /*IsCompAssign = */ false);
7148 
7149   // Finally, we have two differing integer types.
7150   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7151   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7152 }
7153 
7154 /// Convert scalar operands to a vector that matches the
7155 ///        condition in length.
7156 ///
7157 /// Used when handling the OpenCL conditional operator where the
7158 /// condition is a vector while the other operands are scalar.
7159 ///
7160 /// We first compute the "result type" for the scalar operands
7161 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7162 /// into a vector of that type where the length matches the condition
7163 /// vector type. s6.11.6 requires that the element types of the result
7164 /// and the condition must have the same number of bits.
7165 static QualType
7166 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7167                               QualType CondTy, SourceLocation QuestionLoc) {
7168   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7169   if (ResTy.isNull()) return QualType();
7170 
7171   const VectorType *CV = CondTy->getAs<VectorType>();
7172   assert(CV);
7173 
7174   // Determine the vector result type
7175   unsigned NumElements = CV->getNumElements();
7176   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7177 
7178   // Ensure that all types have the same number of bits
7179   if (S.Context.getTypeSize(CV->getElementType())
7180       != S.Context.getTypeSize(ResTy)) {
7181     // Since VectorTy is created internally, it does not pretty print
7182     // with an OpenCL name. Instead, we just print a description.
7183     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7184     SmallString<64> Str;
7185     llvm::raw_svector_ostream OS(Str);
7186     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7187     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7188       << CondTy << OS.str();
7189     return QualType();
7190   }
7191 
7192   // Convert operands to the vector result type
7193   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7194   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7195 
7196   return VectorTy;
7197 }
7198 
7199 /// Return false if this is a valid OpenCL condition vector
7200 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7201                                        SourceLocation QuestionLoc) {
7202   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7203   // integral type.
7204   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7205   assert(CondTy);
7206   QualType EleTy = CondTy->getElementType();
7207   if (EleTy->isIntegerType()) return false;
7208 
7209   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7210     << Cond->getType() << Cond->getSourceRange();
7211   return true;
7212 }
7213 
7214 /// Return false if the vector condition type and the vector
7215 ///        result type are compatible.
7216 ///
7217 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7218 /// number of elements, and their element types have the same number
7219 /// of bits.
7220 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7221                               SourceLocation QuestionLoc) {
7222   const VectorType *CV = CondTy->getAs<VectorType>();
7223   const VectorType *RV = VecResTy->getAs<VectorType>();
7224   assert(CV && RV);
7225 
7226   if (CV->getNumElements() != RV->getNumElements()) {
7227     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7228       << CondTy << VecResTy;
7229     return true;
7230   }
7231 
7232   QualType CVE = CV->getElementType();
7233   QualType RVE = RV->getElementType();
7234 
7235   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7236     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7237       << CondTy << VecResTy;
7238     return true;
7239   }
7240 
7241   return false;
7242 }
7243 
7244 /// Return the resulting type for the conditional operator in
7245 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7246 ///        s6.3.i) when the condition is a vector type.
7247 static QualType
7248 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7249                              ExprResult &LHS, ExprResult &RHS,
7250                              SourceLocation QuestionLoc) {
7251   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7252   if (Cond.isInvalid())
7253     return QualType();
7254   QualType CondTy = Cond.get()->getType();
7255 
7256   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7257     return QualType();
7258 
7259   // If either operand is a vector then find the vector type of the
7260   // result as specified in OpenCL v1.1 s6.3.i.
7261   if (LHS.get()->getType()->isVectorType() ||
7262       RHS.get()->getType()->isVectorType()) {
7263     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7264                                               /*isCompAssign*/false,
7265                                               /*AllowBothBool*/true,
7266                                               /*AllowBoolConversions*/false);
7267     if (VecResTy.isNull()) return QualType();
7268     // The result type must match the condition type as specified in
7269     // OpenCL v1.1 s6.11.6.
7270     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7271       return QualType();
7272     return VecResTy;
7273   }
7274 
7275   // Both operands are scalar.
7276   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7277 }
7278 
7279 /// Return true if the Expr is block type
7280 static bool checkBlockType(Sema &S, const Expr *E) {
7281   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7282     QualType Ty = CE->getCallee()->getType();
7283     if (Ty->isBlockPointerType()) {
7284       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7285       return true;
7286     }
7287   }
7288   return false;
7289 }
7290 
7291 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7292 /// In that case, LHS = cond.
7293 /// C99 6.5.15
7294 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7295                                         ExprResult &RHS, ExprValueKind &VK,
7296                                         ExprObjectKind &OK,
7297                                         SourceLocation QuestionLoc) {
7298 
7299   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7300   if (!LHSResult.isUsable()) return QualType();
7301   LHS = LHSResult;
7302 
7303   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7304   if (!RHSResult.isUsable()) return QualType();
7305   RHS = RHSResult;
7306 
7307   // C++ is sufficiently different to merit its own checker.
7308   if (getLangOpts().CPlusPlus)
7309     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7310 
7311   VK = VK_RValue;
7312   OK = OK_Ordinary;
7313 
7314   // The OpenCL operator with a vector condition is sufficiently
7315   // different to merit its own checker.
7316   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7317     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7318 
7319   // First, check the condition.
7320   Cond = UsualUnaryConversions(Cond.get());
7321   if (Cond.isInvalid())
7322     return QualType();
7323   if (checkCondition(*this, Cond.get(), QuestionLoc))
7324     return QualType();
7325 
7326   // Now check the two expressions.
7327   if (LHS.get()->getType()->isVectorType() ||
7328       RHS.get()->getType()->isVectorType())
7329     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7330                                /*AllowBothBool*/true,
7331                                /*AllowBoolConversions*/false);
7332 
7333   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7334   if (LHS.isInvalid() || RHS.isInvalid())
7335     return QualType();
7336 
7337   QualType LHSTy = LHS.get()->getType();
7338   QualType RHSTy = RHS.get()->getType();
7339 
7340   // Diagnose attempts to convert between __float128 and long double where
7341   // such conversions currently can't be handled.
7342   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7343     Diag(QuestionLoc,
7344          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7345       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7346     return QualType();
7347   }
7348 
7349   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7350   // selection operator (?:).
7351   if (getLangOpts().OpenCL &&
7352       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7353     return QualType();
7354   }
7355 
7356   // If both operands have arithmetic type, do the usual arithmetic conversions
7357   // to find a common type: C99 6.5.15p3,5.
7358   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7359     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7360     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7361 
7362     return ResTy;
7363   }
7364 
7365   // If both operands are the same structure or union type, the result is that
7366   // type.
7367   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7368     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7369       if (LHSRT->getDecl() == RHSRT->getDecl())
7370         // "If both the operands have structure or union type, the result has
7371         // that type."  This implies that CV qualifiers are dropped.
7372         return LHSTy.getUnqualifiedType();
7373     // FIXME: Type of conditional expression must be complete in C mode.
7374   }
7375 
7376   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7377   // The following || allows only one side to be void (a GCC-ism).
7378   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7379     return checkConditionalVoidType(*this, LHS, RHS);
7380   }
7381 
7382   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7383   // the type of the other operand."
7384   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7385   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7386 
7387   // All objective-c pointer type analysis is done here.
7388   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7389                                                         QuestionLoc);
7390   if (LHS.isInvalid() || RHS.isInvalid())
7391     return QualType();
7392   if (!compositeType.isNull())
7393     return compositeType;
7394 
7395 
7396   // Handle block pointer types.
7397   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7398     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7399                                                      QuestionLoc);
7400 
7401   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7402   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7403     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7404                                                        QuestionLoc);
7405 
7406   // GCC compatibility: soften pointer/integer mismatch.  Note that
7407   // null pointers have been filtered out by this point.
7408   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7409       /*IsIntFirstExpr=*/true))
7410     return RHSTy;
7411   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7412       /*IsIntFirstExpr=*/false))
7413     return LHSTy;
7414 
7415   // Emit a better diagnostic if one of the expressions is a null pointer
7416   // constant and the other is not a pointer type. In this case, the user most
7417   // likely forgot to take the address of the other expression.
7418   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7419     return QualType();
7420 
7421   // Otherwise, the operands are not compatible.
7422   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7423     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7424     << RHS.get()->getSourceRange();
7425   return QualType();
7426 }
7427 
7428 /// FindCompositeObjCPointerType - Helper method to find composite type of
7429 /// two objective-c pointer types of the two input expressions.
7430 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7431                                             SourceLocation QuestionLoc) {
7432   QualType LHSTy = LHS.get()->getType();
7433   QualType RHSTy = RHS.get()->getType();
7434 
7435   // Handle things like Class and struct objc_class*.  Here we case the result
7436   // to the pseudo-builtin, because that will be implicitly cast back to the
7437   // redefinition type if an attempt is made to access its fields.
7438   if (LHSTy->isObjCClassType() &&
7439       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7440     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7441     return LHSTy;
7442   }
7443   if (RHSTy->isObjCClassType() &&
7444       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7445     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7446     return RHSTy;
7447   }
7448   // And the same for struct objc_object* / id
7449   if (LHSTy->isObjCIdType() &&
7450       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7451     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7452     return LHSTy;
7453   }
7454   if (RHSTy->isObjCIdType() &&
7455       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7456     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7457     return RHSTy;
7458   }
7459   // And the same for struct objc_selector* / SEL
7460   if (Context.isObjCSelType(LHSTy) &&
7461       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7462     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7463     return LHSTy;
7464   }
7465   if (Context.isObjCSelType(RHSTy) &&
7466       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7467     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7468     return RHSTy;
7469   }
7470   // Check constraints for Objective-C object pointers types.
7471   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7472 
7473     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7474       // Two identical object pointer types are always compatible.
7475       return LHSTy;
7476     }
7477     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7478     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7479     QualType compositeType = LHSTy;
7480 
7481     // If both operands are interfaces and either operand can be
7482     // assigned to the other, use that type as the composite
7483     // type. This allows
7484     //   xxx ? (A*) a : (B*) b
7485     // where B is a subclass of A.
7486     //
7487     // Additionally, as for assignment, if either type is 'id'
7488     // allow silent coercion. Finally, if the types are
7489     // incompatible then make sure to use 'id' as the composite
7490     // type so the result is acceptable for sending messages to.
7491 
7492     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7493     // It could return the composite type.
7494     if (!(compositeType =
7495           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7496       // Nothing more to do.
7497     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7498       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7499     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7500       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7501     } else if ((LHSOPT->isObjCQualifiedIdType() ||
7502                 RHSOPT->isObjCQualifiedIdType()) &&
7503                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7504                                                          true)) {
7505       // Need to handle "id<xx>" explicitly.
7506       // GCC allows qualified id and any Objective-C type to devolve to
7507       // id. Currently localizing to here until clear this should be
7508       // part of ObjCQualifiedIdTypesAreCompatible.
7509       compositeType = Context.getObjCIdType();
7510     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7511       compositeType = Context.getObjCIdType();
7512     } else {
7513       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7514       << LHSTy << RHSTy
7515       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7516       QualType incompatTy = Context.getObjCIdType();
7517       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7518       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7519       return incompatTy;
7520     }
7521     // The object pointer types are compatible.
7522     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7523     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7524     return compositeType;
7525   }
7526   // Check Objective-C object pointer types and 'void *'
7527   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7528     if (getLangOpts().ObjCAutoRefCount) {
7529       // ARC forbids the implicit conversion of object pointers to 'void *',
7530       // so these types are not compatible.
7531       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7532           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7533       LHS = RHS = true;
7534       return QualType();
7535     }
7536     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7537     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7538     QualType destPointee
7539     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7540     QualType destType = Context.getPointerType(destPointee);
7541     // Add qualifiers if necessary.
7542     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7543     // Promote to void*.
7544     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7545     return destType;
7546   }
7547   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7548     if (getLangOpts().ObjCAutoRefCount) {
7549       // ARC forbids the implicit conversion of object pointers to 'void *',
7550       // so these types are not compatible.
7551       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7552           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7553       LHS = RHS = true;
7554       return QualType();
7555     }
7556     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7557     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7558     QualType destPointee
7559     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7560     QualType destType = Context.getPointerType(destPointee);
7561     // Add qualifiers if necessary.
7562     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7563     // Promote to void*.
7564     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7565     return destType;
7566   }
7567   return QualType();
7568 }
7569 
7570 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7571 /// ParenRange in parentheses.
7572 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7573                                const PartialDiagnostic &Note,
7574                                SourceRange ParenRange) {
7575   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7576   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7577       EndLoc.isValid()) {
7578     Self.Diag(Loc, Note)
7579       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7580       << FixItHint::CreateInsertion(EndLoc, ")");
7581   } else {
7582     // We can't display the parentheses, so just show the bare note.
7583     Self.Diag(Loc, Note) << ParenRange;
7584   }
7585 }
7586 
7587 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7588   return BinaryOperator::isAdditiveOp(Opc) ||
7589          BinaryOperator::isMultiplicativeOp(Opc) ||
7590          BinaryOperator::isShiftOp(Opc);
7591 }
7592 
7593 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7594 /// expression, either using a built-in or overloaded operator,
7595 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7596 /// expression.
7597 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7598                                    Expr **RHSExprs) {
7599   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7600   E = E->IgnoreImpCasts();
7601   E = E->IgnoreConversionOperator();
7602   E = E->IgnoreImpCasts();
7603   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7604     E = MTE->GetTemporaryExpr();
7605     E = E->IgnoreImpCasts();
7606   }
7607 
7608   // Built-in binary operator.
7609   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7610     if (IsArithmeticOp(OP->getOpcode())) {
7611       *Opcode = OP->getOpcode();
7612       *RHSExprs = OP->getRHS();
7613       return true;
7614     }
7615   }
7616 
7617   // Overloaded operator.
7618   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7619     if (Call->getNumArgs() != 2)
7620       return false;
7621 
7622     // Make sure this is really a binary operator that is safe to pass into
7623     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7624     OverloadedOperatorKind OO = Call->getOperator();
7625     if (OO < OO_Plus || OO > OO_Arrow ||
7626         OO == OO_PlusPlus || OO == OO_MinusMinus)
7627       return false;
7628 
7629     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7630     if (IsArithmeticOp(OpKind)) {
7631       *Opcode = OpKind;
7632       *RHSExprs = Call->getArg(1);
7633       return true;
7634     }
7635   }
7636 
7637   return false;
7638 }
7639 
7640 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7641 /// or is a logical expression such as (x==y) which has int type, but is
7642 /// commonly interpreted as boolean.
7643 static bool ExprLooksBoolean(Expr *E) {
7644   E = E->IgnoreParenImpCasts();
7645 
7646   if (E->getType()->isBooleanType())
7647     return true;
7648   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7649     return OP->isComparisonOp() || OP->isLogicalOp();
7650   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7651     return OP->getOpcode() == UO_LNot;
7652   if (E->getType()->isPointerType())
7653     return true;
7654   // FIXME: What about overloaded operator calls returning "unspecified boolean
7655   // type"s (commonly pointer-to-members)?
7656 
7657   return false;
7658 }
7659 
7660 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7661 /// and binary operator are mixed in a way that suggests the programmer assumed
7662 /// the conditional operator has higher precedence, for example:
7663 /// "int x = a + someBinaryCondition ? 1 : 2".
7664 static void DiagnoseConditionalPrecedence(Sema &Self,
7665                                           SourceLocation OpLoc,
7666                                           Expr *Condition,
7667                                           Expr *LHSExpr,
7668                                           Expr *RHSExpr) {
7669   BinaryOperatorKind CondOpcode;
7670   Expr *CondRHS;
7671 
7672   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7673     return;
7674   if (!ExprLooksBoolean(CondRHS))
7675     return;
7676 
7677   // The condition is an arithmetic binary expression, with a right-
7678   // hand side that looks boolean, so warn.
7679 
7680   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7681       << Condition->getSourceRange()
7682       << BinaryOperator::getOpcodeStr(CondOpcode);
7683 
7684   SuggestParentheses(
7685       Self, OpLoc,
7686       Self.PDiag(diag::note_precedence_silence)
7687           << BinaryOperator::getOpcodeStr(CondOpcode),
7688       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7689 
7690   SuggestParentheses(Self, OpLoc,
7691                      Self.PDiag(diag::note_precedence_conditional_first),
7692                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7693 }
7694 
7695 /// Compute the nullability of a conditional expression.
7696 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7697                                               QualType LHSTy, QualType RHSTy,
7698                                               ASTContext &Ctx) {
7699   if (!ResTy->isAnyPointerType())
7700     return ResTy;
7701 
7702   auto GetNullability = [&Ctx](QualType Ty) {
7703     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7704     if (Kind)
7705       return *Kind;
7706     return NullabilityKind::Unspecified;
7707   };
7708 
7709   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7710   NullabilityKind MergedKind;
7711 
7712   // Compute nullability of a binary conditional expression.
7713   if (IsBin) {
7714     if (LHSKind == NullabilityKind::NonNull)
7715       MergedKind = NullabilityKind::NonNull;
7716     else
7717       MergedKind = RHSKind;
7718   // Compute nullability of a normal conditional expression.
7719   } else {
7720     if (LHSKind == NullabilityKind::Nullable ||
7721         RHSKind == NullabilityKind::Nullable)
7722       MergedKind = NullabilityKind::Nullable;
7723     else if (LHSKind == NullabilityKind::NonNull)
7724       MergedKind = RHSKind;
7725     else if (RHSKind == NullabilityKind::NonNull)
7726       MergedKind = LHSKind;
7727     else
7728       MergedKind = NullabilityKind::Unspecified;
7729   }
7730 
7731   // Return if ResTy already has the correct nullability.
7732   if (GetNullability(ResTy) == MergedKind)
7733     return ResTy;
7734 
7735   // Strip all nullability from ResTy.
7736   while (ResTy->getNullability(Ctx))
7737     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7738 
7739   // Create a new AttributedType with the new nullability kind.
7740   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7741   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7742 }
7743 
7744 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7745 /// in the case of a the GNU conditional expr extension.
7746 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7747                                     SourceLocation ColonLoc,
7748                                     Expr *CondExpr, Expr *LHSExpr,
7749                                     Expr *RHSExpr) {
7750   if (!getLangOpts().CPlusPlus) {
7751     // C cannot handle TypoExpr nodes in the condition because it
7752     // doesn't handle dependent types properly, so make sure any TypoExprs have
7753     // been dealt with before checking the operands.
7754     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7755     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7756     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7757 
7758     if (!CondResult.isUsable())
7759       return ExprError();
7760 
7761     if (LHSExpr) {
7762       if (!LHSResult.isUsable())
7763         return ExprError();
7764     }
7765 
7766     if (!RHSResult.isUsable())
7767       return ExprError();
7768 
7769     CondExpr = CondResult.get();
7770     LHSExpr = LHSResult.get();
7771     RHSExpr = RHSResult.get();
7772   }
7773 
7774   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7775   // was the condition.
7776   OpaqueValueExpr *opaqueValue = nullptr;
7777   Expr *commonExpr = nullptr;
7778   if (!LHSExpr) {
7779     commonExpr = CondExpr;
7780     // Lower out placeholder types first.  This is important so that we don't
7781     // try to capture a placeholder. This happens in few cases in C++; such
7782     // as Objective-C++'s dictionary subscripting syntax.
7783     if (commonExpr->hasPlaceholderType()) {
7784       ExprResult result = CheckPlaceholderExpr(commonExpr);
7785       if (!result.isUsable()) return ExprError();
7786       commonExpr = result.get();
7787     }
7788     // We usually want to apply unary conversions *before* saving, except
7789     // in the special case of a C++ l-value conditional.
7790     if (!(getLangOpts().CPlusPlus
7791           && !commonExpr->isTypeDependent()
7792           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7793           && commonExpr->isGLValue()
7794           && commonExpr->isOrdinaryOrBitFieldObject()
7795           && RHSExpr->isOrdinaryOrBitFieldObject()
7796           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7797       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7798       if (commonRes.isInvalid())
7799         return ExprError();
7800       commonExpr = commonRes.get();
7801     }
7802 
7803     // If the common expression is a class or array prvalue, materialize it
7804     // so that we can safely refer to it multiple times.
7805     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7806                                    commonExpr->getType()->isArrayType())) {
7807       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7808       if (MatExpr.isInvalid())
7809         return ExprError();
7810       commonExpr = MatExpr.get();
7811     }
7812 
7813     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7814                                                 commonExpr->getType(),
7815                                                 commonExpr->getValueKind(),
7816                                                 commonExpr->getObjectKind(),
7817                                                 commonExpr);
7818     LHSExpr = CondExpr = opaqueValue;
7819   }
7820 
7821   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7822   ExprValueKind VK = VK_RValue;
7823   ExprObjectKind OK = OK_Ordinary;
7824   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7825   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7826                                              VK, OK, QuestionLoc);
7827   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7828       RHS.isInvalid())
7829     return ExprError();
7830 
7831   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7832                                 RHS.get());
7833 
7834   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7835 
7836   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7837                                          Context);
7838 
7839   if (!commonExpr)
7840     return new (Context)
7841         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7842                             RHS.get(), result, VK, OK);
7843 
7844   return new (Context) BinaryConditionalOperator(
7845       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7846       ColonLoc, result, VK, OK);
7847 }
7848 
7849 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7850 // being closely modeled after the C99 spec:-). The odd characteristic of this
7851 // routine is it effectively iqnores the qualifiers on the top level pointee.
7852 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7853 // FIXME: add a couple examples in this comment.
7854 static Sema::AssignConvertType
7855 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7856   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7857   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7858 
7859   // get the "pointed to" type (ignoring qualifiers at the top level)
7860   const Type *lhptee, *rhptee;
7861   Qualifiers lhq, rhq;
7862   std::tie(lhptee, lhq) =
7863       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7864   std::tie(rhptee, rhq) =
7865       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7866 
7867   Sema::AssignConvertType ConvTy = Sema::Compatible;
7868 
7869   // C99 6.5.16.1p1: This following citation is common to constraints
7870   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7871   // qualifiers of the type *pointed to* by the right;
7872 
7873   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7874   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7875       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7876     // Ignore lifetime for further calculation.
7877     lhq.removeObjCLifetime();
7878     rhq.removeObjCLifetime();
7879   }
7880 
7881   if (!lhq.compatiblyIncludes(rhq)) {
7882     // Treat address-space mismatches as fatal.
7883     if (!lhq.isAddressSpaceSupersetOf(rhq))
7884       return Sema::IncompatiblePointerDiscardsQualifiers;
7885 
7886     // It's okay to add or remove GC or lifetime qualifiers when converting to
7887     // and from void*.
7888     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7889                         .compatiblyIncludes(
7890                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7891              && (lhptee->isVoidType() || rhptee->isVoidType()))
7892       ; // keep old
7893 
7894     // Treat lifetime mismatches as fatal.
7895     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7896       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7897 
7898     // For GCC/MS compatibility, other qualifier mismatches are treated
7899     // as still compatible in C.
7900     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7901   }
7902 
7903   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7904   // incomplete type and the other is a pointer to a qualified or unqualified
7905   // version of void...
7906   if (lhptee->isVoidType()) {
7907     if (rhptee->isIncompleteOrObjectType())
7908       return ConvTy;
7909 
7910     // As an extension, we allow cast to/from void* to function pointer.
7911     assert(rhptee->isFunctionType());
7912     return Sema::FunctionVoidPointer;
7913   }
7914 
7915   if (rhptee->isVoidType()) {
7916     if (lhptee->isIncompleteOrObjectType())
7917       return ConvTy;
7918 
7919     // As an extension, we allow cast to/from void* to function pointer.
7920     assert(lhptee->isFunctionType());
7921     return Sema::FunctionVoidPointer;
7922   }
7923 
7924   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7925   // unqualified versions of compatible types, ...
7926   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7927   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7928     // Check if the pointee types are compatible ignoring the sign.
7929     // We explicitly check for char so that we catch "char" vs
7930     // "unsigned char" on systems where "char" is unsigned.
7931     if (lhptee->isCharType())
7932       ltrans = S.Context.UnsignedCharTy;
7933     else if (lhptee->hasSignedIntegerRepresentation())
7934       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7935 
7936     if (rhptee->isCharType())
7937       rtrans = S.Context.UnsignedCharTy;
7938     else if (rhptee->hasSignedIntegerRepresentation())
7939       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7940 
7941     if (ltrans == rtrans) {
7942       // Types are compatible ignoring the sign. Qualifier incompatibility
7943       // takes priority over sign incompatibility because the sign
7944       // warning can be disabled.
7945       if (ConvTy != Sema::Compatible)
7946         return ConvTy;
7947 
7948       return Sema::IncompatiblePointerSign;
7949     }
7950 
7951     // If we are a multi-level pointer, it's possible that our issue is simply
7952     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7953     // the eventual target type is the same and the pointers have the same
7954     // level of indirection, this must be the issue.
7955     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7956       do {
7957         std::tie(lhptee, lhq) =
7958           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7959         std::tie(rhptee, rhq) =
7960           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7961 
7962         // Inconsistent address spaces at this point is invalid, even if the
7963         // address spaces would be compatible.
7964         // FIXME: This doesn't catch address space mismatches for pointers of
7965         // different nesting levels, like:
7966         //   __local int *** a;
7967         //   int ** b = a;
7968         // It's not clear how to actually determine when such pointers are
7969         // invalidly incompatible.
7970         if (lhq.getAddressSpace() != rhq.getAddressSpace())
7971           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
7972 
7973       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7974 
7975       if (lhptee == rhptee)
7976         return Sema::IncompatibleNestedPointerQualifiers;
7977     }
7978 
7979     // General pointer incompatibility takes priority over qualifiers.
7980     return Sema::IncompatiblePointer;
7981   }
7982   if (!S.getLangOpts().CPlusPlus &&
7983       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7984     return Sema::IncompatiblePointer;
7985   return ConvTy;
7986 }
7987 
7988 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7989 /// block pointer types are compatible or whether a block and normal pointer
7990 /// are compatible. It is more restrict than comparing two function pointer
7991 // types.
7992 static Sema::AssignConvertType
7993 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7994                                     QualType RHSType) {
7995   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7996   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7997 
7998   QualType lhptee, rhptee;
7999 
8000   // get the "pointed to" type (ignoring qualifiers at the top level)
8001   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8002   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8003 
8004   // In C++, the types have to match exactly.
8005   if (S.getLangOpts().CPlusPlus)
8006     return Sema::IncompatibleBlockPointer;
8007 
8008   Sema::AssignConvertType ConvTy = Sema::Compatible;
8009 
8010   // For blocks we enforce that qualifiers are identical.
8011   Qualifiers LQuals = lhptee.getLocalQualifiers();
8012   Qualifiers RQuals = rhptee.getLocalQualifiers();
8013   if (S.getLangOpts().OpenCL) {
8014     LQuals.removeAddressSpace();
8015     RQuals.removeAddressSpace();
8016   }
8017   if (LQuals != RQuals)
8018     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8019 
8020   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8021   // assignment.
8022   // The current behavior is similar to C++ lambdas. A block might be
8023   // assigned to a variable iff its return type and parameters are compatible
8024   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8025   // an assignment. Presumably it should behave in way that a function pointer
8026   // assignment does in C, so for each parameter and return type:
8027   //  * CVR and address space of LHS should be a superset of CVR and address
8028   //  space of RHS.
8029   //  * unqualified types should be compatible.
8030   if (S.getLangOpts().OpenCL) {
8031     if (!S.Context.typesAreBlockPointerCompatible(
8032             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8033             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8034       return Sema::IncompatibleBlockPointer;
8035   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8036     return Sema::IncompatibleBlockPointer;
8037 
8038   return ConvTy;
8039 }
8040 
8041 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8042 /// for assignment compatibility.
8043 static Sema::AssignConvertType
8044 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8045                                    QualType RHSType) {
8046   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8047   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8048 
8049   if (LHSType->isObjCBuiltinType()) {
8050     // Class is not compatible with ObjC object pointers.
8051     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8052         !RHSType->isObjCQualifiedClassType())
8053       return Sema::IncompatiblePointer;
8054     return Sema::Compatible;
8055   }
8056   if (RHSType->isObjCBuiltinType()) {
8057     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8058         !LHSType->isObjCQualifiedClassType())
8059       return Sema::IncompatiblePointer;
8060     return Sema::Compatible;
8061   }
8062   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8063   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8064 
8065   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8066       // make an exception for id<P>
8067       !LHSType->isObjCQualifiedIdType())
8068     return Sema::CompatiblePointerDiscardsQualifiers;
8069 
8070   if (S.Context.typesAreCompatible(LHSType, RHSType))
8071     return Sema::Compatible;
8072   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8073     return Sema::IncompatibleObjCQualifiedId;
8074   return Sema::IncompatiblePointer;
8075 }
8076 
8077 Sema::AssignConvertType
8078 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8079                                  QualType LHSType, QualType RHSType) {
8080   // Fake up an opaque expression.  We don't actually care about what
8081   // cast operations are required, so if CheckAssignmentConstraints
8082   // adds casts to this they'll be wasted, but fortunately that doesn't
8083   // usually happen on valid code.
8084   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8085   ExprResult RHSPtr = &RHSExpr;
8086   CastKind K;
8087 
8088   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8089 }
8090 
8091 /// This helper function returns true if QT is a vector type that has element
8092 /// type ElementType.
8093 static bool isVector(QualType QT, QualType ElementType) {
8094   if (const VectorType *VT = QT->getAs<VectorType>())
8095     return VT->getElementType() == ElementType;
8096   return false;
8097 }
8098 
8099 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8100 /// has code to accommodate several GCC extensions when type checking
8101 /// pointers. Here are some objectionable examples that GCC considers warnings:
8102 ///
8103 ///  int a, *pint;
8104 ///  short *pshort;
8105 ///  struct foo *pfoo;
8106 ///
8107 ///  pint = pshort; // warning: assignment from incompatible pointer type
8108 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8109 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8110 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8111 ///
8112 /// As a result, the code for dealing with pointers is more complex than the
8113 /// C99 spec dictates.
8114 ///
8115 /// Sets 'Kind' for any result kind except Incompatible.
8116 Sema::AssignConvertType
8117 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8118                                  CastKind &Kind, bool ConvertRHS) {
8119   QualType RHSType = RHS.get()->getType();
8120   QualType OrigLHSType = LHSType;
8121 
8122   // Get canonical types.  We're not formatting these types, just comparing
8123   // them.
8124   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8125   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8126 
8127   // Common case: no conversion required.
8128   if (LHSType == RHSType) {
8129     Kind = CK_NoOp;
8130     return Compatible;
8131   }
8132 
8133   // If we have an atomic type, try a non-atomic assignment, then just add an
8134   // atomic qualification step.
8135   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8136     Sema::AssignConvertType result =
8137       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8138     if (result != Compatible)
8139       return result;
8140     if (Kind != CK_NoOp && ConvertRHS)
8141       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8142     Kind = CK_NonAtomicToAtomic;
8143     return Compatible;
8144   }
8145 
8146   // If the left-hand side is a reference type, then we are in a
8147   // (rare!) case where we've allowed the use of references in C,
8148   // e.g., as a parameter type in a built-in function. In this case,
8149   // just make sure that the type referenced is compatible with the
8150   // right-hand side type. The caller is responsible for adjusting
8151   // LHSType so that the resulting expression does not have reference
8152   // type.
8153   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8154     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8155       Kind = CK_LValueBitCast;
8156       return Compatible;
8157     }
8158     return Incompatible;
8159   }
8160 
8161   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8162   // to the same ExtVector type.
8163   if (LHSType->isExtVectorType()) {
8164     if (RHSType->isExtVectorType())
8165       return Incompatible;
8166     if (RHSType->isArithmeticType()) {
8167       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8168       if (ConvertRHS)
8169         RHS = prepareVectorSplat(LHSType, RHS.get());
8170       Kind = CK_VectorSplat;
8171       return Compatible;
8172     }
8173   }
8174 
8175   // Conversions to or from vector type.
8176   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8177     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8178       // Allow assignments of an AltiVec vector type to an equivalent GCC
8179       // vector type and vice versa
8180       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8181         Kind = CK_BitCast;
8182         return Compatible;
8183       }
8184 
8185       // If we are allowing lax vector conversions, and LHS and RHS are both
8186       // vectors, the total size only needs to be the same. This is a bitcast;
8187       // no bits are changed but the result type is different.
8188       if (isLaxVectorConversion(RHSType, LHSType)) {
8189         Kind = CK_BitCast;
8190         return IncompatibleVectors;
8191       }
8192     }
8193 
8194     // When the RHS comes from another lax conversion (e.g. binops between
8195     // scalars and vectors) the result is canonicalized as a vector. When the
8196     // LHS is also a vector, the lax is allowed by the condition above. Handle
8197     // the case where LHS is a scalar.
8198     if (LHSType->isScalarType()) {
8199       const VectorType *VecType = RHSType->getAs<VectorType>();
8200       if (VecType && VecType->getNumElements() == 1 &&
8201           isLaxVectorConversion(RHSType, LHSType)) {
8202         ExprResult *VecExpr = &RHS;
8203         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8204         Kind = CK_BitCast;
8205         return Compatible;
8206       }
8207     }
8208 
8209     return Incompatible;
8210   }
8211 
8212   // Diagnose attempts to convert between __float128 and long double where
8213   // such conversions currently can't be handled.
8214   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8215     return Incompatible;
8216 
8217   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8218   // discards the imaginary part.
8219   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8220       !LHSType->getAs<ComplexType>())
8221     return Incompatible;
8222 
8223   // Arithmetic conversions.
8224   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8225       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8226     if (ConvertRHS)
8227       Kind = PrepareScalarCast(RHS, LHSType);
8228     return Compatible;
8229   }
8230 
8231   // Conversions to normal pointers.
8232   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8233     // U* -> T*
8234     if (isa<PointerType>(RHSType)) {
8235       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8236       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8237       if (AddrSpaceL != AddrSpaceR)
8238         Kind = CK_AddressSpaceConversion;
8239       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8240         Kind = CK_NoOp;
8241       else
8242         Kind = CK_BitCast;
8243       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8244     }
8245 
8246     // int -> T*
8247     if (RHSType->isIntegerType()) {
8248       Kind = CK_IntegralToPointer; // FIXME: null?
8249       return IntToPointer;
8250     }
8251 
8252     // C pointers are not compatible with ObjC object pointers,
8253     // with two exceptions:
8254     if (isa<ObjCObjectPointerType>(RHSType)) {
8255       //  - conversions to void*
8256       if (LHSPointer->getPointeeType()->isVoidType()) {
8257         Kind = CK_BitCast;
8258         return Compatible;
8259       }
8260 
8261       //  - conversions from 'Class' to the redefinition type
8262       if (RHSType->isObjCClassType() &&
8263           Context.hasSameType(LHSType,
8264                               Context.getObjCClassRedefinitionType())) {
8265         Kind = CK_BitCast;
8266         return Compatible;
8267       }
8268 
8269       Kind = CK_BitCast;
8270       return IncompatiblePointer;
8271     }
8272 
8273     // U^ -> void*
8274     if (RHSType->getAs<BlockPointerType>()) {
8275       if (LHSPointer->getPointeeType()->isVoidType()) {
8276         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8277         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8278                                 ->getPointeeType()
8279                                 .getAddressSpace();
8280         Kind =
8281             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8282         return Compatible;
8283       }
8284     }
8285 
8286     return Incompatible;
8287   }
8288 
8289   // Conversions to block pointers.
8290   if (isa<BlockPointerType>(LHSType)) {
8291     // U^ -> T^
8292     if (RHSType->isBlockPointerType()) {
8293       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8294                               ->getPointeeType()
8295                               .getAddressSpace();
8296       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8297                               ->getPointeeType()
8298                               .getAddressSpace();
8299       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8300       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8301     }
8302 
8303     // int or null -> T^
8304     if (RHSType->isIntegerType()) {
8305       Kind = CK_IntegralToPointer; // FIXME: null
8306       return IntToBlockPointer;
8307     }
8308 
8309     // id -> T^
8310     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8311       Kind = CK_AnyPointerToBlockPointerCast;
8312       return Compatible;
8313     }
8314 
8315     // void* -> T^
8316     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8317       if (RHSPT->getPointeeType()->isVoidType()) {
8318         Kind = CK_AnyPointerToBlockPointerCast;
8319         return Compatible;
8320       }
8321 
8322     return Incompatible;
8323   }
8324 
8325   // Conversions to Objective-C pointers.
8326   if (isa<ObjCObjectPointerType>(LHSType)) {
8327     // A* -> B*
8328     if (RHSType->isObjCObjectPointerType()) {
8329       Kind = CK_BitCast;
8330       Sema::AssignConvertType result =
8331         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8332       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8333           result == Compatible &&
8334           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8335         result = IncompatibleObjCWeakRef;
8336       return result;
8337     }
8338 
8339     // int or null -> A*
8340     if (RHSType->isIntegerType()) {
8341       Kind = CK_IntegralToPointer; // FIXME: null
8342       return IntToPointer;
8343     }
8344 
8345     // In general, C pointers are not compatible with ObjC object pointers,
8346     // with two exceptions:
8347     if (isa<PointerType>(RHSType)) {
8348       Kind = CK_CPointerToObjCPointerCast;
8349 
8350       //  - conversions from 'void*'
8351       if (RHSType->isVoidPointerType()) {
8352         return Compatible;
8353       }
8354 
8355       //  - conversions to 'Class' from its redefinition type
8356       if (LHSType->isObjCClassType() &&
8357           Context.hasSameType(RHSType,
8358                               Context.getObjCClassRedefinitionType())) {
8359         return Compatible;
8360       }
8361 
8362       return IncompatiblePointer;
8363     }
8364 
8365     // Only under strict condition T^ is compatible with an Objective-C pointer.
8366     if (RHSType->isBlockPointerType() &&
8367         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8368       if (ConvertRHS)
8369         maybeExtendBlockObject(RHS);
8370       Kind = CK_BlockPointerToObjCPointerCast;
8371       return Compatible;
8372     }
8373 
8374     return Incompatible;
8375   }
8376 
8377   // Conversions from pointers that are not covered by the above.
8378   if (isa<PointerType>(RHSType)) {
8379     // T* -> _Bool
8380     if (LHSType == Context.BoolTy) {
8381       Kind = CK_PointerToBoolean;
8382       return Compatible;
8383     }
8384 
8385     // T* -> int
8386     if (LHSType->isIntegerType()) {
8387       Kind = CK_PointerToIntegral;
8388       return PointerToInt;
8389     }
8390 
8391     return Incompatible;
8392   }
8393 
8394   // Conversions from Objective-C pointers that are not covered by the above.
8395   if (isa<ObjCObjectPointerType>(RHSType)) {
8396     // T* -> _Bool
8397     if (LHSType == Context.BoolTy) {
8398       Kind = CK_PointerToBoolean;
8399       return Compatible;
8400     }
8401 
8402     // T* -> int
8403     if (LHSType->isIntegerType()) {
8404       Kind = CK_PointerToIntegral;
8405       return PointerToInt;
8406     }
8407 
8408     return Incompatible;
8409   }
8410 
8411   // struct A -> struct B
8412   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8413     if (Context.typesAreCompatible(LHSType, RHSType)) {
8414       Kind = CK_NoOp;
8415       return Compatible;
8416     }
8417   }
8418 
8419   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8420     Kind = CK_IntToOCLSampler;
8421     return Compatible;
8422   }
8423 
8424   return Incompatible;
8425 }
8426 
8427 /// Constructs a transparent union from an expression that is
8428 /// used to initialize the transparent union.
8429 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8430                                       ExprResult &EResult, QualType UnionType,
8431                                       FieldDecl *Field) {
8432   // Build an initializer list that designates the appropriate member
8433   // of the transparent union.
8434   Expr *E = EResult.get();
8435   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8436                                                    E, SourceLocation());
8437   Initializer->setType(UnionType);
8438   Initializer->setInitializedFieldInUnion(Field);
8439 
8440   // Build a compound literal constructing a value of the transparent
8441   // union type from this initializer list.
8442   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8443   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8444                                         VK_RValue, Initializer, false);
8445 }
8446 
8447 Sema::AssignConvertType
8448 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8449                                                ExprResult &RHS) {
8450   QualType RHSType = RHS.get()->getType();
8451 
8452   // If the ArgType is a Union type, we want to handle a potential
8453   // transparent_union GCC extension.
8454   const RecordType *UT = ArgType->getAsUnionType();
8455   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8456     return Incompatible;
8457 
8458   // The field to initialize within the transparent union.
8459   RecordDecl *UD = UT->getDecl();
8460   FieldDecl *InitField = nullptr;
8461   // It's compatible if the expression matches any of the fields.
8462   for (auto *it : UD->fields()) {
8463     if (it->getType()->isPointerType()) {
8464       // If the transparent union contains a pointer type, we allow:
8465       // 1) void pointer
8466       // 2) null pointer constant
8467       if (RHSType->isPointerType())
8468         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8469           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8470           InitField = it;
8471           break;
8472         }
8473 
8474       if (RHS.get()->isNullPointerConstant(Context,
8475                                            Expr::NPC_ValueDependentIsNull)) {
8476         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8477                                 CK_NullToPointer);
8478         InitField = it;
8479         break;
8480       }
8481     }
8482 
8483     CastKind Kind;
8484     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8485           == Compatible) {
8486       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8487       InitField = it;
8488       break;
8489     }
8490   }
8491 
8492   if (!InitField)
8493     return Incompatible;
8494 
8495   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8496   return Compatible;
8497 }
8498 
8499 Sema::AssignConvertType
8500 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8501                                        bool Diagnose,
8502                                        bool DiagnoseCFAudited,
8503                                        bool ConvertRHS) {
8504   // We need to be able to tell the caller whether we diagnosed a problem, if
8505   // they ask us to issue diagnostics.
8506   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8507 
8508   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8509   // we can't avoid *all* modifications at the moment, so we need some somewhere
8510   // to put the updated value.
8511   ExprResult LocalRHS = CallerRHS;
8512   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8513 
8514   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8515     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8516       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8517           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8518         Diag(RHS.get()->getExprLoc(),
8519              diag::warn_noderef_to_dereferenceable_pointer)
8520             << RHS.get()->getSourceRange();
8521       }
8522     }
8523   }
8524 
8525   if (getLangOpts().CPlusPlus) {
8526     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8527       // C++ 5.17p3: If the left operand is not of class type, the
8528       // expression is implicitly converted (C++ 4) to the
8529       // cv-unqualified type of the left operand.
8530       QualType RHSType = RHS.get()->getType();
8531       if (Diagnose) {
8532         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8533                                         AA_Assigning);
8534       } else {
8535         ImplicitConversionSequence ICS =
8536             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8537                                   /*SuppressUserConversions=*/false,
8538                                   /*AllowExplicit=*/false,
8539                                   /*InOverloadResolution=*/false,
8540                                   /*CStyle=*/false,
8541                                   /*AllowObjCWritebackConversion=*/false);
8542         if (ICS.isFailure())
8543           return Incompatible;
8544         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8545                                         ICS, AA_Assigning);
8546       }
8547       if (RHS.isInvalid())
8548         return Incompatible;
8549       Sema::AssignConvertType result = Compatible;
8550       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8551           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8552         result = IncompatibleObjCWeakRef;
8553       return result;
8554     }
8555 
8556     // FIXME: Currently, we fall through and treat C++ classes like C
8557     // structures.
8558     // FIXME: We also fall through for atomics; not sure what should
8559     // happen there, though.
8560   } else if (RHS.get()->getType() == Context.OverloadTy) {
8561     // As a set of extensions to C, we support overloading on functions. These
8562     // functions need to be resolved here.
8563     DeclAccessPair DAP;
8564     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8565             RHS.get(), LHSType, /*Complain=*/false, DAP))
8566       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8567     else
8568       return Incompatible;
8569   }
8570 
8571   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8572   // a null pointer constant.
8573   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8574        LHSType->isBlockPointerType()) &&
8575       RHS.get()->isNullPointerConstant(Context,
8576                                        Expr::NPC_ValueDependentIsNull)) {
8577     if (Diagnose || ConvertRHS) {
8578       CastKind Kind;
8579       CXXCastPath Path;
8580       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8581                              /*IgnoreBaseAccess=*/false, Diagnose);
8582       if (ConvertRHS)
8583         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8584     }
8585     return Compatible;
8586   }
8587 
8588   // OpenCL queue_t type assignment.
8589   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8590                                  Context, Expr::NPC_ValueDependentIsNull)) {
8591     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8592     return Compatible;
8593   }
8594 
8595   // This check seems unnatural, however it is necessary to ensure the proper
8596   // conversion of functions/arrays. If the conversion were done for all
8597   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8598   // expressions that suppress this implicit conversion (&, sizeof).
8599   //
8600   // Suppress this for references: C++ 8.5.3p5.
8601   if (!LHSType->isReferenceType()) {
8602     // FIXME: We potentially allocate here even if ConvertRHS is false.
8603     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8604     if (RHS.isInvalid())
8605       return Incompatible;
8606   }
8607   CastKind Kind;
8608   Sema::AssignConvertType result =
8609     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8610 
8611   // C99 6.5.16.1p2: The value of the right operand is converted to the
8612   // type of the assignment expression.
8613   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8614   // so that we can use references in built-in functions even in C.
8615   // The getNonReferenceType() call makes sure that the resulting expression
8616   // does not have reference type.
8617   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8618     QualType Ty = LHSType.getNonLValueExprType(Context);
8619     Expr *E = RHS.get();
8620 
8621     // Check for various Objective-C errors. If we are not reporting
8622     // diagnostics and just checking for errors, e.g., during overload
8623     // resolution, return Incompatible to indicate the failure.
8624     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8625         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8626                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8627       if (!Diagnose)
8628         return Incompatible;
8629     }
8630     if (getLangOpts().ObjC &&
8631         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8632                                            E->getType(), E, Diagnose) ||
8633          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8634       if (!Diagnose)
8635         return Incompatible;
8636       // Replace the expression with a corrected version and continue so we
8637       // can find further errors.
8638       RHS = E;
8639       return Compatible;
8640     }
8641 
8642     if (ConvertRHS)
8643       RHS = ImpCastExprToType(E, Ty, Kind);
8644   }
8645 
8646   return result;
8647 }
8648 
8649 namespace {
8650 /// The original operand to an operator, prior to the application of the usual
8651 /// arithmetic conversions and converting the arguments of a builtin operator
8652 /// candidate.
8653 struct OriginalOperand {
8654   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8655     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8656       Op = MTE->GetTemporaryExpr();
8657     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8658       Op = BTE->getSubExpr();
8659     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8660       Orig = ICE->getSubExprAsWritten();
8661       Conversion = ICE->getConversionFunction();
8662     }
8663   }
8664 
8665   QualType getType() const { return Orig->getType(); }
8666 
8667   Expr *Orig;
8668   NamedDecl *Conversion;
8669 };
8670 }
8671 
8672 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8673                                ExprResult &RHS) {
8674   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8675 
8676   Diag(Loc, diag::err_typecheck_invalid_operands)
8677     << OrigLHS.getType() << OrigRHS.getType()
8678     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8679 
8680   // If a user-defined conversion was applied to either of the operands prior
8681   // to applying the built-in operator rules, tell the user about it.
8682   if (OrigLHS.Conversion) {
8683     Diag(OrigLHS.Conversion->getLocation(),
8684          diag::note_typecheck_invalid_operands_converted)
8685       << 0 << LHS.get()->getType();
8686   }
8687   if (OrigRHS.Conversion) {
8688     Diag(OrigRHS.Conversion->getLocation(),
8689          diag::note_typecheck_invalid_operands_converted)
8690       << 1 << RHS.get()->getType();
8691   }
8692 
8693   return QualType();
8694 }
8695 
8696 // Diagnose cases where a scalar was implicitly converted to a vector and
8697 // diagnose the underlying types. Otherwise, diagnose the error
8698 // as invalid vector logical operands for non-C++ cases.
8699 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8700                                             ExprResult &RHS) {
8701   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8702   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8703 
8704   bool LHSNatVec = LHSType->isVectorType();
8705   bool RHSNatVec = RHSType->isVectorType();
8706 
8707   if (!(LHSNatVec && RHSNatVec)) {
8708     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8709     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8710     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8711         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8712         << Vector->getSourceRange();
8713     return QualType();
8714   }
8715 
8716   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8717       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8718       << RHS.get()->getSourceRange();
8719 
8720   return QualType();
8721 }
8722 
8723 /// Try to convert a value of non-vector type to a vector type by converting
8724 /// the type to the element type of the vector and then performing a splat.
8725 /// If the language is OpenCL, we only use conversions that promote scalar
8726 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8727 /// for float->int.
8728 ///
8729 /// OpenCL V2.0 6.2.6.p2:
8730 /// An error shall occur if any scalar operand type has greater rank
8731 /// than the type of the vector element.
8732 ///
8733 /// \param scalar - if non-null, actually perform the conversions
8734 /// \return true if the operation fails (but without diagnosing the failure)
8735 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8736                                      QualType scalarTy,
8737                                      QualType vectorEltTy,
8738                                      QualType vectorTy,
8739                                      unsigned &DiagID) {
8740   // The conversion to apply to the scalar before splatting it,
8741   // if necessary.
8742   CastKind scalarCast = CK_NoOp;
8743 
8744   if (vectorEltTy->isIntegralType(S.Context)) {
8745     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8746         (scalarTy->isIntegerType() &&
8747          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8748       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8749       return true;
8750     }
8751     if (!scalarTy->isIntegralType(S.Context))
8752       return true;
8753     scalarCast = CK_IntegralCast;
8754   } else if (vectorEltTy->isRealFloatingType()) {
8755     if (scalarTy->isRealFloatingType()) {
8756       if (S.getLangOpts().OpenCL &&
8757           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8758         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8759         return true;
8760       }
8761       scalarCast = CK_FloatingCast;
8762     }
8763     else if (scalarTy->isIntegralType(S.Context))
8764       scalarCast = CK_IntegralToFloating;
8765     else
8766       return true;
8767   } else {
8768     return true;
8769   }
8770 
8771   // Adjust scalar if desired.
8772   if (scalar) {
8773     if (scalarCast != CK_NoOp)
8774       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8775     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8776   }
8777   return false;
8778 }
8779 
8780 /// Convert vector E to a vector with the same number of elements but different
8781 /// element type.
8782 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8783   const auto *VecTy = E->getType()->getAs<VectorType>();
8784   assert(VecTy && "Expression E must be a vector");
8785   QualType NewVecTy = S.Context.getVectorType(ElementType,
8786                                               VecTy->getNumElements(),
8787                                               VecTy->getVectorKind());
8788 
8789   // Look through the implicit cast. Return the subexpression if its type is
8790   // NewVecTy.
8791   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8792     if (ICE->getSubExpr()->getType() == NewVecTy)
8793       return ICE->getSubExpr();
8794 
8795   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8796   return S.ImpCastExprToType(E, NewVecTy, Cast);
8797 }
8798 
8799 /// Test if a (constant) integer Int can be casted to another integer type
8800 /// IntTy without losing precision.
8801 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8802                                       QualType OtherIntTy) {
8803   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8804 
8805   // Reject cases where the value of the Int is unknown as that would
8806   // possibly cause truncation, but accept cases where the scalar can be
8807   // demoted without loss of precision.
8808   Expr::EvalResult EVResult;
8809   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8810   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8811   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8812   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8813 
8814   if (CstInt) {
8815     // If the scalar is constant and is of a higher order and has more active
8816     // bits that the vector element type, reject it.
8817     llvm::APSInt Result = EVResult.Val.getInt();
8818     unsigned NumBits = IntSigned
8819                            ? (Result.isNegative() ? Result.getMinSignedBits()
8820                                                   : Result.getActiveBits())
8821                            : Result.getActiveBits();
8822     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8823       return true;
8824 
8825     // If the signedness of the scalar type and the vector element type
8826     // differs and the number of bits is greater than that of the vector
8827     // element reject it.
8828     return (IntSigned != OtherIntSigned &&
8829             NumBits > S.Context.getIntWidth(OtherIntTy));
8830   }
8831 
8832   // Reject cases where the value of the scalar is not constant and it's
8833   // order is greater than that of the vector element type.
8834   return (Order < 0);
8835 }
8836 
8837 /// Test if a (constant) integer Int can be casted to floating point type
8838 /// FloatTy without losing precision.
8839 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8840                                      QualType FloatTy) {
8841   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8842 
8843   // Determine if the integer constant can be expressed as a floating point
8844   // number of the appropriate type.
8845   Expr::EvalResult EVResult;
8846   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8847 
8848   uint64_t Bits = 0;
8849   if (CstInt) {
8850     // Reject constants that would be truncated if they were converted to
8851     // the floating point type. Test by simple to/from conversion.
8852     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8853     //        could be avoided if there was a convertFromAPInt method
8854     //        which could signal back if implicit truncation occurred.
8855     llvm::APSInt Result = EVResult.Val.getInt();
8856     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8857     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8858                            llvm::APFloat::rmTowardZero);
8859     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8860                              !IntTy->hasSignedIntegerRepresentation());
8861     bool Ignored = false;
8862     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8863                            &Ignored);
8864     if (Result != ConvertBack)
8865       return true;
8866   } else {
8867     // Reject types that cannot be fully encoded into the mantissa of
8868     // the float.
8869     Bits = S.Context.getTypeSize(IntTy);
8870     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8871         S.Context.getFloatTypeSemantics(FloatTy));
8872     if (Bits > FloatPrec)
8873       return true;
8874   }
8875 
8876   return false;
8877 }
8878 
8879 /// Attempt to convert and splat Scalar into a vector whose types matches
8880 /// Vector following GCC conversion rules. The rule is that implicit
8881 /// conversion can occur when Scalar can be casted to match Vector's element
8882 /// type without causing truncation of Scalar.
8883 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8884                                         ExprResult *Vector) {
8885   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8886   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8887   const VectorType *VT = VectorTy->getAs<VectorType>();
8888 
8889   assert(!isa<ExtVectorType>(VT) &&
8890          "ExtVectorTypes should not be handled here!");
8891 
8892   QualType VectorEltTy = VT->getElementType();
8893 
8894   // Reject cases where the vector element type or the scalar element type are
8895   // not integral or floating point types.
8896   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8897     return true;
8898 
8899   // The conversion to apply to the scalar before splatting it,
8900   // if necessary.
8901   CastKind ScalarCast = CK_NoOp;
8902 
8903   // Accept cases where the vector elements are integers and the scalar is
8904   // an integer.
8905   // FIXME: Notionally if the scalar was a floating point value with a precise
8906   //        integral representation, we could cast it to an appropriate integer
8907   //        type and then perform the rest of the checks here. GCC will perform
8908   //        this conversion in some cases as determined by the input language.
8909   //        We should accept it on a language independent basis.
8910   if (VectorEltTy->isIntegralType(S.Context) &&
8911       ScalarTy->isIntegralType(S.Context) &&
8912       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8913 
8914     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8915       return true;
8916 
8917     ScalarCast = CK_IntegralCast;
8918   } else if (VectorEltTy->isRealFloatingType()) {
8919     if (ScalarTy->isRealFloatingType()) {
8920 
8921       // Reject cases where the scalar type is not a constant and has a higher
8922       // Order than the vector element type.
8923       llvm::APFloat Result(0.0);
8924       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8925       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8926       if (!CstScalar && Order < 0)
8927         return true;
8928 
8929       // If the scalar cannot be safely casted to the vector element type,
8930       // reject it.
8931       if (CstScalar) {
8932         bool Truncated = false;
8933         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8934                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8935         if (Truncated)
8936           return true;
8937       }
8938 
8939       ScalarCast = CK_FloatingCast;
8940     } else if (ScalarTy->isIntegralType(S.Context)) {
8941       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8942         return true;
8943 
8944       ScalarCast = CK_IntegralToFloating;
8945     } else
8946       return true;
8947   }
8948 
8949   // Adjust scalar if desired.
8950   if (Scalar) {
8951     if (ScalarCast != CK_NoOp)
8952       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8953     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8954   }
8955   return false;
8956 }
8957 
8958 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8959                                    SourceLocation Loc, bool IsCompAssign,
8960                                    bool AllowBothBool,
8961                                    bool AllowBoolConversions) {
8962   if (!IsCompAssign) {
8963     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8964     if (LHS.isInvalid())
8965       return QualType();
8966   }
8967   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8968   if (RHS.isInvalid())
8969     return QualType();
8970 
8971   // For conversion purposes, we ignore any qualifiers.
8972   // For example, "const float" and "float" are equivalent.
8973   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8974   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8975 
8976   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8977   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8978   assert(LHSVecType || RHSVecType);
8979 
8980   // AltiVec-style "vector bool op vector bool" combinations are allowed
8981   // for some operators but not others.
8982   if (!AllowBothBool &&
8983       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8984       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8985     return InvalidOperands(Loc, LHS, RHS);
8986 
8987   // If the vector types are identical, return.
8988   if (Context.hasSameType(LHSType, RHSType))
8989     return LHSType;
8990 
8991   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8992   if (LHSVecType && RHSVecType &&
8993       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8994     if (isa<ExtVectorType>(LHSVecType)) {
8995       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8996       return LHSType;
8997     }
8998 
8999     if (!IsCompAssign)
9000       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9001     return RHSType;
9002   }
9003 
9004   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9005   // can be mixed, with the result being the non-bool type.  The non-bool
9006   // operand must have integer element type.
9007   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9008       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9009       (Context.getTypeSize(LHSVecType->getElementType()) ==
9010        Context.getTypeSize(RHSVecType->getElementType()))) {
9011     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9012         LHSVecType->getElementType()->isIntegerType() &&
9013         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9014       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9015       return LHSType;
9016     }
9017     if (!IsCompAssign &&
9018         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9019         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9020         RHSVecType->getElementType()->isIntegerType()) {
9021       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9022       return RHSType;
9023     }
9024   }
9025 
9026   // If there's a vector type and a scalar, try to convert the scalar to
9027   // the vector element type and splat.
9028   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9029   if (!RHSVecType) {
9030     if (isa<ExtVectorType>(LHSVecType)) {
9031       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9032                                     LHSVecType->getElementType(), LHSType,
9033                                     DiagID))
9034         return LHSType;
9035     } else {
9036       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9037         return LHSType;
9038     }
9039   }
9040   if (!LHSVecType) {
9041     if (isa<ExtVectorType>(RHSVecType)) {
9042       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9043                                     LHSType, RHSVecType->getElementType(),
9044                                     RHSType, DiagID))
9045         return RHSType;
9046     } else {
9047       if (LHS.get()->getValueKind() == VK_LValue ||
9048           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9049         return RHSType;
9050     }
9051   }
9052 
9053   // FIXME: The code below also handles conversion between vectors and
9054   // non-scalars, we should break this down into fine grained specific checks
9055   // and emit proper diagnostics.
9056   QualType VecType = LHSVecType ? LHSType : RHSType;
9057   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9058   QualType OtherType = LHSVecType ? RHSType : LHSType;
9059   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9060   if (isLaxVectorConversion(OtherType, VecType)) {
9061     // If we're allowing lax vector conversions, only the total (data) size
9062     // needs to be the same. For non compound assignment, if one of the types is
9063     // scalar, the result is always the vector type.
9064     if (!IsCompAssign) {
9065       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9066       return VecType;
9067     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9068     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9069     // type. Note that this is already done by non-compound assignments in
9070     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9071     // <1 x T> -> T. The result is also a vector type.
9072     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9073                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9074       ExprResult *RHSExpr = &RHS;
9075       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9076       return VecType;
9077     }
9078   }
9079 
9080   // Okay, the expression is invalid.
9081 
9082   // If there's a non-vector, non-real operand, diagnose that.
9083   if ((!RHSVecType && !RHSType->isRealType()) ||
9084       (!LHSVecType && !LHSType->isRealType())) {
9085     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9086       << LHSType << RHSType
9087       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9088     return QualType();
9089   }
9090 
9091   // OpenCL V1.1 6.2.6.p1:
9092   // If the operands are of more than one vector type, then an error shall
9093   // occur. Implicit conversions between vector types are not permitted, per
9094   // section 6.2.1.
9095   if (getLangOpts().OpenCL &&
9096       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9097       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9098     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9099                                                            << RHSType;
9100     return QualType();
9101   }
9102 
9103 
9104   // If there is a vector type that is not a ExtVector and a scalar, we reach
9105   // this point if scalar could not be converted to the vector's element type
9106   // without truncation.
9107   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9108       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9109     QualType Scalar = LHSVecType ? RHSType : LHSType;
9110     QualType Vector = LHSVecType ? LHSType : RHSType;
9111     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9112     Diag(Loc,
9113          diag::err_typecheck_vector_not_convertable_implict_truncation)
9114         << ScalarOrVector << Scalar << Vector;
9115 
9116     return QualType();
9117   }
9118 
9119   // Otherwise, use the generic diagnostic.
9120   Diag(Loc, DiagID)
9121     << LHSType << RHSType
9122     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9123   return QualType();
9124 }
9125 
9126 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9127 // expression.  These are mainly cases where the null pointer is used as an
9128 // integer instead of a pointer.
9129 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9130                                 SourceLocation Loc, bool IsCompare) {
9131   // The canonical way to check for a GNU null is with isNullPointerConstant,
9132   // but we use a bit of a hack here for speed; this is a relatively
9133   // hot path, and isNullPointerConstant is slow.
9134   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9135   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9136 
9137   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9138 
9139   // Avoid analyzing cases where the result will either be invalid (and
9140   // diagnosed as such) or entirely valid and not something to warn about.
9141   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9142       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9143     return;
9144 
9145   // Comparison operations would not make sense with a null pointer no matter
9146   // what the other expression is.
9147   if (!IsCompare) {
9148     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9149         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9150         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9151     return;
9152   }
9153 
9154   // The rest of the operations only make sense with a null pointer
9155   // if the other expression is a pointer.
9156   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9157       NonNullType->canDecayToPointerType())
9158     return;
9159 
9160   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9161       << LHSNull /* LHS is NULL */ << NonNullType
9162       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9163 }
9164 
9165 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9166                                           SourceLocation Loc) {
9167   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9168   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9169   if (!LUE || !RUE)
9170     return;
9171   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9172       RUE->getKind() != UETT_SizeOf)
9173     return;
9174 
9175   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9176   QualType LHSTy = LHSArg->getType();
9177   QualType RHSTy;
9178 
9179   if (RUE->isArgumentType())
9180     RHSTy = RUE->getArgumentType();
9181   else
9182     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9183 
9184   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9185     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9186       return;
9187 
9188     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9189     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9190       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9191         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9192             << LHSArgDecl;
9193     }
9194   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9195     QualType ArrayElemTy = ArrayTy->getElementType();
9196     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9197         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9198         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9199       return;
9200     S.Diag(Loc, diag::warn_division_sizeof_array)
9201         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9202     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9203       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9204         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9205             << LHSArgDecl;
9206     }
9207 
9208     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9209   }
9210 }
9211 
9212 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9213                                                ExprResult &RHS,
9214                                                SourceLocation Loc, bool IsDiv) {
9215   // Check for division/remainder by zero.
9216   Expr::EvalResult RHSValue;
9217   if (!RHS.get()->isValueDependent() &&
9218       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9219       RHSValue.Val.getInt() == 0)
9220     S.DiagRuntimeBehavior(Loc, RHS.get(),
9221                           S.PDiag(diag::warn_remainder_division_by_zero)
9222                             << IsDiv << RHS.get()->getSourceRange());
9223 }
9224 
9225 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9226                                            SourceLocation Loc,
9227                                            bool IsCompAssign, bool IsDiv) {
9228   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9229 
9230   if (LHS.get()->getType()->isVectorType() ||
9231       RHS.get()->getType()->isVectorType())
9232     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9233                                /*AllowBothBool*/getLangOpts().AltiVec,
9234                                /*AllowBoolConversions*/false);
9235 
9236   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9237   if (LHS.isInvalid() || RHS.isInvalid())
9238     return QualType();
9239 
9240 
9241   if (compType.isNull() || !compType->isArithmeticType())
9242     return InvalidOperands(Loc, LHS, RHS);
9243   if (IsDiv) {
9244     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9245     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9246   }
9247   return compType;
9248 }
9249 
9250 QualType Sema::CheckRemainderOperands(
9251   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9252   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9253 
9254   if (LHS.get()->getType()->isVectorType() ||
9255       RHS.get()->getType()->isVectorType()) {
9256     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9257         RHS.get()->getType()->hasIntegerRepresentation())
9258       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9259                                  /*AllowBothBool*/getLangOpts().AltiVec,
9260                                  /*AllowBoolConversions*/false);
9261     return InvalidOperands(Loc, LHS, RHS);
9262   }
9263 
9264   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9265   if (LHS.isInvalid() || RHS.isInvalid())
9266     return QualType();
9267 
9268   if (compType.isNull() || !compType->isIntegerType())
9269     return InvalidOperands(Loc, LHS, RHS);
9270   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9271   return compType;
9272 }
9273 
9274 /// Diagnose invalid arithmetic on two void pointers.
9275 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9276                                                 Expr *LHSExpr, Expr *RHSExpr) {
9277   S.Diag(Loc, S.getLangOpts().CPlusPlus
9278                 ? diag::err_typecheck_pointer_arith_void_type
9279                 : diag::ext_gnu_void_ptr)
9280     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9281                             << RHSExpr->getSourceRange();
9282 }
9283 
9284 /// Diagnose invalid arithmetic on a void pointer.
9285 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9286                                             Expr *Pointer) {
9287   S.Diag(Loc, S.getLangOpts().CPlusPlus
9288                 ? diag::err_typecheck_pointer_arith_void_type
9289                 : diag::ext_gnu_void_ptr)
9290     << 0 /* one pointer */ << Pointer->getSourceRange();
9291 }
9292 
9293 /// Diagnose invalid arithmetic on a null pointer.
9294 ///
9295 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9296 /// idiom, which we recognize as a GNU extension.
9297 ///
9298 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9299                                             Expr *Pointer, bool IsGNUIdiom) {
9300   if (IsGNUIdiom)
9301     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9302       << Pointer->getSourceRange();
9303   else
9304     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9305       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9306 }
9307 
9308 /// Diagnose invalid arithmetic on two function pointers.
9309 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9310                                                     Expr *LHS, Expr *RHS) {
9311   assert(LHS->getType()->isAnyPointerType());
9312   assert(RHS->getType()->isAnyPointerType());
9313   S.Diag(Loc, S.getLangOpts().CPlusPlus
9314                 ? diag::err_typecheck_pointer_arith_function_type
9315                 : diag::ext_gnu_ptr_func_arith)
9316     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9317     // We only show the second type if it differs from the first.
9318     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9319                                                    RHS->getType())
9320     << RHS->getType()->getPointeeType()
9321     << LHS->getSourceRange() << RHS->getSourceRange();
9322 }
9323 
9324 /// Diagnose invalid arithmetic on a function pointer.
9325 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9326                                                 Expr *Pointer) {
9327   assert(Pointer->getType()->isAnyPointerType());
9328   S.Diag(Loc, S.getLangOpts().CPlusPlus
9329                 ? diag::err_typecheck_pointer_arith_function_type
9330                 : diag::ext_gnu_ptr_func_arith)
9331     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9332     << 0 /* one pointer, so only one type */
9333     << Pointer->getSourceRange();
9334 }
9335 
9336 /// Emit error if Operand is incomplete pointer type
9337 ///
9338 /// \returns True if pointer has incomplete type
9339 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9340                                                  Expr *Operand) {
9341   QualType ResType = Operand->getType();
9342   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9343     ResType = ResAtomicType->getValueType();
9344 
9345   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9346   QualType PointeeTy = ResType->getPointeeType();
9347   return S.RequireCompleteType(Loc, PointeeTy,
9348                                diag::err_typecheck_arithmetic_incomplete_type,
9349                                PointeeTy, Operand->getSourceRange());
9350 }
9351 
9352 /// Check the validity of an arithmetic pointer operand.
9353 ///
9354 /// If the operand has pointer type, this code will check for pointer types
9355 /// which are invalid in arithmetic operations. These will be diagnosed
9356 /// appropriately, including whether or not the use is supported as an
9357 /// extension.
9358 ///
9359 /// \returns True when the operand is valid to use (even if as an extension).
9360 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9361                                             Expr *Operand) {
9362   QualType ResType = Operand->getType();
9363   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9364     ResType = ResAtomicType->getValueType();
9365 
9366   if (!ResType->isAnyPointerType()) return true;
9367 
9368   QualType PointeeTy = ResType->getPointeeType();
9369   if (PointeeTy->isVoidType()) {
9370     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9371     return !S.getLangOpts().CPlusPlus;
9372   }
9373   if (PointeeTy->isFunctionType()) {
9374     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9375     return !S.getLangOpts().CPlusPlus;
9376   }
9377 
9378   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9379 
9380   return true;
9381 }
9382 
9383 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9384 /// operands.
9385 ///
9386 /// This routine will diagnose any invalid arithmetic on pointer operands much
9387 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9388 /// for emitting a single diagnostic even for operations where both LHS and RHS
9389 /// are (potentially problematic) pointers.
9390 ///
9391 /// \returns True when the operand is valid to use (even if as an extension).
9392 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9393                                                 Expr *LHSExpr, Expr *RHSExpr) {
9394   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9395   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9396   if (!isLHSPointer && !isRHSPointer) return true;
9397 
9398   QualType LHSPointeeTy, RHSPointeeTy;
9399   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9400   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9401 
9402   // if both are pointers check if operation is valid wrt address spaces
9403   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9404     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9405     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9406     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9407       S.Diag(Loc,
9408              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9409           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9410           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9411       return false;
9412     }
9413   }
9414 
9415   // Check for arithmetic on pointers to incomplete types.
9416   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9417   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9418   if (isLHSVoidPtr || isRHSVoidPtr) {
9419     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9420     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9421     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9422 
9423     return !S.getLangOpts().CPlusPlus;
9424   }
9425 
9426   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9427   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9428   if (isLHSFuncPtr || isRHSFuncPtr) {
9429     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9430     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9431                                                                 RHSExpr);
9432     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9433 
9434     return !S.getLangOpts().CPlusPlus;
9435   }
9436 
9437   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9438     return false;
9439   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9440     return false;
9441 
9442   return true;
9443 }
9444 
9445 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9446 /// literal.
9447 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9448                                   Expr *LHSExpr, Expr *RHSExpr) {
9449   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9450   Expr* IndexExpr = RHSExpr;
9451   if (!StrExpr) {
9452     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9453     IndexExpr = LHSExpr;
9454   }
9455 
9456   bool IsStringPlusInt = StrExpr &&
9457       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9458   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9459     return;
9460 
9461   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9462   Self.Diag(OpLoc, diag::warn_string_plus_int)
9463       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9464 
9465   // Only print a fixit for "str" + int, not for int + "str".
9466   if (IndexExpr == RHSExpr) {
9467     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9468     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9469         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9470         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9471         << FixItHint::CreateInsertion(EndLoc, "]");
9472   } else
9473     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9474 }
9475 
9476 /// Emit a warning when adding a char literal to a string.
9477 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9478                                    Expr *LHSExpr, Expr *RHSExpr) {
9479   const Expr *StringRefExpr = LHSExpr;
9480   const CharacterLiteral *CharExpr =
9481       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9482 
9483   if (!CharExpr) {
9484     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9485     StringRefExpr = RHSExpr;
9486   }
9487 
9488   if (!CharExpr || !StringRefExpr)
9489     return;
9490 
9491   const QualType StringType = StringRefExpr->getType();
9492 
9493   // Return if not a PointerType.
9494   if (!StringType->isAnyPointerType())
9495     return;
9496 
9497   // Return if not a CharacterType.
9498   if (!StringType->getPointeeType()->isAnyCharacterType())
9499     return;
9500 
9501   ASTContext &Ctx = Self.getASTContext();
9502   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9503 
9504   const QualType CharType = CharExpr->getType();
9505   if (!CharType->isAnyCharacterType() &&
9506       CharType->isIntegerType() &&
9507       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9508     Self.Diag(OpLoc, diag::warn_string_plus_char)
9509         << DiagRange << Ctx.CharTy;
9510   } else {
9511     Self.Diag(OpLoc, diag::warn_string_plus_char)
9512         << DiagRange << CharExpr->getType();
9513   }
9514 
9515   // Only print a fixit for str + char, not for char + str.
9516   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9517     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9518     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9519         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9520         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9521         << FixItHint::CreateInsertion(EndLoc, "]");
9522   } else {
9523     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9524   }
9525 }
9526 
9527 /// Emit error when two pointers are incompatible.
9528 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9529                                            Expr *LHSExpr, Expr *RHSExpr) {
9530   assert(LHSExpr->getType()->isAnyPointerType());
9531   assert(RHSExpr->getType()->isAnyPointerType());
9532   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9533     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9534     << RHSExpr->getSourceRange();
9535 }
9536 
9537 // C99 6.5.6
9538 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9539                                      SourceLocation Loc, BinaryOperatorKind Opc,
9540                                      QualType* CompLHSTy) {
9541   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9542 
9543   if (LHS.get()->getType()->isVectorType() ||
9544       RHS.get()->getType()->isVectorType()) {
9545     QualType compType = CheckVectorOperands(
9546         LHS, RHS, Loc, CompLHSTy,
9547         /*AllowBothBool*/getLangOpts().AltiVec,
9548         /*AllowBoolConversions*/getLangOpts().ZVector);
9549     if (CompLHSTy) *CompLHSTy = compType;
9550     return compType;
9551   }
9552 
9553   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9554   if (LHS.isInvalid() || RHS.isInvalid())
9555     return QualType();
9556 
9557   // Diagnose "string literal" '+' int and string '+' "char literal".
9558   if (Opc == BO_Add) {
9559     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9560     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9561   }
9562 
9563   // handle the common case first (both operands are arithmetic).
9564   if (!compType.isNull() && compType->isArithmeticType()) {
9565     if (CompLHSTy) *CompLHSTy = compType;
9566     return compType;
9567   }
9568 
9569   // Type-checking.  Ultimately the pointer's going to be in PExp;
9570   // note that we bias towards the LHS being the pointer.
9571   Expr *PExp = LHS.get(), *IExp = RHS.get();
9572 
9573   bool isObjCPointer;
9574   if (PExp->getType()->isPointerType()) {
9575     isObjCPointer = false;
9576   } else if (PExp->getType()->isObjCObjectPointerType()) {
9577     isObjCPointer = true;
9578   } else {
9579     std::swap(PExp, IExp);
9580     if (PExp->getType()->isPointerType()) {
9581       isObjCPointer = false;
9582     } else if (PExp->getType()->isObjCObjectPointerType()) {
9583       isObjCPointer = true;
9584     } else {
9585       return InvalidOperands(Loc, LHS, RHS);
9586     }
9587   }
9588   assert(PExp->getType()->isAnyPointerType());
9589 
9590   if (!IExp->getType()->isIntegerType())
9591     return InvalidOperands(Loc, LHS, RHS);
9592 
9593   // Adding to a null pointer results in undefined behavior.
9594   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9595           Context, Expr::NPC_ValueDependentIsNotNull)) {
9596     // In C++ adding zero to a null pointer is defined.
9597     Expr::EvalResult KnownVal;
9598     if (!getLangOpts().CPlusPlus ||
9599         (!IExp->isValueDependent() &&
9600          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9601           KnownVal.Val.getInt() != 0))) {
9602       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9603       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9604           Context, BO_Add, PExp, IExp);
9605       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9606     }
9607   }
9608 
9609   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9610     return QualType();
9611 
9612   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9613     return QualType();
9614 
9615   // Check array bounds for pointer arithemtic
9616   CheckArrayAccess(PExp, IExp);
9617 
9618   if (CompLHSTy) {
9619     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9620     if (LHSTy.isNull()) {
9621       LHSTy = LHS.get()->getType();
9622       if (LHSTy->isPromotableIntegerType())
9623         LHSTy = Context.getPromotedIntegerType(LHSTy);
9624     }
9625     *CompLHSTy = LHSTy;
9626   }
9627 
9628   return PExp->getType();
9629 }
9630 
9631 // C99 6.5.6
9632 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9633                                         SourceLocation Loc,
9634                                         QualType* CompLHSTy) {
9635   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9636 
9637   if (LHS.get()->getType()->isVectorType() ||
9638       RHS.get()->getType()->isVectorType()) {
9639     QualType compType = CheckVectorOperands(
9640         LHS, RHS, Loc, CompLHSTy,
9641         /*AllowBothBool*/getLangOpts().AltiVec,
9642         /*AllowBoolConversions*/getLangOpts().ZVector);
9643     if (CompLHSTy) *CompLHSTy = compType;
9644     return compType;
9645   }
9646 
9647   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9648   if (LHS.isInvalid() || RHS.isInvalid())
9649     return QualType();
9650 
9651   // Enforce type constraints: C99 6.5.6p3.
9652 
9653   // Handle the common case first (both operands are arithmetic).
9654   if (!compType.isNull() && compType->isArithmeticType()) {
9655     if (CompLHSTy) *CompLHSTy = compType;
9656     return compType;
9657   }
9658 
9659   // Either ptr - int   or   ptr - ptr.
9660   if (LHS.get()->getType()->isAnyPointerType()) {
9661     QualType lpointee = LHS.get()->getType()->getPointeeType();
9662 
9663     // Diagnose bad cases where we step over interface counts.
9664     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9665         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9666       return QualType();
9667 
9668     // The result type of a pointer-int computation is the pointer type.
9669     if (RHS.get()->getType()->isIntegerType()) {
9670       // Subtracting from a null pointer should produce a warning.
9671       // The last argument to the diagnose call says this doesn't match the
9672       // GNU int-to-pointer idiom.
9673       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9674                                            Expr::NPC_ValueDependentIsNotNull)) {
9675         // In C++ adding zero to a null pointer is defined.
9676         Expr::EvalResult KnownVal;
9677         if (!getLangOpts().CPlusPlus ||
9678             (!RHS.get()->isValueDependent() &&
9679              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9680               KnownVal.Val.getInt() != 0))) {
9681           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9682         }
9683       }
9684 
9685       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9686         return QualType();
9687 
9688       // Check array bounds for pointer arithemtic
9689       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9690                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9691 
9692       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9693       return LHS.get()->getType();
9694     }
9695 
9696     // Handle pointer-pointer subtractions.
9697     if (const PointerType *RHSPTy
9698           = RHS.get()->getType()->getAs<PointerType>()) {
9699       QualType rpointee = RHSPTy->getPointeeType();
9700 
9701       if (getLangOpts().CPlusPlus) {
9702         // Pointee types must be the same: C++ [expr.add]
9703         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9704           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9705         }
9706       } else {
9707         // Pointee types must be compatible C99 6.5.6p3
9708         if (!Context.typesAreCompatible(
9709                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9710                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9711           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9712           return QualType();
9713         }
9714       }
9715 
9716       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9717                                                LHS.get(), RHS.get()))
9718         return QualType();
9719 
9720       // FIXME: Add warnings for nullptr - ptr.
9721 
9722       // The pointee type may have zero size.  As an extension, a structure or
9723       // union may have zero size or an array may have zero length.  In this
9724       // case subtraction does not make sense.
9725       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9726         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9727         if (ElementSize.isZero()) {
9728           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9729             << rpointee.getUnqualifiedType()
9730             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9731         }
9732       }
9733 
9734       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9735       return Context.getPointerDiffType();
9736     }
9737   }
9738 
9739   return InvalidOperands(Loc, LHS, RHS);
9740 }
9741 
9742 static bool isScopedEnumerationType(QualType T) {
9743   if (const EnumType *ET = T->getAs<EnumType>())
9744     return ET->getDecl()->isScoped();
9745   return false;
9746 }
9747 
9748 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9749                                    SourceLocation Loc, BinaryOperatorKind Opc,
9750                                    QualType LHSType) {
9751   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9752   // so skip remaining warnings as we don't want to modify values within Sema.
9753   if (S.getLangOpts().OpenCL)
9754     return;
9755 
9756   // Check right/shifter operand
9757   Expr::EvalResult RHSResult;
9758   if (RHS.get()->isValueDependent() ||
9759       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9760     return;
9761   llvm::APSInt Right = RHSResult.Val.getInt();
9762 
9763   if (Right.isNegative()) {
9764     S.DiagRuntimeBehavior(Loc, RHS.get(),
9765                           S.PDiag(diag::warn_shift_negative)
9766                             << RHS.get()->getSourceRange());
9767     return;
9768   }
9769   llvm::APInt LeftBits(Right.getBitWidth(),
9770                        S.Context.getTypeSize(LHS.get()->getType()));
9771   if (Right.uge(LeftBits)) {
9772     S.DiagRuntimeBehavior(Loc, RHS.get(),
9773                           S.PDiag(diag::warn_shift_gt_typewidth)
9774                             << RHS.get()->getSourceRange());
9775     return;
9776   }
9777   if (Opc != BO_Shl)
9778     return;
9779 
9780   // When left shifting an ICE which is signed, we can check for overflow which
9781   // according to C++ standards prior to C++2a has undefined behavior
9782   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9783   // more than the maximum value representable in the result type, so never
9784   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9785   // expression is still probably a bug.)
9786   Expr::EvalResult LHSResult;
9787   if (LHS.get()->isValueDependent() ||
9788       LHSType->hasUnsignedIntegerRepresentation() ||
9789       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9790     return;
9791   llvm::APSInt Left = LHSResult.Val.getInt();
9792 
9793   // If LHS does not have a signed type and non-negative value
9794   // then, the behavior is undefined before C++2a. Warn about it.
9795   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9796       !S.getLangOpts().CPlusPlus2a) {
9797     S.DiagRuntimeBehavior(Loc, LHS.get(),
9798                           S.PDiag(diag::warn_shift_lhs_negative)
9799                             << LHS.get()->getSourceRange());
9800     return;
9801   }
9802 
9803   llvm::APInt ResultBits =
9804       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9805   if (LeftBits.uge(ResultBits))
9806     return;
9807   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9808   Result = Result.shl(Right);
9809 
9810   // Print the bit representation of the signed integer as an unsigned
9811   // hexadecimal number.
9812   SmallString<40> HexResult;
9813   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9814 
9815   // If we are only missing a sign bit, this is less likely to result in actual
9816   // bugs -- if the result is cast back to an unsigned type, it will have the
9817   // expected value. Thus we place this behind a different warning that can be
9818   // turned off separately if needed.
9819   if (LeftBits == ResultBits - 1) {
9820     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9821         << HexResult << LHSType
9822         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9823     return;
9824   }
9825 
9826   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9827     << HexResult.str() << Result.getMinSignedBits() << LHSType
9828     << Left.getBitWidth() << LHS.get()->getSourceRange()
9829     << RHS.get()->getSourceRange();
9830 }
9831 
9832 /// Return the resulting type when a vector is shifted
9833 ///        by a scalar or vector shift amount.
9834 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9835                                  SourceLocation Loc, bool IsCompAssign) {
9836   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9837   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9838       !LHS.get()->getType()->isVectorType()) {
9839     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9840       << RHS.get()->getType() << LHS.get()->getType()
9841       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9842     return QualType();
9843   }
9844 
9845   if (!IsCompAssign) {
9846     LHS = S.UsualUnaryConversions(LHS.get());
9847     if (LHS.isInvalid()) return QualType();
9848   }
9849 
9850   RHS = S.UsualUnaryConversions(RHS.get());
9851   if (RHS.isInvalid()) return QualType();
9852 
9853   QualType LHSType = LHS.get()->getType();
9854   // Note that LHS might be a scalar because the routine calls not only in
9855   // OpenCL case.
9856   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9857   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9858 
9859   // Note that RHS might not be a vector.
9860   QualType RHSType = RHS.get()->getType();
9861   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9862   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9863 
9864   // The operands need to be integers.
9865   if (!LHSEleType->isIntegerType()) {
9866     S.Diag(Loc, diag::err_typecheck_expect_int)
9867       << LHS.get()->getType() << LHS.get()->getSourceRange();
9868     return QualType();
9869   }
9870 
9871   if (!RHSEleType->isIntegerType()) {
9872     S.Diag(Loc, diag::err_typecheck_expect_int)
9873       << RHS.get()->getType() << RHS.get()->getSourceRange();
9874     return QualType();
9875   }
9876 
9877   if (!LHSVecTy) {
9878     assert(RHSVecTy);
9879     if (IsCompAssign)
9880       return RHSType;
9881     if (LHSEleType != RHSEleType) {
9882       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9883       LHSEleType = RHSEleType;
9884     }
9885     QualType VecTy =
9886         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9887     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9888     LHSType = VecTy;
9889   } else if (RHSVecTy) {
9890     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9891     // are applied component-wise. So if RHS is a vector, then ensure
9892     // that the number of elements is the same as LHS...
9893     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9894       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9895         << LHS.get()->getType() << RHS.get()->getType()
9896         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9897       return QualType();
9898     }
9899     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9900       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9901       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9902       if (LHSBT != RHSBT &&
9903           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9904         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9905             << LHS.get()->getType() << RHS.get()->getType()
9906             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9907       }
9908     }
9909   } else {
9910     // ...else expand RHS to match the number of elements in LHS.
9911     QualType VecTy =
9912       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9913     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9914   }
9915 
9916   return LHSType;
9917 }
9918 
9919 // C99 6.5.7
9920 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9921                                   SourceLocation Loc, BinaryOperatorKind Opc,
9922                                   bool IsCompAssign) {
9923   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9924 
9925   // Vector shifts promote their scalar inputs to vector type.
9926   if (LHS.get()->getType()->isVectorType() ||
9927       RHS.get()->getType()->isVectorType()) {
9928     if (LangOpts.ZVector) {
9929       // The shift operators for the z vector extensions work basically
9930       // like general shifts, except that neither the LHS nor the RHS is
9931       // allowed to be a "vector bool".
9932       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9933         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9934           return InvalidOperands(Loc, LHS, RHS);
9935       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9936         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9937           return InvalidOperands(Loc, LHS, RHS);
9938     }
9939     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9940   }
9941 
9942   // Shifts don't perform usual arithmetic conversions, they just do integer
9943   // promotions on each operand. C99 6.5.7p3
9944 
9945   // For the LHS, do usual unary conversions, but then reset them away
9946   // if this is a compound assignment.
9947   ExprResult OldLHS = LHS;
9948   LHS = UsualUnaryConversions(LHS.get());
9949   if (LHS.isInvalid())
9950     return QualType();
9951   QualType LHSType = LHS.get()->getType();
9952   if (IsCompAssign) LHS = OldLHS;
9953 
9954   // The RHS is simpler.
9955   RHS = UsualUnaryConversions(RHS.get());
9956   if (RHS.isInvalid())
9957     return QualType();
9958   QualType RHSType = RHS.get()->getType();
9959 
9960   // C99 6.5.7p2: Each of the operands shall have integer type.
9961   if (!LHSType->hasIntegerRepresentation() ||
9962       !RHSType->hasIntegerRepresentation())
9963     return InvalidOperands(Loc, LHS, RHS);
9964 
9965   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9966   // hasIntegerRepresentation() above instead of this.
9967   if (isScopedEnumerationType(LHSType) ||
9968       isScopedEnumerationType(RHSType)) {
9969     return InvalidOperands(Loc, LHS, RHS);
9970   }
9971   // Sanity-check shift operands
9972   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9973 
9974   // "The type of the result is that of the promoted left operand."
9975   return LHSType;
9976 }
9977 
9978 /// If two different enums are compared, raise a warning.
9979 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9980                                 Expr *RHS) {
9981   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9982   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9983 
9984   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9985   if (!LHSEnumType)
9986     return;
9987   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9988   if (!RHSEnumType)
9989     return;
9990 
9991   // Ignore anonymous enums.
9992   if (!LHSEnumType->getDecl()->getIdentifier() &&
9993       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9994     return;
9995   if (!RHSEnumType->getDecl()->getIdentifier() &&
9996       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9997     return;
9998 
9999   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
10000     return;
10001 
10002   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
10003       << LHSStrippedType << RHSStrippedType
10004       << LHS->getSourceRange() << RHS->getSourceRange();
10005 }
10006 
10007 /// Diagnose bad pointer comparisons.
10008 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10009                                               ExprResult &LHS, ExprResult &RHS,
10010                                               bool IsError) {
10011   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10012                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10013     << LHS.get()->getType() << RHS.get()->getType()
10014     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10015 }
10016 
10017 /// Returns false if the pointers are converted to a composite type,
10018 /// true otherwise.
10019 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10020                                            ExprResult &LHS, ExprResult &RHS) {
10021   // C++ [expr.rel]p2:
10022   //   [...] Pointer conversions (4.10) and qualification
10023   //   conversions (4.4) are performed on pointer operands (or on
10024   //   a pointer operand and a null pointer constant) to bring
10025   //   them to their composite pointer type. [...]
10026   //
10027   // C++ [expr.eq]p1 uses the same notion for (in)equality
10028   // comparisons of pointers.
10029 
10030   QualType LHSType = LHS.get()->getType();
10031   QualType RHSType = RHS.get()->getType();
10032   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10033          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10034 
10035   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10036   if (T.isNull()) {
10037     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
10038         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
10039       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10040     else
10041       S.InvalidOperands(Loc, LHS, RHS);
10042     return true;
10043   }
10044 
10045   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
10046   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
10047   return false;
10048 }
10049 
10050 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10051                                                     ExprResult &LHS,
10052                                                     ExprResult &RHS,
10053                                                     bool IsError) {
10054   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10055                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10056     << LHS.get()->getType() << RHS.get()->getType()
10057     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10058 }
10059 
10060 static bool isObjCObjectLiteral(ExprResult &E) {
10061   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10062   case Stmt::ObjCArrayLiteralClass:
10063   case Stmt::ObjCDictionaryLiteralClass:
10064   case Stmt::ObjCStringLiteralClass:
10065   case Stmt::ObjCBoxedExprClass:
10066     return true;
10067   default:
10068     // Note that ObjCBoolLiteral is NOT an object literal!
10069     return false;
10070   }
10071 }
10072 
10073 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10074   const ObjCObjectPointerType *Type =
10075     LHS->getType()->getAs<ObjCObjectPointerType>();
10076 
10077   // If this is not actually an Objective-C object, bail out.
10078   if (!Type)
10079     return false;
10080 
10081   // Get the LHS object's interface type.
10082   QualType InterfaceType = Type->getPointeeType();
10083 
10084   // If the RHS isn't an Objective-C object, bail out.
10085   if (!RHS->getType()->isObjCObjectPointerType())
10086     return false;
10087 
10088   // Try to find the -isEqual: method.
10089   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10090   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10091                                                       InterfaceType,
10092                                                       /*IsInstance=*/true);
10093   if (!Method) {
10094     if (Type->isObjCIdType()) {
10095       // For 'id', just check the global pool.
10096       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10097                                                   /*receiverId=*/true);
10098     } else {
10099       // Check protocols.
10100       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10101                                              /*IsInstance=*/true);
10102     }
10103   }
10104 
10105   if (!Method)
10106     return false;
10107 
10108   QualType T = Method->parameters()[0]->getType();
10109   if (!T->isObjCObjectPointerType())
10110     return false;
10111 
10112   QualType R = Method->getReturnType();
10113   if (!R->isScalarType())
10114     return false;
10115 
10116   return true;
10117 }
10118 
10119 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10120   FromE = FromE->IgnoreParenImpCasts();
10121   switch (FromE->getStmtClass()) {
10122     default:
10123       break;
10124     case Stmt::ObjCStringLiteralClass:
10125       // "string literal"
10126       return LK_String;
10127     case Stmt::ObjCArrayLiteralClass:
10128       // "array literal"
10129       return LK_Array;
10130     case Stmt::ObjCDictionaryLiteralClass:
10131       // "dictionary literal"
10132       return LK_Dictionary;
10133     case Stmt::BlockExprClass:
10134       return LK_Block;
10135     case Stmt::ObjCBoxedExprClass: {
10136       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10137       switch (Inner->getStmtClass()) {
10138         case Stmt::IntegerLiteralClass:
10139         case Stmt::FloatingLiteralClass:
10140         case Stmt::CharacterLiteralClass:
10141         case Stmt::ObjCBoolLiteralExprClass:
10142         case Stmt::CXXBoolLiteralExprClass:
10143           // "numeric literal"
10144           return LK_Numeric;
10145         case Stmt::ImplicitCastExprClass: {
10146           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10147           // Boolean literals can be represented by implicit casts.
10148           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10149             return LK_Numeric;
10150           break;
10151         }
10152         default:
10153           break;
10154       }
10155       return LK_Boxed;
10156     }
10157   }
10158   return LK_None;
10159 }
10160 
10161 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10162                                           ExprResult &LHS, ExprResult &RHS,
10163                                           BinaryOperator::Opcode Opc){
10164   Expr *Literal;
10165   Expr *Other;
10166   if (isObjCObjectLiteral(LHS)) {
10167     Literal = LHS.get();
10168     Other = RHS.get();
10169   } else {
10170     Literal = RHS.get();
10171     Other = LHS.get();
10172   }
10173 
10174   // Don't warn on comparisons against nil.
10175   Other = Other->IgnoreParenCasts();
10176   if (Other->isNullPointerConstant(S.getASTContext(),
10177                                    Expr::NPC_ValueDependentIsNotNull))
10178     return;
10179 
10180   // This should be kept in sync with warn_objc_literal_comparison.
10181   // LK_String should always be after the other literals, since it has its own
10182   // warning flag.
10183   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10184   assert(LiteralKind != Sema::LK_Block);
10185   if (LiteralKind == Sema::LK_None) {
10186     llvm_unreachable("Unknown Objective-C object literal kind");
10187   }
10188 
10189   if (LiteralKind == Sema::LK_String)
10190     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10191       << Literal->getSourceRange();
10192   else
10193     S.Diag(Loc, diag::warn_objc_literal_comparison)
10194       << LiteralKind << Literal->getSourceRange();
10195 
10196   if (BinaryOperator::isEqualityOp(Opc) &&
10197       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10198     SourceLocation Start = LHS.get()->getBeginLoc();
10199     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10200     CharSourceRange OpRange =
10201       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10202 
10203     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10204       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10205       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10206       << FixItHint::CreateInsertion(End, "]");
10207   }
10208 }
10209 
10210 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10211 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10212                                            ExprResult &RHS, SourceLocation Loc,
10213                                            BinaryOperatorKind Opc) {
10214   // Check that left hand side is !something.
10215   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10216   if (!UO || UO->getOpcode() != UO_LNot) return;
10217 
10218   // Only check if the right hand side is non-bool arithmetic type.
10219   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10220 
10221   // Make sure that the something in !something is not bool.
10222   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10223   if (SubExpr->isKnownToHaveBooleanValue()) return;
10224 
10225   // Emit warning.
10226   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10227   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10228       << Loc << IsBitwiseOp;
10229 
10230   // First note suggest !(x < y)
10231   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10232   SourceLocation FirstClose = RHS.get()->getEndLoc();
10233   FirstClose = S.getLocForEndOfToken(FirstClose);
10234   if (FirstClose.isInvalid())
10235     FirstOpen = SourceLocation();
10236   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10237       << IsBitwiseOp
10238       << FixItHint::CreateInsertion(FirstOpen, "(")
10239       << FixItHint::CreateInsertion(FirstClose, ")");
10240 
10241   // Second note suggests (!x) < y
10242   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10243   SourceLocation SecondClose = LHS.get()->getEndLoc();
10244   SecondClose = S.getLocForEndOfToken(SecondClose);
10245   if (SecondClose.isInvalid())
10246     SecondOpen = SourceLocation();
10247   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10248       << FixItHint::CreateInsertion(SecondOpen, "(")
10249       << FixItHint::CreateInsertion(SecondClose, ")");
10250 }
10251 
10252 // Returns true if E refers to a non-weak array.
10253 static bool checkForArray(const Expr *E) {
10254   const ValueDecl *D = nullptr;
10255   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10256     D = DR->getDecl();
10257   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10258     if (Mem->isImplicitAccess())
10259       D = Mem->getMemberDecl();
10260   }
10261   if (!D)
10262     return false;
10263   return D->getType()->isArrayType() && !D->isWeak();
10264 }
10265 
10266 /// Diagnose some forms of syntactically-obvious tautological comparison.
10267 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10268                                            Expr *LHS, Expr *RHS,
10269                                            BinaryOperatorKind Opc) {
10270   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10271   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10272 
10273   QualType LHSType = LHS->getType();
10274   QualType RHSType = RHS->getType();
10275   if (LHSType->hasFloatingRepresentation() ||
10276       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10277       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10278       S.inTemplateInstantiation())
10279     return;
10280 
10281   // Comparisons between two array types are ill-formed for operator<=>, so
10282   // we shouldn't emit any additional warnings about it.
10283   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10284     return;
10285 
10286   // For non-floating point types, check for self-comparisons of the form
10287   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10288   // often indicate logic errors in the program.
10289   //
10290   // NOTE: Don't warn about comparison expressions resulting from macro
10291   // expansion. Also don't warn about comparisons which are only self
10292   // comparisons within a template instantiation. The warnings should catch
10293   // obvious cases in the definition of the template anyways. The idea is to
10294   // warn when the typed comparison operator will always evaluate to the same
10295   // result.
10296 
10297   // Used for indexing into %select in warn_comparison_always
10298   enum {
10299     AlwaysConstant,
10300     AlwaysTrue,
10301     AlwaysFalse,
10302     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10303   };
10304 
10305   if (Expr::isSameComparisonOperand(LHS, RHS)) {
10306     unsigned Result;
10307     switch (Opc) {
10308     case BO_EQ: case BO_LE: case BO_GE:
10309       Result = AlwaysTrue;
10310       break;
10311     case BO_NE: case BO_LT: case BO_GT:
10312       Result = AlwaysFalse;
10313       break;
10314     case BO_Cmp:
10315       Result = AlwaysEqual;
10316       break;
10317     default:
10318       Result = AlwaysConstant;
10319       break;
10320     }
10321     S.DiagRuntimeBehavior(Loc, nullptr,
10322                           S.PDiag(diag::warn_comparison_always)
10323                               << 0 /*self-comparison*/
10324                               << Result);
10325   } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10326     // What is it always going to evaluate to?
10327     unsigned Result;
10328     switch(Opc) {
10329     case BO_EQ: // e.g. array1 == array2
10330       Result = AlwaysFalse;
10331       break;
10332     case BO_NE: // e.g. array1 != array2
10333       Result = AlwaysTrue;
10334       break;
10335     default: // e.g. array1 <= array2
10336       // The best we can say is 'a constant'
10337       Result = AlwaysConstant;
10338       break;
10339     }
10340     S.DiagRuntimeBehavior(Loc, nullptr,
10341                           S.PDiag(diag::warn_comparison_always)
10342                               << 1 /*array comparison*/
10343                               << Result);
10344   }
10345 
10346   if (isa<CastExpr>(LHSStripped))
10347     LHSStripped = LHSStripped->IgnoreParenCasts();
10348   if (isa<CastExpr>(RHSStripped))
10349     RHSStripped = RHSStripped->IgnoreParenCasts();
10350 
10351   // Warn about comparisons against a string constant (unless the other
10352   // operand is null); the user probably wants strcmp.
10353   Expr *LiteralString = nullptr;
10354   Expr *LiteralStringStripped = nullptr;
10355   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10356       !RHSStripped->isNullPointerConstant(S.Context,
10357                                           Expr::NPC_ValueDependentIsNull)) {
10358     LiteralString = LHS;
10359     LiteralStringStripped = LHSStripped;
10360   } else if ((isa<StringLiteral>(RHSStripped) ||
10361               isa<ObjCEncodeExpr>(RHSStripped)) &&
10362              !LHSStripped->isNullPointerConstant(S.Context,
10363                                           Expr::NPC_ValueDependentIsNull)) {
10364     LiteralString = RHS;
10365     LiteralStringStripped = RHSStripped;
10366   }
10367 
10368   if (LiteralString) {
10369     S.DiagRuntimeBehavior(Loc, nullptr,
10370                           S.PDiag(diag::warn_stringcompare)
10371                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10372                               << LiteralString->getSourceRange());
10373   }
10374 }
10375 
10376 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10377   switch (CK) {
10378   default: {
10379 #ifndef NDEBUG
10380     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10381                  << "\n";
10382 #endif
10383     llvm_unreachable("unhandled cast kind");
10384   }
10385   case CK_UserDefinedConversion:
10386     return ICK_Identity;
10387   case CK_LValueToRValue:
10388     return ICK_Lvalue_To_Rvalue;
10389   case CK_ArrayToPointerDecay:
10390     return ICK_Array_To_Pointer;
10391   case CK_FunctionToPointerDecay:
10392     return ICK_Function_To_Pointer;
10393   case CK_IntegralCast:
10394     return ICK_Integral_Conversion;
10395   case CK_FloatingCast:
10396     return ICK_Floating_Conversion;
10397   case CK_IntegralToFloating:
10398   case CK_FloatingToIntegral:
10399     return ICK_Floating_Integral;
10400   case CK_IntegralComplexCast:
10401   case CK_FloatingComplexCast:
10402   case CK_FloatingComplexToIntegralComplex:
10403   case CK_IntegralComplexToFloatingComplex:
10404     return ICK_Complex_Conversion;
10405   case CK_FloatingComplexToReal:
10406   case CK_FloatingRealToComplex:
10407   case CK_IntegralComplexToReal:
10408   case CK_IntegralRealToComplex:
10409     return ICK_Complex_Real;
10410   }
10411 }
10412 
10413 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10414                                              QualType FromType,
10415                                              SourceLocation Loc) {
10416   // Check for a narrowing implicit conversion.
10417   StandardConversionSequence SCS;
10418   SCS.setAsIdentityConversion();
10419   SCS.setToType(0, FromType);
10420   SCS.setToType(1, ToType);
10421   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10422     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10423 
10424   APValue PreNarrowingValue;
10425   QualType PreNarrowingType;
10426   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10427                                PreNarrowingType,
10428                                /*IgnoreFloatToIntegralConversion*/ true)) {
10429   case NK_Dependent_Narrowing:
10430     // Implicit conversion to a narrower type, but the expression is
10431     // value-dependent so we can't tell whether it's actually narrowing.
10432   case NK_Not_Narrowing:
10433     return false;
10434 
10435   case NK_Constant_Narrowing:
10436     // Implicit conversion to a narrower type, and the value is not a constant
10437     // expression.
10438     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10439         << /*Constant*/ 1
10440         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10441     return true;
10442 
10443   case NK_Variable_Narrowing:
10444     // Implicit conversion to a narrower type, and the value is not a constant
10445     // expression.
10446   case NK_Type_Narrowing:
10447     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10448         << /*Constant*/ 0 << FromType << ToType;
10449     // TODO: It's not a constant expression, but what if the user intended it
10450     // to be? Can we produce notes to help them figure out why it isn't?
10451     return true;
10452   }
10453   llvm_unreachable("unhandled case in switch");
10454 }
10455 
10456 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10457                                                          ExprResult &LHS,
10458                                                          ExprResult &RHS,
10459                                                          SourceLocation Loc) {
10460   using CCT = ComparisonCategoryType;
10461 
10462   QualType LHSType = LHS.get()->getType();
10463   QualType RHSType = RHS.get()->getType();
10464   // Dig out the original argument type and expression before implicit casts
10465   // were applied. These are the types/expressions we need to check the
10466   // [expr.spaceship] requirements against.
10467   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10468   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10469   QualType LHSStrippedType = LHSStripped.get()->getType();
10470   QualType RHSStrippedType = RHSStripped.get()->getType();
10471 
10472   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10473   // other is not, the program is ill-formed.
10474   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10475     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10476     return QualType();
10477   }
10478 
10479   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10480                     RHSStrippedType->isEnumeralType();
10481   if (NumEnumArgs == 1) {
10482     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10483     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10484     if (OtherTy->hasFloatingRepresentation()) {
10485       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10486       return QualType();
10487     }
10488   }
10489   if (NumEnumArgs == 2) {
10490     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10491     // type E, the operator yields the result of converting the operands
10492     // to the underlying type of E and applying <=> to the converted operands.
10493     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10494       S.InvalidOperands(Loc, LHS, RHS);
10495       return QualType();
10496     }
10497     QualType IntType =
10498         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10499     assert(IntType->isArithmeticType());
10500 
10501     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10502     // promote the boolean type, and all other promotable integer types, to
10503     // avoid this.
10504     if (IntType->isPromotableIntegerType())
10505       IntType = S.Context.getPromotedIntegerType(IntType);
10506 
10507     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10508     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10509     LHSType = RHSType = IntType;
10510   }
10511 
10512   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10513   // usual arithmetic conversions are applied to the operands.
10514   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10515   if (LHS.isInvalid() || RHS.isInvalid())
10516     return QualType();
10517   if (Type.isNull())
10518     return S.InvalidOperands(Loc, LHS, RHS);
10519   assert(Type->isArithmeticType() || Type->isEnumeralType());
10520 
10521   bool HasNarrowing = checkThreeWayNarrowingConversion(
10522       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10523   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10524                                                    RHS.get()->getBeginLoc());
10525   if (HasNarrowing)
10526     return QualType();
10527 
10528   assert(!Type.isNull() && "composite type for <=> has not been set");
10529 
10530   auto TypeKind = [&]() {
10531     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10532       if (CT->getElementType()->hasFloatingRepresentation())
10533         return CCT::WeakEquality;
10534       return CCT::StrongEquality;
10535     }
10536     if (Type->isIntegralOrEnumerationType())
10537       return CCT::StrongOrdering;
10538     if (Type->hasFloatingRepresentation())
10539       return CCT::PartialOrdering;
10540     llvm_unreachable("other types are unimplemented");
10541   }();
10542 
10543   return S.CheckComparisonCategoryType(TypeKind, Loc);
10544 }
10545 
10546 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10547                                                  ExprResult &RHS,
10548                                                  SourceLocation Loc,
10549                                                  BinaryOperatorKind Opc) {
10550   if (Opc == BO_Cmp)
10551     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10552 
10553   // C99 6.5.8p3 / C99 6.5.9p4
10554   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10555   if (LHS.isInvalid() || RHS.isInvalid())
10556     return QualType();
10557   if (Type.isNull())
10558     return S.InvalidOperands(Loc, LHS, RHS);
10559   assert(Type->isArithmeticType() || Type->isEnumeralType());
10560 
10561   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10562 
10563   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10564     return S.InvalidOperands(Loc, LHS, RHS);
10565 
10566   // Check for comparisons of floating point operands using != and ==.
10567   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10568     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10569 
10570   // The result of comparisons is 'bool' in C++, 'int' in C.
10571   return S.Context.getLogicalOperationType();
10572 }
10573 
10574 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10575   if (!NullE.get()->getType()->isAnyPointerType())
10576     return;
10577   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10578   if (!E.get()->getType()->isAnyPointerType() &&
10579       E.get()->isNullPointerConstant(Context,
10580                                      Expr::NPC_ValueDependentIsNotNull) ==
10581         Expr::NPCK_ZeroExpression) {
10582     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10583       if (CL->getValue() == 0)
10584         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10585             << NullValue
10586             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10587                                             NullValue ? "NULL" : "(void *)0");
10588     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10589         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10590         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10591         if (T == Context.CharTy)
10592           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10593               << NullValue
10594               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10595                                               NullValue ? "NULL" : "(void *)0");
10596       }
10597   }
10598 }
10599 
10600 // C99 6.5.8, C++ [expr.rel]
10601 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10602                                     SourceLocation Loc,
10603                                     BinaryOperatorKind Opc) {
10604   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10605   bool IsThreeWay = Opc == BO_Cmp;
10606   auto IsAnyPointerType = [](ExprResult E) {
10607     QualType Ty = E.get()->getType();
10608     return Ty->isPointerType() || Ty->isMemberPointerType();
10609   };
10610 
10611   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10612   // type, array-to-pointer, ..., conversions are performed on both operands to
10613   // bring them to their composite type.
10614   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10615   // any type-related checks.
10616   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10617     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10618     if (LHS.isInvalid())
10619       return QualType();
10620     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10621     if (RHS.isInvalid())
10622       return QualType();
10623   } else {
10624     LHS = DefaultLvalueConversion(LHS.get());
10625     if (LHS.isInvalid())
10626       return QualType();
10627     RHS = DefaultLvalueConversion(RHS.get());
10628     if (RHS.isInvalid())
10629       return QualType();
10630   }
10631 
10632   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10633   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10634     CheckPtrComparisonWithNullChar(LHS, RHS);
10635     CheckPtrComparisonWithNullChar(RHS, LHS);
10636   }
10637 
10638   // Handle vector comparisons separately.
10639   if (LHS.get()->getType()->isVectorType() ||
10640       RHS.get()->getType()->isVectorType())
10641     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10642 
10643   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10644   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10645 
10646   QualType LHSType = LHS.get()->getType();
10647   QualType RHSType = RHS.get()->getType();
10648   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10649       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10650     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10651 
10652   const Expr::NullPointerConstantKind LHSNullKind =
10653       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10654   const Expr::NullPointerConstantKind RHSNullKind =
10655       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10656   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10657   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10658 
10659   auto computeResultTy = [&]() {
10660     if (Opc != BO_Cmp)
10661       return Context.getLogicalOperationType();
10662     assert(getLangOpts().CPlusPlus);
10663     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10664 
10665     QualType CompositeTy = LHS.get()->getType();
10666     assert(!CompositeTy->isReferenceType());
10667 
10668     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10669       return CheckComparisonCategoryType(Kind, Loc);
10670     };
10671 
10672     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10673     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10674     // result is of type std::strong_equality
10675     if (CompositeTy->isFunctionPointerType() ||
10676         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10677       // FIXME: consider making the function pointer case produce
10678       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10679       // and direction polls
10680       return buildResultTy(ComparisonCategoryType::StrongEquality);
10681 
10682     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10683     // pointer type, p <=> q is of type std::strong_ordering.
10684     if (CompositeTy->isPointerType()) {
10685       // P0946R0: Comparisons between a null pointer constant and an object
10686       // pointer result in std::strong_equality
10687       if (LHSIsNull != RHSIsNull)
10688         return buildResultTy(ComparisonCategoryType::StrongEquality);
10689       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10690     }
10691     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10692     // TODO: Extend support for operator<=> to ObjC types.
10693     return InvalidOperands(Loc, LHS, RHS);
10694   };
10695 
10696 
10697   if (!IsRelational && LHSIsNull != RHSIsNull) {
10698     bool IsEquality = Opc == BO_EQ;
10699     if (RHSIsNull)
10700       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10701                                    RHS.get()->getSourceRange());
10702     else
10703       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10704                                    LHS.get()->getSourceRange());
10705   }
10706 
10707   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10708       (RHSType->isIntegerType() && !RHSIsNull)) {
10709     // Skip normal pointer conversion checks in this case; we have better
10710     // diagnostics for this below.
10711   } else if (getLangOpts().CPlusPlus) {
10712     // Equality comparison of a function pointer to a void pointer is invalid,
10713     // but we allow it as an extension.
10714     // FIXME: If we really want to allow this, should it be part of composite
10715     // pointer type computation so it works in conditionals too?
10716     if (!IsRelational &&
10717         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10718          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10719       // This is a gcc extension compatibility comparison.
10720       // In a SFINAE context, we treat this as a hard error to maintain
10721       // conformance with the C++ standard.
10722       diagnoseFunctionPointerToVoidComparison(
10723           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10724 
10725       if (isSFINAEContext())
10726         return QualType();
10727 
10728       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10729       return computeResultTy();
10730     }
10731 
10732     // C++ [expr.eq]p2:
10733     //   If at least one operand is a pointer [...] bring them to their
10734     //   composite pointer type.
10735     // C++ [expr.spaceship]p6
10736     //  If at least one of the operands is of pointer type, [...] bring them
10737     //  to their composite pointer type.
10738     // C++ [expr.rel]p2:
10739     //   If both operands are pointers, [...] bring them to their composite
10740     //   pointer type.
10741     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10742             (IsRelational ? 2 : 1) &&
10743         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10744                                          RHSType->isObjCObjectPointerType()))) {
10745       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10746         return QualType();
10747       return computeResultTy();
10748     }
10749   } else if (LHSType->isPointerType() &&
10750              RHSType->isPointerType()) { // C99 6.5.8p2
10751     // All of the following pointer-related warnings are GCC extensions, except
10752     // when handling null pointer constants.
10753     QualType LCanPointeeTy =
10754       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10755     QualType RCanPointeeTy =
10756       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10757 
10758     // C99 6.5.9p2 and C99 6.5.8p2
10759     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10760                                    RCanPointeeTy.getUnqualifiedType())) {
10761       // Valid unless a relational comparison of function pointers
10762       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10763         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10764           << LHSType << RHSType << LHS.get()->getSourceRange()
10765           << RHS.get()->getSourceRange();
10766       }
10767     } else if (!IsRelational &&
10768                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10769       // Valid unless comparison between non-null pointer and function pointer
10770       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10771           && !LHSIsNull && !RHSIsNull)
10772         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10773                                                 /*isError*/false);
10774     } else {
10775       // Invalid
10776       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10777     }
10778     if (LCanPointeeTy != RCanPointeeTy) {
10779       // Treat NULL constant as a special case in OpenCL.
10780       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10781         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10782         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10783           Diag(Loc,
10784                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10785               << LHSType << RHSType << 0 /* comparison */
10786               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10787         }
10788       }
10789       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10790       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10791       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10792                                                : CK_BitCast;
10793       if (LHSIsNull && !RHSIsNull)
10794         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10795       else
10796         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10797     }
10798     return computeResultTy();
10799   }
10800 
10801   if (getLangOpts().CPlusPlus) {
10802     // C++ [expr.eq]p4:
10803     //   Two operands of type std::nullptr_t or one operand of type
10804     //   std::nullptr_t and the other a null pointer constant compare equal.
10805     if (!IsRelational && LHSIsNull && RHSIsNull) {
10806       if (LHSType->isNullPtrType()) {
10807         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10808         return computeResultTy();
10809       }
10810       if (RHSType->isNullPtrType()) {
10811         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10812         return computeResultTy();
10813       }
10814     }
10815 
10816     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10817     // These aren't covered by the composite pointer type rules.
10818     if (!IsRelational && RHSType->isNullPtrType() &&
10819         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10820       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10821       return computeResultTy();
10822     }
10823     if (!IsRelational && LHSType->isNullPtrType() &&
10824         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10825       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10826       return computeResultTy();
10827     }
10828 
10829     if (IsRelational &&
10830         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10831          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10832       // HACK: Relational comparison of nullptr_t against a pointer type is
10833       // invalid per DR583, but we allow it within std::less<> and friends,
10834       // since otherwise common uses of it break.
10835       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10836       // friends to have std::nullptr_t overload candidates.
10837       DeclContext *DC = CurContext;
10838       if (isa<FunctionDecl>(DC))
10839         DC = DC->getParent();
10840       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10841         if (CTSD->isInStdNamespace() &&
10842             llvm::StringSwitch<bool>(CTSD->getName())
10843                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10844                 .Default(false)) {
10845           if (RHSType->isNullPtrType())
10846             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10847           else
10848             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10849           return computeResultTy();
10850         }
10851       }
10852     }
10853 
10854     // C++ [expr.eq]p2:
10855     //   If at least one operand is a pointer to member, [...] bring them to
10856     //   their composite pointer type.
10857     if (!IsRelational &&
10858         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10859       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10860         return QualType();
10861       else
10862         return computeResultTy();
10863     }
10864   }
10865 
10866   // Handle block pointer types.
10867   if (!IsRelational && LHSType->isBlockPointerType() &&
10868       RHSType->isBlockPointerType()) {
10869     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10870     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10871 
10872     if (!LHSIsNull && !RHSIsNull &&
10873         !Context.typesAreCompatible(lpointee, rpointee)) {
10874       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10875         << LHSType << RHSType << LHS.get()->getSourceRange()
10876         << RHS.get()->getSourceRange();
10877     }
10878     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10879     return computeResultTy();
10880   }
10881 
10882   // Allow block pointers to be compared with null pointer constants.
10883   if (!IsRelational
10884       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10885           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10886     if (!LHSIsNull && !RHSIsNull) {
10887       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10888              ->getPointeeType()->isVoidType())
10889             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10890                 ->getPointeeType()->isVoidType())))
10891         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10892           << LHSType << RHSType << LHS.get()->getSourceRange()
10893           << RHS.get()->getSourceRange();
10894     }
10895     if (LHSIsNull && !RHSIsNull)
10896       LHS = ImpCastExprToType(LHS.get(), RHSType,
10897                               RHSType->isPointerType() ? CK_BitCast
10898                                 : CK_AnyPointerToBlockPointerCast);
10899     else
10900       RHS = ImpCastExprToType(RHS.get(), LHSType,
10901                               LHSType->isPointerType() ? CK_BitCast
10902                                 : CK_AnyPointerToBlockPointerCast);
10903     return computeResultTy();
10904   }
10905 
10906   if (LHSType->isObjCObjectPointerType() ||
10907       RHSType->isObjCObjectPointerType()) {
10908     const PointerType *LPT = LHSType->getAs<PointerType>();
10909     const PointerType *RPT = RHSType->getAs<PointerType>();
10910     if (LPT || RPT) {
10911       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10912       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10913 
10914       if (!LPtrToVoid && !RPtrToVoid &&
10915           !Context.typesAreCompatible(LHSType, RHSType)) {
10916         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10917                                           /*isError*/false);
10918       }
10919       if (LHSIsNull && !RHSIsNull) {
10920         Expr *E = LHS.get();
10921         if (getLangOpts().ObjCAutoRefCount)
10922           CheckObjCConversion(SourceRange(), RHSType, E,
10923                               CCK_ImplicitConversion);
10924         LHS = ImpCastExprToType(E, RHSType,
10925                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10926       }
10927       else {
10928         Expr *E = RHS.get();
10929         if (getLangOpts().ObjCAutoRefCount)
10930           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10931                               /*Diagnose=*/true,
10932                               /*DiagnoseCFAudited=*/false, Opc);
10933         RHS = ImpCastExprToType(E, LHSType,
10934                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10935       }
10936       return computeResultTy();
10937     }
10938     if (LHSType->isObjCObjectPointerType() &&
10939         RHSType->isObjCObjectPointerType()) {
10940       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10941         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10942                                           /*isError*/false);
10943       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10944         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10945 
10946       if (LHSIsNull && !RHSIsNull)
10947         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10948       else
10949         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10950       return computeResultTy();
10951     }
10952 
10953     if (!IsRelational && LHSType->isBlockPointerType() &&
10954         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10955       LHS = ImpCastExprToType(LHS.get(), RHSType,
10956                               CK_BlockPointerToObjCPointerCast);
10957       return computeResultTy();
10958     } else if (!IsRelational &&
10959                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10960                RHSType->isBlockPointerType()) {
10961       RHS = ImpCastExprToType(RHS.get(), LHSType,
10962                               CK_BlockPointerToObjCPointerCast);
10963       return computeResultTy();
10964     }
10965   }
10966   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10967       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10968     unsigned DiagID = 0;
10969     bool isError = false;
10970     if (LangOpts.DebuggerSupport) {
10971       // Under a debugger, allow the comparison of pointers to integers,
10972       // since users tend to want to compare addresses.
10973     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10974                (RHSIsNull && RHSType->isIntegerType())) {
10975       if (IsRelational) {
10976         isError = getLangOpts().CPlusPlus;
10977         DiagID =
10978           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10979                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10980       }
10981     } else if (getLangOpts().CPlusPlus) {
10982       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10983       isError = true;
10984     } else if (IsRelational)
10985       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10986     else
10987       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10988 
10989     if (DiagID) {
10990       Diag(Loc, DiagID)
10991         << LHSType << RHSType << LHS.get()->getSourceRange()
10992         << RHS.get()->getSourceRange();
10993       if (isError)
10994         return QualType();
10995     }
10996 
10997     if (LHSType->isIntegerType())
10998       LHS = ImpCastExprToType(LHS.get(), RHSType,
10999                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11000     else
11001       RHS = ImpCastExprToType(RHS.get(), LHSType,
11002                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11003     return computeResultTy();
11004   }
11005 
11006   // Handle block pointers.
11007   if (!IsRelational && RHSIsNull
11008       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11009     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11010     return computeResultTy();
11011   }
11012   if (!IsRelational && LHSIsNull
11013       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11014     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11015     return computeResultTy();
11016   }
11017 
11018   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11019     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11020       return computeResultTy();
11021     }
11022 
11023     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11024       return computeResultTy();
11025     }
11026 
11027     if (LHSIsNull && RHSType->isQueueT()) {
11028       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11029       return computeResultTy();
11030     }
11031 
11032     if (LHSType->isQueueT() && RHSIsNull) {
11033       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11034       return computeResultTy();
11035     }
11036   }
11037 
11038   return InvalidOperands(Loc, LHS, RHS);
11039 }
11040 
11041 // Return a signed ext_vector_type that is of identical size and number of
11042 // elements. For floating point vectors, return an integer type of identical
11043 // size and number of elements. In the non ext_vector_type case, search from
11044 // the largest type to the smallest type to avoid cases where long long == long,
11045 // where long gets picked over long long.
11046 QualType Sema::GetSignedVectorType(QualType V) {
11047   const VectorType *VTy = V->castAs<VectorType>();
11048   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11049 
11050   if (isa<ExtVectorType>(VTy)) {
11051     if (TypeSize == Context.getTypeSize(Context.CharTy))
11052       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11053     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11054       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11055     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11056       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11057     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11058       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11059     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11060            "Unhandled vector element size in vector compare");
11061     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11062   }
11063 
11064   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11065     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11066                                  VectorType::GenericVector);
11067   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11068     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11069                                  VectorType::GenericVector);
11070   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11071     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11072                                  VectorType::GenericVector);
11073   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11074     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11075                                  VectorType::GenericVector);
11076   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11077          "Unhandled vector element size in vector compare");
11078   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11079                                VectorType::GenericVector);
11080 }
11081 
11082 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11083 /// operates on extended vector types.  Instead of producing an IntTy result,
11084 /// like a scalar comparison, a vector comparison produces a vector of integer
11085 /// types.
11086 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11087                                           SourceLocation Loc,
11088                                           BinaryOperatorKind Opc) {
11089   // Check to make sure we're operating on vectors of the same type and width,
11090   // Allowing one side to be a scalar of element type.
11091   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11092                               /*AllowBothBool*/true,
11093                               /*AllowBoolConversions*/getLangOpts().ZVector);
11094   if (vType.isNull())
11095     return vType;
11096 
11097   QualType LHSType = LHS.get()->getType();
11098 
11099   // If AltiVec, the comparison results in a numeric type, i.e.
11100   // bool for C++, int for C
11101   if (getLangOpts().AltiVec &&
11102       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11103     return Context.getLogicalOperationType();
11104 
11105   // For non-floating point types, check for self-comparisons of the form
11106   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11107   // often indicate logic errors in the program.
11108   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11109 
11110   // Check for comparisons of floating point operands using != and ==.
11111   if (BinaryOperator::isEqualityOp(Opc) &&
11112       LHSType->hasFloatingRepresentation()) {
11113     assert(RHS.get()->getType()->hasFloatingRepresentation());
11114     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11115   }
11116 
11117   // Return a signed type for the vector.
11118   return GetSignedVectorType(vType);
11119 }
11120 
11121 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11122                                     const ExprResult &XorRHS,
11123                                     const SourceLocation Loc) {
11124   // Do not diagnose macros.
11125   if (Loc.isMacroID())
11126     return;
11127 
11128   bool Negative = false;
11129   bool ExplicitPlus = false;
11130   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11131   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11132 
11133   if (!LHSInt)
11134     return;
11135   if (!RHSInt) {
11136     // Check negative literals.
11137     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11138       UnaryOperatorKind Opc = UO->getOpcode();
11139       if (Opc != UO_Minus && Opc != UO_Plus)
11140         return;
11141       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11142       if (!RHSInt)
11143         return;
11144       Negative = (Opc == UO_Minus);
11145       ExplicitPlus = !Negative;
11146     } else {
11147       return;
11148     }
11149   }
11150 
11151   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11152   llvm::APInt RightSideValue = RHSInt->getValue();
11153   if (LeftSideValue != 2 && LeftSideValue != 10)
11154     return;
11155 
11156   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11157     return;
11158 
11159   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11160       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11161   llvm::StringRef ExprStr =
11162       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11163 
11164   CharSourceRange XorRange =
11165       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11166   llvm::StringRef XorStr =
11167       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11168   // Do not diagnose if xor keyword/macro is used.
11169   if (XorStr == "xor")
11170     return;
11171 
11172   std::string LHSStr = Lexer::getSourceText(
11173       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11174       S.getSourceManager(), S.getLangOpts());
11175   std::string RHSStr = Lexer::getSourceText(
11176       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11177       S.getSourceManager(), S.getLangOpts());
11178 
11179   if (Negative) {
11180     RightSideValue = -RightSideValue;
11181     RHSStr = "-" + RHSStr;
11182   } else if (ExplicitPlus) {
11183     RHSStr = "+" + RHSStr;
11184   }
11185 
11186   StringRef LHSStrRef = LHSStr;
11187   StringRef RHSStrRef = RHSStr;
11188   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11189   // literals.
11190   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11191       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11192       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11193       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11194       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11195       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11196       LHSStrRef.find('\'') != StringRef::npos ||
11197       RHSStrRef.find('\'') != StringRef::npos)
11198     return;
11199 
11200   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11201   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11202   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11203   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11204     std::string SuggestedExpr = "1 << " + RHSStr;
11205     bool Overflow = false;
11206     llvm::APInt One = (LeftSideValue - 1);
11207     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11208     if (Overflow) {
11209       if (RightSideIntValue < 64)
11210         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11211             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11212             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11213       else if (RightSideIntValue == 64)
11214         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11215       else
11216         return;
11217     } else {
11218       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11219           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11220           << PowValue.toString(10, true)
11221           << FixItHint::CreateReplacement(
11222                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11223     }
11224 
11225     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11226   } else if (LeftSideValue == 10) {
11227     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11228     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11229         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11230         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11231     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11232   }
11233 }
11234 
11235 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11236                                           SourceLocation Loc) {
11237   // Ensure that either both operands are of the same vector type, or
11238   // one operand is of a vector type and the other is of its element type.
11239   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11240                                        /*AllowBothBool*/true,
11241                                        /*AllowBoolConversions*/false);
11242   if (vType.isNull())
11243     return InvalidOperands(Loc, LHS, RHS);
11244   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11245       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11246     return InvalidOperands(Loc, LHS, RHS);
11247   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11248   //        usage of the logical operators && and || with vectors in C. This
11249   //        check could be notionally dropped.
11250   if (!getLangOpts().CPlusPlus &&
11251       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11252     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11253 
11254   return GetSignedVectorType(LHS.get()->getType());
11255 }
11256 
11257 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11258                                            SourceLocation Loc,
11259                                            BinaryOperatorKind Opc) {
11260   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11261 
11262   bool IsCompAssign =
11263       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11264 
11265   if (LHS.get()->getType()->isVectorType() ||
11266       RHS.get()->getType()->isVectorType()) {
11267     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11268         RHS.get()->getType()->hasIntegerRepresentation())
11269       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11270                         /*AllowBothBool*/true,
11271                         /*AllowBoolConversions*/getLangOpts().ZVector);
11272     return InvalidOperands(Loc, LHS, RHS);
11273   }
11274 
11275   if (Opc == BO_And)
11276     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11277 
11278   ExprResult LHSResult = LHS, RHSResult = RHS;
11279   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
11280                                                  IsCompAssign);
11281   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11282     return QualType();
11283   LHS = LHSResult.get();
11284   RHS = RHSResult.get();
11285 
11286   if (Opc == BO_Xor)
11287     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11288 
11289   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11290     return compType;
11291   return InvalidOperands(Loc, LHS, RHS);
11292 }
11293 
11294 // C99 6.5.[13,14]
11295 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11296                                            SourceLocation Loc,
11297                                            BinaryOperatorKind Opc) {
11298   // Check vector operands differently.
11299   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11300     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11301 
11302   bool EnumConstantInBoolContext = false;
11303   for (const ExprResult &HS : {LHS, RHS}) {
11304     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11305       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11306       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11307         EnumConstantInBoolContext = true;
11308     }
11309   }
11310 
11311   if (EnumConstantInBoolContext)
11312     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11313 
11314   // Diagnose cases where the user write a logical and/or but probably meant a
11315   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11316   // is a constant.
11317   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11318       !LHS.get()->getType()->isBooleanType() &&
11319       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11320       // Don't warn in macros or template instantiations.
11321       !Loc.isMacroID() && !inTemplateInstantiation()) {
11322     // If the RHS can be constant folded, and if it constant folds to something
11323     // that isn't 0 or 1 (which indicate a potential logical operation that
11324     // happened to fold to true/false) then warn.
11325     // Parens on the RHS are ignored.
11326     Expr::EvalResult EVResult;
11327     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11328       llvm::APSInt Result = EVResult.Val.getInt();
11329       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11330            !RHS.get()->getExprLoc().isMacroID()) ||
11331           (Result != 0 && Result != 1)) {
11332         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11333           << RHS.get()->getSourceRange()
11334           << (Opc == BO_LAnd ? "&&" : "||");
11335         // Suggest replacing the logical operator with the bitwise version
11336         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11337             << (Opc == BO_LAnd ? "&" : "|")
11338             << FixItHint::CreateReplacement(SourceRange(
11339                                                  Loc, getLocForEndOfToken(Loc)),
11340                                             Opc == BO_LAnd ? "&" : "|");
11341         if (Opc == BO_LAnd)
11342           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11343           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11344               << FixItHint::CreateRemoval(
11345                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11346                                  RHS.get()->getEndLoc()));
11347       }
11348     }
11349   }
11350 
11351   if (!Context.getLangOpts().CPlusPlus) {
11352     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11353     // not operate on the built-in scalar and vector float types.
11354     if (Context.getLangOpts().OpenCL &&
11355         Context.getLangOpts().OpenCLVersion < 120) {
11356       if (LHS.get()->getType()->isFloatingType() ||
11357           RHS.get()->getType()->isFloatingType())
11358         return InvalidOperands(Loc, LHS, RHS);
11359     }
11360 
11361     LHS = UsualUnaryConversions(LHS.get());
11362     if (LHS.isInvalid())
11363       return QualType();
11364 
11365     RHS = UsualUnaryConversions(RHS.get());
11366     if (RHS.isInvalid())
11367       return QualType();
11368 
11369     if (!LHS.get()->getType()->isScalarType() ||
11370         !RHS.get()->getType()->isScalarType())
11371       return InvalidOperands(Loc, LHS, RHS);
11372 
11373     return Context.IntTy;
11374   }
11375 
11376   // The following is safe because we only use this method for
11377   // non-overloadable operands.
11378 
11379   // C++ [expr.log.and]p1
11380   // C++ [expr.log.or]p1
11381   // The operands are both contextually converted to type bool.
11382   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11383   if (LHSRes.isInvalid())
11384     return InvalidOperands(Loc, LHS, RHS);
11385   LHS = LHSRes;
11386 
11387   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11388   if (RHSRes.isInvalid())
11389     return InvalidOperands(Loc, LHS, RHS);
11390   RHS = RHSRes;
11391 
11392   // C++ [expr.log.and]p2
11393   // C++ [expr.log.or]p2
11394   // The result is a bool.
11395   return Context.BoolTy;
11396 }
11397 
11398 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11399   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11400   if (!ME) return false;
11401   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11402   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11403       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11404   if (!Base) return false;
11405   return Base->getMethodDecl() != nullptr;
11406 }
11407 
11408 /// Is the given expression (which must be 'const') a reference to a
11409 /// variable which was originally non-const, but which has become
11410 /// 'const' due to being captured within a block?
11411 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11412 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11413   assert(E->isLValue() && E->getType().isConstQualified());
11414   E = E->IgnoreParens();
11415 
11416   // Must be a reference to a declaration from an enclosing scope.
11417   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11418   if (!DRE) return NCCK_None;
11419   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11420 
11421   // The declaration must be a variable which is not declared 'const'.
11422   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11423   if (!var) return NCCK_None;
11424   if (var->getType().isConstQualified()) return NCCK_None;
11425   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11426 
11427   // Decide whether the first capture was for a block or a lambda.
11428   DeclContext *DC = S.CurContext, *Prev = nullptr;
11429   // Decide whether the first capture was for a block or a lambda.
11430   while (DC) {
11431     // For init-capture, it is possible that the variable belongs to the
11432     // template pattern of the current context.
11433     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11434       if (var->isInitCapture() &&
11435           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11436         break;
11437     if (DC == var->getDeclContext())
11438       break;
11439     Prev = DC;
11440     DC = DC->getParent();
11441   }
11442   // Unless we have an init-capture, we've gone one step too far.
11443   if (!var->isInitCapture())
11444     DC = Prev;
11445   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11446 }
11447 
11448 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11449   Ty = Ty.getNonReferenceType();
11450   if (IsDereference && Ty->isPointerType())
11451     Ty = Ty->getPointeeType();
11452   return !Ty.isConstQualified();
11453 }
11454 
11455 // Update err_typecheck_assign_const and note_typecheck_assign_const
11456 // when this enum is changed.
11457 enum {
11458   ConstFunction,
11459   ConstVariable,
11460   ConstMember,
11461   ConstMethod,
11462   NestedConstMember,
11463   ConstUnknown,  // Keep as last element
11464 };
11465 
11466 /// Emit the "read-only variable not assignable" error and print notes to give
11467 /// more information about why the variable is not assignable, such as pointing
11468 /// to the declaration of a const variable, showing that a method is const, or
11469 /// that the function is returning a const reference.
11470 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11471                                     SourceLocation Loc) {
11472   SourceRange ExprRange = E->getSourceRange();
11473 
11474   // Only emit one error on the first const found.  All other consts will emit
11475   // a note to the error.
11476   bool DiagnosticEmitted = false;
11477 
11478   // Track if the current expression is the result of a dereference, and if the
11479   // next checked expression is the result of a dereference.
11480   bool IsDereference = false;
11481   bool NextIsDereference = false;
11482 
11483   // Loop to process MemberExpr chains.
11484   while (true) {
11485     IsDereference = NextIsDereference;
11486 
11487     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11488     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11489       NextIsDereference = ME->isArrow();
11490       const ValueDecl *VD = ME->getMemberDecl();
11491       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11492         // Mutable fields can be modified even if the class is const.
11493         if (Field->isMutable()) {
11494           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11495           break;
11496         }
11497 
11498         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11499           if (!DiagnosticEmitted) {
11500             S.Diag(Loc, diag::err_typecheck_assign_const)
11501                 << ExprRange << ConstMember << false /*static*/ << Field
11502                 << Field->getType();
11503             DiagnosticEmitted = true;
11504           }
11505           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11506               << ConstMember << false /*static*/ << Field << Field->getType()
11507               << Field->getSourceRange();
11508         }
11509         E = ME->getBase();
11510         continue;
11511       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11512         if (VDecl->getType().isConstQualified()) {
11513           if (!DiagnosticEmitted) {
11514             S.Diag(Loc, diag::err_typecheck_assign_const)
11515                 << ExprRange << ConstMember << true /*static*/ << VDecl
11516                 << VDecl->getType();
11517             DiagnosticEmitted = true;
11518           }
11519           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11520               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11521               << VDecl->getSourceRange();
11522         }
11523         // Static fields do not inherit constness from parents.
11524         break;
11525       }
11526       break; // End MemberExpr
11527     } else if (const ArraySubscriptExpr *ASE =
11528                    dyn_cast<ArraySubscriptExpr>(E)) {
11529       E = ASE->getBase()->IgnoreParenImpCasts();
11530       continue;
11531     } else if (const ExtVectorElementExpr *EVE =
11532                    dyn_cast<ExtVectorElementExpr>(E)) {
11533       E = EVE->getBase()->IgnoreParenImpCasts();
11534       continue;
11535     }
11536     break;
11537   }
11538 
11539   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11540     // Function calls
11541     const FunctionDecl *FD = CE->getDirectCallee();
11542     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11543       if (!DiagnosticEmitted) {
11544         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11545                                                       << ConstFunction << FD;
11546         DiagnosticEmitted = true;
11547       }
11548       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11549              diag::note_typecheck_assign_const)
11550           << ConstFunction << FD << FD->getReturnType()
11551           << FD->getReturnTypeSourceRange();
11552     }
11553   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11554     // Point to variable declaration.
11555     if (const ValueDecl *VD = DRE->getDecl()) {
11556       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11557         if (!DiagnosticEmitted) {
11558           S.Diag(Loc, diag::err_typecheck_assign_const)
11559               << ExprRange << ConstVariable << VD << VD->getType();
11560           DiagnosticEmitted = true;
11561         }
11562         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11563             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11564       }
11565     }
11566   } else if (isa<CXXThisExpr>(E)) {
11567     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11568       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11569         if (MD->isConst()) {
11570           if (!DiagnosticEmitted) {
11571             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11572                                                           << ConstMethod << MD;
11573             DiagnosticEmitted = true;
11574           }
11575           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11576               << ConstMethod << MD << MD->getSourceRange();
11577         }
11578       }
11579     }
11580   }
11581 
11582   if (DiagnosticEmitted)
11583     return;
11584 
11585   // Can't determine a more specific message, so display the generic error.
11586   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11587 }
11588 
11589 enum OriginalExprKind {
11590   OEK_Variable,
11591   OEK_Member,
11592   OEK_LValue
11593 };
11594 
11595 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11596                                          const RecordType *Ty,
11597                                          SourceLocation Loc, SourceRange Range,
11598                                          OriginalExprKind OEK,
11599                                          bool &DiagnosticEmitted) {
11600   std::vector<const RecordType *> RecordTypeList;
11601   RecordTypeList.push_back(Ty);
11602   unsigned NextToCheckIndex = 0;
11603   // We walk the record hierarchy breadth-first to ensure that we print
11604   // diagnostics in field nesting order.
11605   while (RecordTypeList.size() > NextToCheckIndex) {
11606     bool IsNested = NextToCheckIndex > 0;
11607     for (const FieldDecl *Field :
11608          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11609       // First, check every field for constness.
11610       QualType FieldTy = Field->getType();
11611       if (FieldTy.isConstQualified()) {
11612         if (!DiagnosticEmitted) {
11613           S.Diag(Loc, diag::err_typecheck_assign_const)
11614               << Range << NestedConstMember << OEK << VD
11615               << IsNested << Field;
11616           DiagnosticEmitted = true;
11617         }
11618         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11619             << NestedConstMember << IsNested << Field
11620             << FieldTy << Field->getSourceRange();
11621       }
11622 
11623       // Then we append it to the list to check next in order.
11624       FieldTy = FieldTy.getCanonicalType();
11625       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11626         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11627           RecordTypeList.push_back(FieldRecTy);
11628       }
11629     }
11630     ++NextToCheckIndex;
11631   }
11632 }
11633 
11634 /// Emit an error for the case where a record we are trying to assign to has a
11635 /// const-qualified field somewhere in its hierarchy.
11636 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11637                                          SourceLocation Loc) {
11638   QualType Ty = E->getType();
11639   assert(Ty->isRecordType() && "lvalue was not record?");
11640   SourceRange Range = E->getSourceRange();
11641   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11642   bool DiagEmitted = false;
11643 
11644   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11645     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11646             Range, OEK_Member, DiagEmitted);
11647   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11648     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11649             Range, OEK_Variable, DiagEmitted);
11650   else
11651     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11652             Range, OEK_LValue, DiagEmitted);
11653   if (!DiagEmitted)
11654     DiagnoseConstAssignment(S, E, Loc);
11655 }
11656 
11657 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11658 /// emit an error and return true.  If so, return false.
11659 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11660   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11661 
11662   S.CheckShadowingDeclModification(E, Loc);
11663 
11664   SourceLocation OrigLoc = Loc;
11665   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11666                                                               &Loc);
11667   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11668     IsLV = Expr::MLV_InvalidMessageExpression;
11669   if (IsLV == Expr::MLV_Valid)
11670     return false;
11671 
11672   unsigned DiagID = 0;
11673   bool NeedType = false;
11674   switch (IsLV) { // C99 6.5.16p2
11675   case Expr::MLV_ConstQualified:
11676     // Use a specialized diagnostic when we're assigning to an object
11677     // from an enclosing function or block.
11678     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11679       if (NCCK == NCCK_Block)
11680         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11681       else
11682         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11683       break;
11684     }
11685 
11686     // In ARC, use some specialized diagnostics for occasions where we
11687     // infer 'const'.  These are always pseudo-strong variables.
11688     if (S.getLangOpts().ObjCAutoRefCount) {
11689       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11690       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11691         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11692 
11693         // Use the normal diagnostic if it's pseudo-__strong but the
11694         // user actually wrote 'const'.
11695         if (var->isARCPseudoStrong() &&
11696             (!var->getTypeSourceInfo() ||
11697              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11698           // There are three pseudo-strong cases:
11699           //  - self
11700           ObjCMethodDecl *method = S.getCurMethodDecl();
11701           if (method && var == method->getSelfDecl()) {
11702             DiagID = method->isClassMethod()
11703               ? diag::err_typecheck_arc_assign_self_class_method
11704               : diag::err_typecheck_arc_assign_self;
11705 
11706           //  - Objective-C externally_retained attribute.
11707           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11708                      isa<ParmVarDecl>(var)) {
11709             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11710 
11711           //  - fast enumeration variables
11712           } else {
11713             DiagID = diag::err_typecheck_arr_assign_enumeration;
11714           }
11715 
11716           SourceRange Assign;
11717           if (Loc != OrigLoc)
11718             Assign = SourceRange(OrigLoc, OrigLoc);
11719           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11720           // We need to preserve the AST regardless, so migration tool
11721           // can do its job.
11722           return false;
11723         }
11724       }
11725     }
11726 
11727     // If none of the special cases above are triggered, then this is a
11728     // simple const assignment.
11729     if (DiagID == 0) {
11730       DiagnoseConstAssignment(S, E, Loc);
11731       return true;
11732     }
11733 
11734     break;
11735   case Expr::MLV_ConstAddrSpace:
11736     DiagnoseConstAssignment(S, E, Loc);
11737     return true;
11738   case Expr::MLV_ConstQualifiedField:
11739     DiagnoseRecursiveConstFields(S, E, Loc);
11740     return true;
11741   case Expr::MLV_ArrayType:
11742   case Expr::MLV_ArrayTemporary:
11743     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11744     NeedType = true;
11745     break;
11746   case Expr::MLV_NotObjectType:
11747     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11748     NeedType = true;
11749     break;
11750   case Expr::MLV_LValueCast:
11751     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11752     break;
11753   case Expr::MLV_Valid:
11754     llvm_unreachable("did not take early return for MLV_Valid");
11755   case Expr::MLV_InvalidExpression:
11756   case Expr::MLV_MemberFunction:
11757   case Expr::MLV_ClassTemporary:
11758     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11759     break;
11760   case Expr::MLV_IncompleteType:
11761   case Expr::MLV_IncompleteVoidType:
11762     return S.RequireCompleteType(Loc, E->getType(),
11763              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11764   case Expr::MLV_DuplicateVectorComponents:
11765     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11766     break;
11767   case Expr::MLV_NoSetterProperty:
11768     llvm_unreachable("readonly properties should be processed differently");
11769   case Expr::MLV_InvalidMessageExpression:
11770     DiagID = diag::err_readonly_message_assignment;
11771     break;
11772   case Expr::MLV_SubObjCPropertySetting:
11773     DiagID = diag::err_no_subobject_property_setting;
11774     break;
11775   }
11776 
11777   SourceRange Assign;
11778   if (Loc != OrigLoc)
11779     Assign = SourceRange(OrigLoc, OrigLoc);
11780   if (NeedType)
11781     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11782   else
11783     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11784   return true;
11785 }
11786 
11787 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11788                                          SourceLocation Loc,
11789                                          Sema &Sema) {
11790   if (Sema.inTemplateInstantiation())
11791     return;
11792   if (Sema.isUnevaluatedContext())
11793     return;
11794   if (Loc.isInvalid() || Loc.isMacroID())
11795     return;
11796   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11797     return;
11798 
11799   // C / C++ fields
11800   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11801   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11802   if (ML && MR) {
11803     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11804       return;
11805     const ValueDecl *LHSDecl =
11806         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11807     const ValueDecl *RHSDecl =
11808         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11809     if (LHSDecl != RHSDecl)
11810       return;
11811     if (LHSDecl->getType().isVolatileQualified())
11812       return;
11813     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11814       if (RefTy->getPointeeType().isVolatileQualified())
11815         return;
11816 
11817     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11818   }
11819 
11820   // Objective-C instance variables
11821   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11822   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11823   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11824     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11825     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11826     if (RL && RR && RL->getDecl() == RR->getDecl())
11827       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11828   }
11829 }
11830 
11831 // C99 6.5.16.1
11832 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11833                                        SourceLocation Loc,
11834                                        QualType CompoundType) {
11835   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11836 
11837   // Verify that LHS is a modifiable lvalue, and emit error if not.
11838   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11839     return QualType();
11840 
11841   QualType LHSType = LHSExpr->getType();
11842   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11843                                              CompoundType;
11844   // OpenCL v1.2 s6.1.1.1 p2:
11845   // The half data type can only be used to declare a pointer to a buffer that
11846   // contains half values
11847   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11848     LHSType->isHalfType()) {
11849     Diag(Loc, diag::err_opencl_half_load_store) << 1
11850         << LHSType.getUnqualifiedType();
11851     return QualType();
11852   }
11853 
11854   AssignConvertType ConvTy;
11855   if (CompoundType.isNull()) {
11856     Expr *RHSCheck = RHS.get();
11857 
11858     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11859 
11860     QualType LHSTy(LHSType);
11861     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11862     if (RHS.isInvalid())
11863       return QualType();
11864     // Special case of NSObject attributes on c-style pointer types.
11865     if (ConvTy == IncompatiblePointer &&
11866         ((Context.isObjCNSObjectType(LHSType) &&
11867           RHSType->isObjCObjectPointerType()) ||
11868          (Context.isObjCNSObjectType(RHSType) &&
11869           LHSType->isObjCObjectPointerType())))
11870       ConvTy = Compatible;
11871 
11872     if (ConvTy == Compatible &&
11873         LHSType->isObjCObjectType())
11874         Diag(Loc, diag::err_objc_object_assignment)
11875           << LHSType;
11876 
11877     // If the RHS is a unary plus or minus, check to see if they = and + are
11878     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11879     // instead of "x += 4".
11880     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11881       RHSCheck = ICE->getSubExpr();
11882     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11883       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11884           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11885           // Only if the two operators are exactly adjacent.
11886           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11887           // And there is a space or other character before the subexpr of the
11888           // unary +/-.  We don't want to warn on "x=-1".
11889           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11890           UO->getSubExpr()->getBeginLoc().isFileID()) {
11891         Diag(Loc, diag::warn_not_compound_assign)
11892           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11893           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11894       }
11895     }
11896 
11897     if (ConvTy == Compatible) {
11898       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11899         // Warn about retain cycles where a block captures the LHS, but
11900         // not if the LHS is a simple variable into which the block is
11901         // being stored...unless that variable can be captured by reference!
11902         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11903         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11904         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11905           checkRetainCycles(LHSExpr, RHS.get());
11906       }
11907 
11908       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11909           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11910         // It is safe to assign a weak reference into a strong variable.
11911         // Although this code can still have problems:
11912         //   id x = self.weakProp;
11913         //   id y = self.weakProp;
11914         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11915         // paths through the function. This should be revisited if
11916         // -Wrepeated-use-of-weak is made flow-sensitive.
11917         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11918         // variable, which will be valid for the current autorelease scope.
11919         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11920                              RHS.get()->getBeginLoc()))
11921           getCurFunction()->markSafeWeakUse(RHS.get());
11922 
11923       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11924         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11925       }
11926     }
11927   } else {
11928     // Compound assignment "x += y"
11929     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11930   }
11931 
11932   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11933                                RHS.get(), AA_Assigning))
11934     return QualType();
11935 
11936   CheckForNullPointerDereference(*this, LHSExpr);
11937 
11938   // C99 6.5.16p3: The type of an assignment expression is the type of the
11939   // left operand unless the left operand has qualified type, in which case
11940   // it is the unqualified version of the type of the left operand.
11941   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11942   // is converted to the type of the assignment expression (above).
11943   // C++ 5.17p1: the type of the assignment expression is that of its left
11944   // operand.
11945   return (getLangOpts().CPlusPlus
11946           ? LHSType : LHSType.getUnqualifiedType());
11947 }
11948 
11949 // Only ignore explicit casts to void.
11950 static bool IgnoreCommaOperand(const Expr *E) {
11951   E = E->IgnoreParens();
11952 
11953   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11954     if (CE->getCastKind() == CK_ToVoid) {
11955       return true;
11956     }
11957 
11958     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11959     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11960         CE->getSubExpr()->getType()->isDependentType()) {
11961       return true;
11962     }
11963   }
11964 
11965   return false;
11966 }
11967 
11968 // Look for instances where it is likely the comma operator is confused with
11969 // another operator.  There is a whitelist of acceptable expressions for the
11970 // left hand side of the comma operator, otherwise emit a warning.
11971 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11972   // No warnings in macros
11973   if (Loc.isMacroID())
11974     return;
11975 
11976   // Don't warn in template instantiations.
11977   if (inTemplateInstantiation())
11978     return;
11979 
11980   // Scope isn't fine-grained enough to whitelist the specific cases, so
11981   // instead, skip more than needed, then call back into here with the
11982   // CommaVisitor in SemaStmt.cpp.
11983   // The whitelisted locations are the initialization and increment portions
11984   // of a for loop.  The additional checks are on the condition of
11985   // if statements, do/while loops, and for loops.
11986   // Differences in scope flags for C89 mode requires the extra logic.
11987   const unsigned ForIncrementFlags =
11988       getLangOpts().C99 || getLangOpts().CPlusPlus
11989           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11990           : Scope::ContinueScope | Scope::BreakScope;
11991   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11992   const unsigned ScopeFlags = getCurScope()->getFlags();
11993   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11994       (ScopeFlags & ForInitFlags) == ForInitFlags)
11995     return;
11996 
11997   // If there are multiple comma operators used together, get the RHS of the
11998   // of the comma operator as the LHS.
11999   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12000     if (BO->getOpcode() != BO_Comma)
12001       break;
12002     LHS = BO->getRHS();
12003   }
12004 
12005   // Only allow some expressions on LHS to not warn.
12006   if (IgnoreCommaOperand(LHS))
12007     return;
12008 
12009   Diag(Loc, diag::warn_comma_operator);
12010   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12011       << LHS->getSourceRange()
12012       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12013                                     LangOpts.CPlusPlus ? "static_cast<void>("
12014                                                        : "(void)(")
12015       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12016                                     ")");
12017 }
12018 
12019 // C99 6.5.17
12020 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12021                                    SourceLocation Loc) {
12022   LHS = S.CheckPlaceholderExpr(LHS.get());
12023   RHS = S.CheckPlaceholderExpr(RHS.get());
12024   if (LHS.isInvalid() || RHS.isInvalid())
12025     return QualType();
12026 
12027   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12028   // operands, but not unary promotions.
12029   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12030 
12031   // So we treat the LHS as a ignored value, and in C++ we allow the
12032   // containing site to determine what should be done with the RHS.
12033   LHS = S.IgnoredValueConversions(LHS.get());
12034   if (LHS.isInvalid())
12035     return QualType();
12036 
12037   S.DiagnoseUnusedExprResult(LHS.get());
12038 
12039   if (!S.getLangOpts().CPlusPlus) {
12040     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12041     if (RHS.isInvalid())
12042       return QualType();
12043     if (!RHS.get()->getType()->isVoidType())
12044       S.RequireCompleteType(Loc, RHS.get()->getType(),
12045                             diag::err_incomplete_type);
12046   }
12047 
12048   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12049     S.DiagnoseCommaOperator(LHS.get(), Loc);
12050 
12051   return RHS.get()->getType();
12052 }
12053 
12054 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12055 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12056 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12057                                                ExprValueKind &VK,
12058                                                ExprObjectKind &OK,
12059                                                SourceLocation OpLoc,
12060                                                bool IsInc, bool IsPrefix) {
12061   if (Op->isTypeDependent())
12062     return S.Context.DependentTy;
12063 
12064   QualType ResType = Op->getType();
12065   // Atomic types can be used for increment / decrement where the non-atomic
12066   // versions can, so ignore the _Atomic() specifier for the purpose of
12067   // checking.
12068   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12069     ResType = ResAtomicType->getValueType();
12070 
12071   assert(!ResType.isNull() && "no type for increment/decrement expression");
12072 
12073   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12074     // Decrement of bool is not allowed.
12075     if (!IsInc) {
12076       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12077       return QualType();
12078     }
12079     // Increment of bool sets it to true, but is deprecated.
12080     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12081                                               : diag::warn_increment_bool)
12082       << Op->getSourceRange();
12083   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12084     // Error on enum increments and decrements in C++ mode
12085     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12086     return QualType();
12087   } else if (ResType->isRealType()) {
12088     // OK!
12089   } else if (ResType->isPointerType()) {
12090     // C99 6.5.2.4p2, 6.5.6p2
12091     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12092       return QualType();
12093   } else if (ResType->isObjCObjectPointerType()) {
12094     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12095     // Otherwise, we just need a complete type.
12096     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12097         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12098       return QualType();
12099   } else if (ResType->isAnyComplexType()) {
12100     // C99 does not support ++/-- on complex types, we allow as an extension.
12101     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12102       << ResType << Op->getSourceRange();
12103   } else if (ResType->isPlaceholderType()) {
12104     ExprResult PR = S.CheckPlaceholderExpr(Op);
12105     if (PR.isInvalid()) return QualType();
12106     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12107                                           IsInc, IsPrefix);
12108   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12109     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12110   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12111              (ResType->castAs<VectorType>()->getVectorKind() !=
12112               VectorType::AltiVecBool)) {
12113     // The z vector extensions allow ++ and -- for non-bool vectors.
12114   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12115             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12116     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12117   } else {
12118     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12119       << ResType << int(IsInc) << Op->getSourceRange();
12120     return QualType();
12121   }
12122   // At this point, we know we have a real, complex or pointer type.
12123   // Now make sure the operand is a modifiable lvalue.
12124   if (CheckForModifiableLvalue(Op, OpLoc, S))
12125     return QualType();
12126   // In C++, a prefix increment is the same type as the operand. Otherwise
12127   // (in C or with postfix), the increment is the unqualified type of the
12128   // operand.
12129   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12130     VK = VK_LValue;
12131     OK = Op->getObjectKind();
12132     return ResType;
12133   } else {
12134     VK = VK_RValue;
12135     return ResType.getUnqualifiedType();
12136   }
12137 }
12138 
12139 
12140 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12141 /// This routine allows us to typecheck complex/recursive expressions
12142 /// where the declaration is needed for type checking. We only need to
12143 /// handle cases when the expression references a function designator
12144 /// or is an lvalue. Here are some examples:
12145 ///  - &(x) => x
12146 ///  - &*****f => f for f a function designator.
12147 ///  - &s.xx => s
12148 ///  - &s.zz[1].yy -> s, if zz is an array
12149 ///  - *(x + 1) -> x, if x is an array
12150 ///  - &"123"[2] -> 0
12151 ///  - & __real__ x -> x
12152 static ValueDecl *getPrimaryDecl(Expr *E) {
12153   switch (E->getStmtClass()) {
12154   case Stmt::DeclRefExprClass:
12155     return cast<DeclRefExpr>(E)->getDecl();
12156   case Stmt::MemberExprClass:
12157     // If this is an arrow operator, the address is an offset from
12158     // the base's value, so the object the base refers to is
12159     // irrelevant.
12160     if (cast<MemberExpr>(E)->isArrow())
12161       return nullptr;
12162     // Otherwise, the expression refers to a part of the base
12163     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12164   case Stmt::ArraySubscriptExprClass: {
12165     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12166     // promotion of register arrays earlier.
12167     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12168     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12169       if (ICE->getSubExpr()->getType()->isArrayType())
12170         return getPrimaryDecl(ICE->getSubExpr());
12171     }
12172     return nullptr;
12173   }
12174   case Stmt::UnaryOperatorClass: {
12175     UnaryOperator *UO = cast<UnaryOperator>(E);
12176 
12177     switch(UO->getOpcode()) {
12178     case UO_Real:
12179     case UO_Imag:
12180     case UO_Extension:
12181       return getPrimaryDecl(UO->getSubExpr());
12182     default:
12183       return nullptr;
12184     }
12185   }
12186   case Stmt::ParenExprClass:
12187     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12188   case Stmt::ImplicitCastExprClass:
12189     // If the result of an implicit cast is an l-value, we care about
12190     // the sub-expression; otherwise, the result here doesn't matter.
12191     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12192   default:
12193     return nullptr;
12194   }
12195 }
12196 
12197 namespace {
12198   enum {
12199     AO_Bit_Field = 0,
12200     AO_Vector_Element = 1,
12201     AO_Property_Expansion = 2,
12202     AO_Register_Variable = 3,
12203     AO_No_Error = 4
12204   };
12205 }
12206 /// Diagnose invalid operand for address of operations.
12207 ///
12208 /// \param Type The type of operand which cannot have its address taken.
12209 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12210                                          Expr *E, unsigned Type) {
12211   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12212 }
12213 
12214 /// CheckAddressOfOperand - The operand of & must be either a function
12215 /// designator or an lvalue designating an object. If it is an lvalue, the
12216 /// object cannot be declared with storage class register or be a bit field.
12217 /// Note: The usual conversions are *not* applied to the operand of the &
12218 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12219 /// In C++, the operand might be an overloaded function name, in which case
12220 /// we allow the '&' but retain the overloaded-function type.
12221 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12222   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12223     if (PTy->getKind() == BuiltinType::Overload) {
12224       Expr *E = OrigOp.get()->IgnoreParens();
12225       if (!isa<OverloadExpr>(E)) {
12226         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12227         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12228           << OrigOp.get()->getSourceRange();
12229         return QualType();
12230       }
12231 
12232       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12233       if (isa<UnresolvedMemberExpr>(Ovl))
12234         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12235           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12236             << OrigOp.get()->getSourceRange();
12237           return QualType();
12238         }
12239 
12240       return Context.OverloadTy;
12241     }
12242 
12243     if (PTy->getKind() == BuiltinType::UnknownAny)
12244       return Context.UnknownAnyTy;
12245 
12246     if (PTy->getKind() == BuiltinType::BoundMember) {
12247       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12248         << OrigOp.get()->getSourceRange();
12249       return QualType();
12250     }
12251 
12252     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12253     if (OrigOp.isInvalid()) return QualType();
12254   }
12255 
12256   if (OrigOp.get()->isTypeDependent())
12257     return Context.DependentTy;
12258 
12259   assert(!OrigOp.get()->getType()->isPlaceholderType());
12260 
12261   // Make sure to ignore parentheses in subsequent checks
12262   Expr *op = OrigOp.get()->IgnoreParens();
12263 
12264   // In OpenCL captures for blocks called as lambda functions
12265   // are located in the private address space. Blocks used in
12266   // enqueue_kernel can be located in a different address space
12267   // depending on a vendor implementation. Thus preventing
12268   // taking an address of the capture to avoid invalid AS casts.
12269   if (LangOpts.OpenCL) {
12270     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12271     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12272       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12273       return QualType();
12274     }
12275   }
12276 
12277   if (getLangOpts().C99) {
12278     // Implement C99-only parts of addressof rules.
12279     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12280       if (uOp->getOpcode() == UO_Deref)
12281         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12282         // (assuming the deref expression is valid).
12283         return uOp->getSubExpr()->getType();
12284     }
12285     // Technically, there should be a check for array subscript
12286     // expressions here, but the result of one is always an lvalue anyway.
12287   }
12288   ValueDecl *dcl = getPrimaryDecl(op);
12289 
12290   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12291     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12292                                            op->getBeginLoc()))
12293       return QualType();
12294 
12295   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12296   unsigned AddressOfError = AO_No_Error;
12297 
12298   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12299     bool sfinae = (bool)isSFINAEContext();
12300     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12301                                   : diag::ext_typecheck_addrof_temporary)
12302       << op->getType() << op->getSourceRange();
12303     if (sfinae)
12304       return QualType();
12305     // Materialize the temporary as an lvalue so that we can take its address.
12306     OrigOp = op =
12307         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12308   } else if (isa<ObjCSelectorExpr>(op)) {
12309     return Context.getPointerType(op->getType());
12310   } else if (lval == Expr::LV_MemberFunction) {
12311     // If it's an instance method, make a member pointer.
12312     // The expression must have exactly the form &A::foo.
12313 
12314     // If the underlying expression isn't a decl ref, give up.
12315     if (!isa<DeclRefExpr>(op)) {
12316       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12317         << OrigOp.get()->getSourceRange();
12318       return QualType();
12319     }
12320     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12321     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12322 
12323     // The id-expression was parenthesized.
12324     if (OrigOp.get() != DRE) {
12325       Diag(OpLoc, diag::err_parens_pointer_member_function)
12326         << OrigOp.get()->getSourceRange();
12327 
12328     // The method was named without a qualifier.
12329     } else if (!DRE->getQualifier()) {
12330       if (MD->getParent()->getName().empty())
12331         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12332           << op->getSourceRange();
12333       else {
12334         SmallString<32> Str;
12335         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12336         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12337           << op->getSourceRange()
12338           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12339       }
12340     }
12341 
12342     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12343     if (isa<CXXDestructorDecl>(MD))
12344       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12345 
12346     QualType MPTy = Context.getMemberPointerType(
12347         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12348     // Under the MS ABI, lock down the inheritance model now.
12349     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12350       (void)isCompleteType(OpLoc, MPTy);
12351     return MPTy;
12352   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12353     // C99 6.5.3.2p1
12354     // The operand must be either an l-value or a function designator
12355     if (!op->getType()->isFunctionType()) {
12356       // Use a special diagnostic for loads from property references.
12357       if (isa<PseudoObjectExpr>(op)) {
12358         AddressOfError = AO_Property_Expansion;
12359       } else {
12360         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12361           << op->getType() << op->getSourceRange();
12362         return QualType();
12363       }
12364     }
12365   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12366     // The operand cannot be a bit-field
12367     AddressOfError = AO_Bit_Field;
12368   } else if (op->getObjectKind() == OK_VectorComponent) {
12369     // The operand cannot be an element of a vector
12370     AddressOfError = AO_Vector_Element;
12371   } else if (dcl) { // C99 6.5.3.2p1
12372     // We have an lvalue with a decl. Make sure the decl is not declared
12373     // with the register storage-class specifier.
12374     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12375       // in C++ it is not error to take address of a register
12376       // variable (c++03 7.1.1P3)
12377       if (vd->getStorageClass() == SC_Register &&
12378           !getLangOpts().CPlusPlus) {
12379         AddressOfError = AO_Register_Variable;
12380       }
12381     } else if (isa<MSPropertyDecl>(dcl)) {
12382       AddressOfError = AO_Property_Expansion;
12383     } else if (isa<FunctionTemplateDecl>(dcl)) {
12384       return Context.OverloadTy;
12385     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12386       // Okay: we can take the address of a field.
12387       // Could be a pointer to member, though, if there is an explicit
12388       // scope qualifier for the class.
12389       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12390         DeclContext *Ctx = dcl->getDeclContext();
12391         if (Ctx && Ctx->isRecord()) {
12392           if (dcl->getType()->isReferenceType()) {
12393             Diag(OpLoc,
12394                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12395               << dcl->getDeclName() << dcl->getType();
12396             return QualType();
12397           }
12398 
12399           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12400             Ctx = Ctx->getParent();
12401 
12402           QualType MPTy = Context.getMemberPointerType(
12403               op->getType(),
12404               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12405           // Under the MS ABI, lock down the inheritance model now.
12406           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12407             (void)isCompleteType(OpLoc, MPTy);
12408           return MPTy;
12409         }
12410       }
12411     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12412                !isa<BindingDecl>(dcl))
12413       llvm_unreachable("Unknown/unexpected decl type");
12414   }
12415 
12416   if (AddressOfError != AO_No_Error) {
12417     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12418     return QualType();
12419   }
12420 
12421   if (lval == Expr::LV_IncompleteVoidType) {
12422     // Taking the address of a void variable is technically illegal, but we
12423     // allow it in cases which are otherwise valid.
12424     // Example: "extern void x; void* y = &x;".
12425     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12426   }
12427 
12428   // If the operand has type "type", the result has type "pointer to type".
12429   if (op->getType()->isObjCObjectType())
12430     return Context.getObjCObjectPointerType(op->getType());
12431 
12432   CheckAddressOfPackedMember(op);
12433 
12434   return Context.getPointerType(op->getType());
12435 }
12436 
12437 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12438   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12439   if (!DRE)
12440     return;
12441   const Decl *D = DRE->getDecl();
12442   if (!D)
12443     return;
12444   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12445   if (!Param)
12446     return;
12447   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12448     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12449       return;
12450   if (FunctionScopeInfo *FD = S.getCurFunction())
12451     if (!FD->ModifiedNonNullParams.count(Param))
12452       FD->ModifiedNonNullParams.insert(Param);
12453 }
12454 
12455 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12456 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12457                                         SourceLocation OpLoc) {
12458   if (Op->isTypeDependent())
12459     return S.Context.DependentTy;
12460 
12461   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12462   if (ConvResult.isInvalid())
12463     return QualType();
12464   Op = ConvResult.get();
12465   QualType OpTy = Op->getType();
12466   QualType Result;
12467 
12468   if (isa<CXXReinterpretCastExpr>(Op)) {
12469     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12470     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12471                                      Op->getSourceRange());
12472   }
12473 
12474   if (const PointerType *PT = OpTy->getAs<PointerType>())
12475   {
12476     Result = PT->getPointeeType();
12477   }
12478   else if (const ObjCObjectPointerType *OPT =
12479              OpTy->getAs<ObjCObjectPointerType>())
12480     Result = OPT->getPointeeType();
12481   else {
12482     ExprResult PR = S.CheckPlaceholderExpr(Op);
12483     if (PR.isInvalid()) return QualType();
12484     if (PR.get() != Op)
12485       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12486   }
12487 
12488   if (Result.isNull()) {
12489     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12490       << OpTy << Op->getSourceRange();
12491     return QualType();
12492   }
12493 
12494   // Note that per both C89 and C99, indirection is always legal, even if Result
12495   // is an incomplete type or void.  It would be possible to warn about
12496   // dereferencing a void pointer, but it's completely well-defined, and such a
12497   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12498   // for pointers to 'void' but is fine for any other pointer type:
12499   //
12500   // C++ [expr.unary.op]p1:
12501   //   [...] the expression to which [the unary * operator] is applied shall
12502   //   be a pointer to an object type, or a pointer to a function type
12503   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12504     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12505       << OpTy << Op->getSourceRange();
12506 
12507   // Dereferences are usually l-values...
12508   VK = VK_LValue;
12509 
12510   // ...except that certain expressions are never l-values in C.
12511   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12512     VK = VK_RValue;
12513 
12514   return Result;
12515 }
12516 
12517 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12518   BinaryOperatorKind Opc;
12519   switch (Kind) {
12520   default: llvm_unreachable("Unknown binop!");
12521   case tok::periodstar:           Opc = BO_PtrMemD; break;
12522   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12523   case tok::star:                 Opc = BO_Mul; break;
12524   case tok::slash:                Opc = BO_Div; break;
12525   case tok::percent:              Opc = BO_Rem; break;
12526   case tok::plus:                 Opc = BO_Add; break;
12527   case tok::minus:                Opc = BO_Sub; break;
12528   case tok::lessless:             Opc = BO_Shl; break;
12529   case tok::greatergreater:       Opc = BO_Shr; break;
12530   case tok::lessequal:            Opc = BO_LE; break;
12531   case tok::less:                 Opc = BO_LT; break;
12532   case tok::greaterequal:         Opc = BO_GE; break;
12533   case tok::greater:              Opc = BO_GT; break;
12534   case tok::exclaimequal:         Opc = BO_NE; break;
12535   case tok::equalequal:           Opc = BO_EQ; break;
12536   case tok::spaceship:            Opc = BO_Cmp; break;
12537   case tok::amp:                  Opc = BO_And; break;
12538   case tok::caret:                Opc = BO_Xor; break;
12539   case tok::pipe:                 Opc = BO_Or; break;
12540   case tok::ampamp:               Opc = BO_LAnd; break;
12541   case tok::pipepipe:             Opc = BO_LOr; break;
12542   case tok::equal:                Opc = BO_Assign; break;
12543   case tok::starequal:            Opc = BO_MulAssign; break;
12544   case tok::slashequal:           Opc = BO_DivAssign; break;
12545   case tok::percentequal:         Opc = BO_RemAssign; break;
12546   case tok::plusequal:            Opc = BO_AddAssign; break;
12547   case tok::minusequal:           Opc = BO_SubAssign; break;
12548   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12549   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12550   case tok::ampequal:             Opc = BO_AndAssign; break;
12551   case tok::caretequal:           Opc = BO_XorAssign; break;
12552   case tok::pipeequal:            Opc = BO_OrAssign; break;
12553   case tok::comma:                Opc = BO_Comma; break;
12554   }
12555   return Opc;
12556 }
12557 
12558 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12559   tok::TokenKind Kind) {
12560   UnaryOperatorKind Opc;
12561   switch (Kind) {
12562   default: llvm_unreachable("Unknown unary op!");
12563   case tok::plusplus:     Opc = UO_PreInc; break;
12564   case tok::minusminus:   Opc = UO_PreDec; break;
12565   case tok::amp:          Opc = UO_AddrOf; break;
12566   case tok::star:         Opc = UO_Deref; break;
12567   case tok::plus:         Opc = UO_Plus; break;
12568   case tok::minus:        Opc = UO_Minus; break;
12569   case tok::tilde:        Opc = UO_Not; break;
12570   case tok::exclaim:      Opc = UO_LNot; break;
12571   case tok::kw___real:    Opc = UO_Real; break;
12572   case tok::kw___imag:    Opc = UO_Imag; break;
12573   case tok::kw___extension__: Opc = UO_Extension; break;
12574   }
12575   return Opc;
12576 }
12577 
12578 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12579 /// This warning suppressed in the event of macro expansions.
12580 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12581                                    SourceLocation OpLoc, bool IsBuiltin) {
12582   if (S.inTemplateInstantiation())
12583     return;
12584   if (S.isUnevaluatedContext())
12585     return;
12586   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12587     return;
12588   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12589   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12590   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12591   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12592   if (!LHSDeclRef || !RHSDeclRef ||
12593       LHSDeclRef->getLocation().isMacroID() ||
12594       RHSDeclRef->getLocation().isMacroID())
12595     return;
12596   const ValueDecl *LHSDecl =
12597     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12598   const ValueDecl *RHSDecl =
12599     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12600   if (LHSDecl != RHSDecl)
12601     return;
12602   if (LHSDecl->getType().isVolatileQualified())
12603     return;
12604   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12605     if (RefTy->getPointeeType().isVolatileQualified())
12606       return;
12607 
12608   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12609                           : diag::warn_self_assignment_overloaded)
12610       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12611       << RHSExpr->getSourceRange();
12612 }
12613 
12614 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12615 /// is usually indicative of introspection within the Objective-C pointer.
12616 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12617                                           SourceLocation OpLoc) {
12618   if (!S.getLangOpts().ObjC)
12619     return;
12620 
12621   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12622   const Expr *LHS = L.get();
12623   const Expr *RHS = R.get();
12624 
12625   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12626     ObjCPointerExpr = LHS;
12627     OtherExpr = RHS;
12628   }
12629   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12630     ObjCPointerExpr = RHS;
12631     OtherExpr = LHS;
12632   }
12633 
12634   // This warning is deliberately made very specific to reduce false
12635   // positives with logic that uses '&' for hashing.  This logic mainly
12636   // looks for code trying to introspect into tagged pointers, which
12637   // code should generally never do.
12638   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12639     unsigned Diag = diag::warn_objc_pointer_masking;
12640     // Determine if we are introspecting the result of performSelectorXXX.
12641     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12642     // Special case messages to -performSelector and friends, which
12643     // can return non-pointer values boxed in a pointer value.
12644     // Some clients may wish to silence warnings in this subcase.
12645     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12646       Selector S = ME->getSelector();
12647       StringRef SelArg0 = S.getNameForSlot(0);
12648       if (SelArg0.startswith("performSelector"))
12649         Diag = diag::warn_objc_pointer_masking_performSelector;
12650     }
12651 
12652     S.Diag(OpLoc, Diag)
12653       << ObjCPointerExpr->getSourceRange();
12654   }
12655 }
12656 
12657 static NamedDecl *getDeclFromExpr(Expr *E) {
12658   if (!E)
12659     return nullptr;
12660   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12661     return DRE->getDecl();
12662   if (auto *ME = dyn_cast<MemberExpr>(E))
12663     return ME->getMemberDecl();
12664   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12665     return IRE->getDecl();
12666   return nullptr;
12667 }
12668 
12669 // This helper function promotes a binary operator's operands (which are of a
12670 // half vector type) to a vector of floats and then truncates the result to
12671 // a vector of either half or short.
12672 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12673                                       BinaryOperatorKind Opc, QualType ResultTy,
12674                                       ExprValueKind VK, ExprObjectKind OK,
12675                                       bool IsCompAssign, SourceLocation OpLoc,
12676                                       FPOptions FPFeatures) {
12677   auto &Context = S.getASTContext();
12678   assert((isVector(ResultTy, Context.HalfTy) ||
12679           isVector(ResultTy, Context.ShortTy)) &&
12680          "Result must be a vector of half or short");
12681   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12682          isVector(RHS.get()->getType(), Context.HalfTy) &&
12683          "both operands expected to be a half vector");
12684 
12685   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12686   QualType BinOpResTy = RHS.get()->getType();
12687 
12688   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12689   // change BinOpResTy to a vector of ints.
12690   if (isVector(ResultTy, Context.ShortTy))
12691     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12692 
12693   if (IsCompAssign)
12694     return new (Context) CompoundAssignOperator(
12695         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12696         OpLoc, FPFeatures);
12697 
12698   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12699   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12700                                           VK, OK, OpLoc, FPFeatures);
12701   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12702 }
12703 
12704 static std::pair<ExprResult, ExprResult>
12705 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12706                            Expr *RHSExpr) {
12707   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12708   if (!S.getLangOpts().CPlusPlus) {
12709     // C cannot handle TypoExpr nodes on either side of a binop because it
12710     // doesn't handle dependent types properly, so make sure any TypoExprs have
12711     // been dealt with before checking the operands.
12712     LHS = S.CorrectDelayedTyposInExpr(LHS);
12713     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12714       if (Opc != BO_Assign)
12715         return ExprResult(E);
12716       // Avoid correcting the RHS to the same Expr as the LHS.
12717       Decl *D = getDeclFromExpr(E);
12718       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12719     });
12720   }
12721   return std::make_pair(LHS, RHS);
12722 }
12723 
12724 /// Returns true if conversion between vectors of halfs and vectors of floats
12725 /// is needed.
12726 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12727                                      QualType SrcType) {
12728   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12729          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12730          isVector(SrcType, Ctx.HalfTy);
12731 }
12732 
12733 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12734 /// operator @p Opc at location @c TokLoc. This routine only supports
12735 /// built-in operations; ActOnBinOp handles overloaded operators.
12736 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12737                                     BinaryOperatorKind Opc,
12738                                     Expr *LHSExpr, Expr *RHSExpr) {
12739   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12740     // The syntax only allows initializer lists on the RHS of assignment,
12741     // so we don't need to worry about accepting invalid code for
12742     // non-assignment operators.
12743     // C++11 5.17p9:
12744     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12745     //   of x = {} is x = T().
12746     InitializationKind Kind = InitializationKind::CreateDirectList(
12747         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12748     InitializedEntity Entity =
12749         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12750     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12751     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12752     if (Init.isInvalid())
12753       return Init;
12754     RHSExpr = Init.get();
12755   }
12756 
12757   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12758   QualType ResultTy;     // Result type of the binary operator.
12759   // The following two variables are used for compound assignment operators
12760   QualType CompLHSTy;    // Type of LHS after promotions for computation
12761   QualType CompResultTy; // Type of computation result
12762   ExprValueKind VK = VK_RValue;
12763   ExprObjectKind OK = OK_Ordinary;
12764   bool ConvertHalfVec = false;
12765 
12766   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12767   if (!LHS.isUsable() || !RHS.isUsable())
12768     return ExprError();
12769 
12770   if (getLangOpts().OpenCL) {
12771     QualType LHSTy = LHSExpr->getType();
12772     QualType RHSTy = RHSExpr->getType();
12773     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12774     // the ATOMIC_VAR_INIT macro.
12775     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12776       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12777       if (BO_Assign == Opc)
12778         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12779       else
12780         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12781       return ExprError();
12782     }
12783 
12784     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12785     // only with a builtin functions and therefore should be disallowed here.
12786     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12787         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12788         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12789         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12790       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12791       return ExprError();
12792     }
12793   }
12794 
12795   // Diagnose operations on the unsupported types for OpenMP device compilation.
12796   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12797     if (Opc != BO_Assign && Opc != BO_Comma) {
12798       checkOpenMPDeviceExpr(LHSExpr);
12799       checkOpenMPDeviceExpr(RHSExpr);
12800     }
12801   }
12802 
12803   switch (Opc) {
12804   case BO_Assign:
12805     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12806     if (getLangOpts().CPlusPlus &&
12807         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12808       VK = LHS.get()->getValueKind();
12809       OK = LHS.get()->getObjectKind();
12810     }
12811     if (!ResultTy.isNull()) {
12812       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12813       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12814 
12815       // Avoid copying a block to the heap if the block is assigned to a local
12816       // auto variable that is declared in the same scope as the block. This
12817       // optimization is unsafe if the local variable is declared in an outer
12818       // scope. For example:
12819       //
12820       // BlockTy b;
12821       // {
12822       //   b = ^{...};
12823       // }
12824       // // It is unsafe to invoke the block here if it wasn't copied to the
12825       // // heap.
12826       // b();
12827 
12828       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12829         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12830           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12831             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12832               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12833 
12834       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
12835         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
12836                               NTCUC_Assignment, NTCUK_Copy);
12837     }
12838     RecordModifiableNonNullParam(*this, LHS.get());
12839     break;
12840   case BO_PtrMemD:
12841   case BO_PtrMemI:
12842     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12843                                             Opc == BO_PtrMemI);
12844     break;
12845   case BO_Mul:
12846   case BO_Div:
12847     ConvertHalfVec = true;
12848     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12849                                            Opc == BO_Div);
12850     break;
12851   case BO_Rem:
12852     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12853     break;
12854   case BO_Add:
12855     ConvertHalfVec = true;
12856     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12857     break;
12858   case BO_Sub:
12859     ConvertHalfVec = true;
12860     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12861     break;
12862   case BO_Shl:
12863   case BO_Shr:
12864     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12865     break;
12866   case BO_LE:
12867   case BO_LT:
12868   case BO_GE:
12869   case BO_GT:
12870     ConvertHalfVec = true;
12871     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12872     break;
12873   case BO_EQ:
12874   case BO_NE:
12875     ConvertHalfVec = true;
12876     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12877     break;
12878   case BO_Cmp:
12879     ConvertHalfVec = true;
12880     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12881     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12882     break;
12883   case BO_And:
12884     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12885     LLVM_FALLTHROUGH;
12886   case BO_Xor:
12887   case BO_Or:
12888     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12889     break;
12890   case BO_LAnd:
12891   case BO_LOr:
12892     ConvertHalfVec = true;
12893     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12894     break;
12895   case BO_MulAssign:
12896   case BO_DivAssign:
12897     ConvertHalfVec = true;
12898     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12899                                                Opc == BO_DivAssign);
12900     CompLHSTy = CompResultTy;
12901     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12902       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12903     break;
12904   case BO_RemAssign:
12905     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12906     CompLHSTy = CompResultTy;
12907     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12908       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12909     break;
12910   case BO_AddAssign:
12911     ConvertHalfVec = true;
12912     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12913     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12914       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12915     break;
12916   case BO_SubAssign:
12917     ConvertHalfVec = true;
12918     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12919     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12920       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12921     break;
12922   case BO_ShlAssign:
12923   case BO_ShrAssign:
12924     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12925     CompLHSTy = CompResultTy;
12926     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12927       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12928     break;
12929   case BO_AndAssign:
12930   case BO_OrAssign: // fallthrough
12931     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12932     LLVM_FALLTHROUGH;
12933   case BO_XorAssign:
12934     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12935     CompLHSTy = CompResultTy;
12936     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12937       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12938     break;
12939   case BO_Comma:
12940     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12941     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12942       VK = RHS.get()->getValueKind();
12943       OK = RHS.get()->getObjectKind();
12944     }
12945     break;
12946   }
12947   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12948     return ExprError();
12949 
12950   // Some of the binary operations require promoting operands of half vector to
12951   // float vectors and truncating the result back to half vector. For now, we do
12952   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12953   // arm64).
12954   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12955          isVector(LHS.get()->getType(), Context.HalfTy) &&
12956          "both sides are half vectors or neither sides are");
12957   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12958                                             LHS.get()->getType());
12959 
12960   // Check for array bounds violations for both sides of the BinaryOperator
12961   CheckArrayAccess(LHS.get());
12962   CheckArrayAccess(RHS.get());
12963 
12964   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12965     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12966                                                  &Context.Idents.get("object_setClass"),
12967                                                  SourceLocation(), LookupOrdinaryName);
12968     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12969       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12970       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12971           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12972                                         "object_setClass(")
12973           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12974                                           ",")
12975           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12976     }
12977     else
12978       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12979   }
12980   else if (const ObjCIvarRefExpr *OIRE =
12981            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12982     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12983 
12984   // Opc is not a compound assignment if CompResultTy is null.
12985   if (CompResultTy.isNull()) {
12986     if (ConvertHalfVec)
12987       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12988                                  OpLoc, FPFeatures);
12989     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12990                                         OK, OpLoc, FPFeatures);
12991   }
12992 
12993   // Handle compound assignments.
12994   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12995       OK_ObjCProperty) {
12996     VK = VK_LValue;
12997     OK = LHS.get()->getObjectKind();
12998   }
12999 
13000   if (ConvertHalfVec)
13001     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13002                                OpLoc, FPFeatures);
13003 
13004   return new (Context) CompoundAssignOperator(
13005       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13006       OpLoc, FPFeatures);
13007 }
13008 
13009 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13010 /// operators are mixed in a way that suggests that the programmer forgot that
13011 /// comparison operators have higher precedence. The most typical example of
13012 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13013 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13014                                       SourceLocation OpLoc, Expr *LHSExpr,
13015                                       Expr *RHSExpr) {
13016   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13017   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13018 
13019   // Check that one of the sides is a comparison operator and the other isn't.
13020   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13021   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13022   if (isLeftComp == isRightComp)
13023     return;
13024 
13025   // Bitwise operations are sometimes used as eager logical ops.
13026   // Don't diagnose this.
13027   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13028   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13029   if (isLeftBitwise || isRightBitwise)
13030     return;
13031 
13032   SourceRange DiagRange = isLeftComp
13033                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13034                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13035   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13036   SourceRange ParensRange =
13037       isLeftComp
13038           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13039           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13040 
13041   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13042     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13043   SuggestParentheses(Self, OpLoc,
13044     Self.PDiag(diag::note_precedence_silence) << OpStr,
13045     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13046   SuggestParentheses(Self, OpLoc,
13047     Self.PDiag(diag::note_precedence_bitwise_first)
13048       << BinaryOperator::getOpcodeStr(Opc),
13049     ParensRange);
13050 }
13051 
13052 /// It accepts a '&&' expr that is inside a '||' one.
13053 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13054 /// in parentheses.
13055 static void
13056 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13057                                        BinaryOperator *Bop) {
13058   assert(Bop->getOpcode() == BO_LAnd);
13059   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13060       << Bop->getSourceRange() << OpLoc;
13061   SuggestParentheses(Self, Bop->getOperatorLoc(),
13062     Self.PDiag(diag::note_precedence_silence)
13063       << Bop->getOpcodeStr(),
13064     Bop->getSourceRange());
13065 }
13066 
13067 /// Returns true if the given expression can be evaluated as a constant
13068 /// 'true'.
13069 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13070   bool Res;
13071   return !E->isValueDependent() &&
13072          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13073 }
13074 
13075 /// Returns true if the given expression can be evaluated as a constant
13076 /// 'false'.
13077 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13078   bool Res;
13079   return !E->isValueDependent() &&
13080          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13081 }
13082 
13083 /// Look for '&&' in the left hand of a '||' expr.
13084 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13085                                              Expr *LHSExpr, Expr *RHSExpr) {
13086   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13087     if (Bop->getOpcode() == BO_LAnd) {
13088       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13089       if (EvaluatesAsFalse(S, RHSExpr))
13090         return;
13091       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13092       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13093         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13094     } else if (Bop->getOpcode() == BO_LOr) {
13095       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13096         // If it's "a || b && 1 || c" we didn't warn earlier for
13097         // "a || b && 1", but warn now.
13098         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13099           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13100       }
13101     }
13102   }
13103 }
13104 
13105 /// Look for '&&' in the right hand of a '||' expr.
13106 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13107                                              Expr *LHSExpr, Expr *RHSExpr) {
13108   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13109     if (Bop->getOpcode() == BO_LAnd) {
13110       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13111       if (EvaluatesAsFalse(S, LHSExpr))
13112         return;
13113       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13114       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13115         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13116     }
13117   }
13118 }
13119 
13120 /// Look for bitwise op in the left or right hand of a bitwise op with
13121 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13122 /// the '&' expression in parentheses.
13123 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13124                                          SourceLocation OpLoc, Expr *SubExpr) {
13125   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13126     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13127       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13128         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13129         << Bop->getSourceRange() << OpLoc;
13130       SuggestParentheses(S, Bop->getOperatorLoc(),
13131         S.PDiag(diag::note_precedence_silence)
13132           << Bop->getOpcodeStr(),
13133         Bop->getSourceRange());
13134     }
13135   }
13136 }
13137 
13138 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13139                                     Expr *SubExpr, StringRef Shift) {
13140   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13141     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13142       StringRef Op = Bop->getOpcodeStr();
13143       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13144           << Bop->getSourceRange() << OpLoc << Shift << Op;
13145       SuggestParentheses(S, Bop->getOperatorLoc(),
13146           S.PDiag(diag::note_precedence_silence) << Op,
13147           Bop->getSourceRange());
13148     }
13149   }
13150 }
13151 
13152 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13153                                  Expr *LHSExpr, Expr *RHSExpr) {
13154   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13155   if (!OCE)
13156     return;
13157 
13158   FunctionDecl *FD = OCE->getDirectCallee();
13159   if (!FD || !FD->isOverloadedOperator())
13160     return;
13161 
13162   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13163   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13164     return;
13165 
13166   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13167       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13168       << (Kind == OO_LessLess);
13169   SuggestParentheses(S, OCE->getOperatorLoc(),
13170                      S.PDiag(diag::note_precedence_silence)
13171                          << (Kind == OO_LessLess ? "<<" : ">>"),
13172                      OCE->getSourceRange());
13173   SuggestParentheses(
13174       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13175       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13176 }
13177 
13178 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13179 /// precedence.
13180 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13181                                     SourceLocation OpLoc, Expr *LHSExpr,
13182                                     Expr *RHSExpr){
13183   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13184   if (BinaryOperator::isBitwiseOp(Opc))
13185     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13186 
13187   // Diagnose "arg1 & arg2 | arg3"
13188   if ((Opc == BO_Or || Opc == BO_Xor) &&
13189       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13190     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13191     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13192   }
13193 
13194   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13195   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13196   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13197     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13198     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13199   }
13200 
13201   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13202       || Opc == BO_Shr) {
13203     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13204     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13205     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13206   }
13207 
13208   // Warn on overloaded shift operators and comparisons, such as:
13209   // cout << 5 == 4;
13210   if (BinaryOperator::isComparisonOp(Opc))
13211     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13212 }
13213 
13214 // Binary Operators.  'Tok' is the token for the operator.
13215 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13216                             tok::TokenKind Kind,
13217                             Expr *LHSExpr, Expr *RHSExpr) {
13218   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13219   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13220   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13221 
13222   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13223   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13224 
13225   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13226 }
13227 
13228 /// Build an overloaded binary operator expression in the given scope.
13229 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13230                                        BinaryOperatorKind Opc,
13231                                        Expr *LHS, Expr *RHS) {
13232   switch (Opc) {
13233   case BO_Assign:
13234   case BO_DivAssign:
13235   case BO_RemAssign:
13236   case BO_SubAssign:
13237   case BO_AndAssign:
13238   case BO_OrAssign:
13239   case BO_XorAssign:
13240     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13241     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13242     break;
13243   default:
13244     break;
13245   }
13246 
13247   // Find all of the overloaded operators visible from this
13248   // point. We perform both an operator-name lookup from the local
13249   // scope and an argument-dependent lookup based on the types of
13250   // the arguments.
13251   UnresolvedSet<16> Functions;
13252   OverloadedOperatorKind OverOp
13253     = BinaryOperator::getOverloadedOperator(Opc);
13254   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13255     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13256                                    RHS->getType(), Functions);
13257 
13258   // Build the (potentially-overloaded, potentially-dependent)
13259   // binary operation.
13260   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13261 }
13262 
13263 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13264                             BinaryOperatorKind Opc,
13265                             Expr *LHSExpr, Expr *RHSExpr) {
13266   ExprResult LHS, RHS;
13267   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13268   if (!LHS.isUsable() || !RHS.isUsable())
13269     return ExprError();
13270   LHSExpr = LHS.get();
13271   RHSExpr = RHS.get();
13272 
13273   // We want to end up calling one of checkPseudoObjectAssignment
13274   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13275   // both expressions are overloadable or either is type-dependent),
13276   // or CreateBuiltinBinOp (in any other case).  We also want to get
13277   // any placeholder types out of the way.
13278 
13279   // Handle pseudo-objects in the LHS.
13280   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13281     // Assignments with a pseudo-object l-value need special analysis.
13282     if (pty->getKind() == BuiltinType::PseudoObject &&
13283         BinaryOperator::isAssignmentOp(Opc))
13284       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13285 
13286     // Don't resolve overloads if the other type is overloadable.
13287     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13288       // We can't actually test that if we still have a placeholder,
13289       // though.  Fortunately, none of the exceptions we see in that
13290       // code below are valid when the LHS is an overload set.  Note
13291       // that an overload set can be dependently-typed, but it never
13292       // instantiates to having an overloadable type.
13293       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13294       if (resolvedRHS.isInvalid()) return ExprError();
13295       RHSExpr = resolvedRHS.get();
13296 
13297       if (RHSExpr->isTypeDependent() ||
13298           RHSExpr->getType()->isOverloadableType())
13299         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13300     }
13301 
13302     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13303     // template, diagnose the missing 'template' keyword instead of diagnosing
13304     // an invalid use of a bound member function.
13305     //
13306     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13307     // to C++1z [over.over]/1.4, but we already checked for that case above.
13308     if (Opc == BO_LT && inTemplateInstantiation() &&
13309         (pty->getKind() == BuiltinType::BoundMember ||
13310          pty->getKind() == BuiltinType::Overload)) {
13311       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13312       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13313           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13314             return isa<FunctionTemplateDecl>(ND);
13315           })) {
13316         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13317                                 : OE->getNameLoc(),
13318              diag::err_template_kw_missing)
13319           << OE->getName().getAsString() << "";
13320         return ExprError();
13321       }
13322     }
13323 
13324     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13325     if (LHS.isInvalid()) return ExprError();
13326     LHSExpr = LHS.get();
13327   }
13328 
13329   // Handle pseudo-objects in the RHS.
13330   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13331     // An overload in the RHS can potentially be resolved by the type
13332     // being assigned to.
13333     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13334       if (getLangOpts().CPlusPlus &&
13335           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13336            LHSExpr->getType()->isOverloadableType()))
13337         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13338 
13339       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13340     }
13341 
13342     // Don't resolve overloads if the other type is overloadable.
13343     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13344         LHSExpr->getType()->isOverloadableType())
13345       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13346 
13347     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13348     if (!resolvedRHS.isUsable()) return ExprError();
13349     RHSExpr = resolvedRHS.get();
13350   }
13351 
13352   if (getLangOpts().CPlusPlus) {
13353     // If either expression is type-dependent, always build an
13354     // overloaded op.
13355     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13356       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13357 
13358     // Otherwise, build an overloaded op if either expression has an
13359     // overloadable type.
13360     if (LHSExpr->getType()->isOverloadableType() ||
13361         RHSExpr->getType()->isOverloadableType())
13362       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13363   }
13364 
13365   // Build a built-in binary operation.
13366   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13367 }
13368 
13369 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13370   if (T.isNull() || T->isDependentType())
13371     return false;
13372 
13373   if (!T->isPromotableIntegerType())
13374     return true;
13375 
13376   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13377 }
13378 
13379 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13380                                       UnaryOperatorKind Opc,
13381                                       Expr *InputExpr) {
13382   ExprResult Input = InputExpr;
13383   ExprValueKind VK = VK_RValue;
13384   ExprObjectKind OK = OK_Ordinary;
13385   QualType resultType;
13386   bool CanOverflow = false;
13387 
13388   bool ConvertHalfVec = false;
13389   if (getLangOpts().OpenCL) {
13390     QualType Ty = InputExpr->getType();
13391     // The only legal unary operation for atomics is '&'.
13392     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13393     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13394     // only with a builtin functions and therefore should be disallowed here.
13395         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13396         || Ty->isBlockPointerType())) {
13397       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13398                        << InputExpr->getType()
13399                        << Input.get()->getSourceRange());
13400     }
13401   }
13402   // Diagnose operations on the unsupported types for OpenMP device compilation.
13403   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13404     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13405         UnaryOperator::isArithmeticOp(Opc))
13406       checkOpenMPDeviceExpr(InputExpr);
13407   }
13408 
13409   switch (Opc) {
13410   case UO_PreInc:
13411   case UO_PreDec:
13412   case UO_PostInc:
13413   case UO_PostDec:
13414     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13415                                                 OpLoc,
13416                                                 Opc == UO_PreInc ||
13417                                                 Opc == UO_PostInc,
13418                                                 Opc == UO_PreInc ||
13419                                                 Opc == UO_PreDec);
13420     CanOverflow = isOverflowingIntegerType(Context, resultType);
13421     break;
13422   case UO_AddrOf:
13423     resultType = CheckAddressOfOperand(Input, OpLoc);
13424     CheckAddressOfNoDeref(InputExpr);
13425     RecordModifiableNonNullParam(*this, InputExpr);
13426     break;
13427   case UO_Deref: {
13428     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13429     if (Input.isInvalid()) return ExprError();
13430     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13431     break;
13432   }
13433   case UO_Plus:
13434   case UO_Minus:
13435     CanOverflow = Opc == UO_Minus &&
13436                   isOverflowingIntegerType(Context, Input.get()->getType());
13437     Input = UsualUnaryConversions(Input.get());
13438     if (Input.isInvalid()) return ExprError();
13439     // Unary plus and minus require promoting an operand of half vector to a
13440     // float vector and truncating the result back to a half vector. For now, we
13441     // do this only when HalfArgsAndReturns is set (that is, when the target is
13442     // arm or arm64).
13443     ConvertHalfVec =
13444         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13445 
13446     // If the operand is a half vector, promote it to a float vector.
13447     if (ConvertHalfVec)
13448       Input = convertVector(Input.get(), Context.FloatTy, *this);
13449     resultType = Input.get()->getType();
13450     if (resultType->isDependentType())
13451       break;
13452     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13453       break;
13454     else if (resultType->isVectorType() &&
13455              // The z vector extensions don't allow + or - with bool vectors.
13456              (!Context.getLangOpts().ZVector ||
13457               resultType->castAs<VectorType>()->getVectorKind() !=
13458               VectorType::AltiVecBool))
13459       break;
13460     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13461              Opc == UO_Plus &&
13462              resultType->isPointerType())
13463       break;
13464 
13465     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13466       << resultType << Input.get()->getSourceRange());
13467 
13468   case UO_Not: // bitwise complement
13469     Input = UsualUnaryConversions(Input.get());
13470     if (Input.isInvalid())
13471       return ExprError();
13472     resultType = Input.get()->getType();
13473 
13474     if (resultType->isDependentType())
13475       break;
13476     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13477     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13478       // C99 does not support '~' for complex conjugation.
13479       Diag(OpLoc, diag::ext_integer_complement_complex)
13480           << resultType << Input.get()->getSourceRange();
13481     else if (resultType->hasIntegerRepresentation())
13482       break;
13483     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13484       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13485       // on vector float types.
13486       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13487       if (!T->isIntegerType())
13488         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13489                           << resultType << Input.get()->getSourceRange());
13490     } else {
13491       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13492                        << resultType << Input.get()->getSourceRange());
13493     }
13494     break;
13495 
13496   case UO_LNot: // logical negation
13497     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13498     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13499     if (Input.isInvalid()) return ExprError();
13500     resultType = Input.get()->getType();
13501 
13502     // Though we still have to promote half FP to float...
13503     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13504       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13505       resultType = Context.FloatTy;
13506     }
13507 
13508     if (resultType->isDependentType())
13509       break;
13510     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13511       // C99 6.5.3.3p1: ok, fallthrough;
13512       if (Context.getLangOpts().CPlusPlus) {
13513         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13514         // operand contextually converted to bool.
13515         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13516                                   ScalarTypeToBooleanCastKind(resultType));
13517       } else if (Context.getLangOpts().OpenCL &&
13518                  Context.getLangOpts().OpenCLVersion < 120) {
13519         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13520         // operate on scalar float types.
13521         if (!resultType->isIntegerType() && !resultType->isPointerType())
13522           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13523                            << resultType << Input.get()->getSourceRange());
13524       }
13525     } else if (resultType->isExtVectorType()) {
13526       if (Context.getLangOpts().OpenCL &&
13527           Context.getLangOpts().OpenCLVersion < 120 &&
13528           !Context.getLangOpts().OpenCLCPlusPlus) {
13529         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13530         // operate on vector float types.
13531         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13532         if (!T->isIntegerType())
13533           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13534                            << resultType << Input.get()->getSourceRange());
13535       }
13536       // Vector logical not returns the signed variant of the operand type.
13537       resultType = GetSignedVectorType(resultType);
13538       break;
13539     } else {
13540       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13541       //        type in C++. We should allow that here too.
13542       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13543         << resultType << Input.get()->getSourceRange());
13544     }
13545 
13546     // LNot always has type int. C99 6.5.3.3p5.
13547     // In C++, it's bool. C++ 5.3.1p8
13548     resultType = Context.getLogicalOperationType();
13549     break;
13550   case UO_Real:
13551   case UO_Imag:
13552     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13553     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13554     // complex l-values to ordinary l-values and all other values to r-values.
13555     if (Input.isInvalid()) return ExprError();
13556     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13557       if (Input.get()->getValueKind() != VK_RValue &&
13558           Input.get()->getObjectKind() == OK_Ordinary)
13559         VK = Input.get()->getValueKind();
13560     } else if (!getLangOpts().CPlusPlus) {
13561       // In C, a volatile scalar is read by __imag. In C++, it is not.
13562       Input = DefaultLvalueConversion(Input.get());
13563     }
13564     break;
13565   case UO_Extension:
13566     resultType = Input.get()->getType();
13567     VK = Input.get()->getValueKind();
13568     OK = Input.get()->getObjectKind();
13569     break;
13570   case UO_Coawait:
13571     // It's unnecessary to represent the pass-through operator co_await in the
13572     // AST; just return the input expression instead.
13573     assert(!Input.get()->getType()->isDependentType() &&
13574                    "the co_await expression must be non-dependant before "
13575                    "building operator co_await");
13576     return Input;
13577   }
13578   if (resultType.isNull() || Input.isInvalid())
13579     return ExprError();
13580 
13581   // Check for array bounds violations in the operand of the UnaryOperator,
13582   // except for the '*' and '&' operators that have to be handled specially
13583   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13584   // that are explicitly defined as valid by the standard).
13585   if (Opc != UO_AddrOf && Opc != UO_Deref)
13586     CheckArrayAccess(Input.get());
13587 
13588   auto *UO = new (Context)
13589       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13590 
13591   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13592       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13593     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13594 
13595   // Convert the result back to a half vector.
13596   if (ConvertHalfVec)
13597     return convertVector(UO, Context.HalfTy, *this);
13598   return UO;
13599 }
13600 
13601 /// Determine whether the given expression is a qualified member
13602 /// access expression, of a form that could be turned into a pointer to member
13603 /// with the address-of operator.
13604 bool Sema::isQualifiedMemberAccess(Expr *E) {
13605   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13606     if (!DRE->getQualifier())
13607       return false;
13608 
13609     ValueDecl *VD = DRE->getDecl();
13610     if (!VD->isCXXClassMember())
13611       return false;
13612 
13613     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13614       return true;
13615     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13616       return Method->isInstance();
13617 
13618     return false;
13619   }
13620 
13621   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13622     if (!ULE->getQualifier())
13623       return false;
13624 
13625     for (NamedDecl *D : ULE->decls()) {
13626       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13627         if (Method->isInstance())
13628           return true;
13629       } else {
13630         // Overload set does not contain methods.
13631         break;
13632       }
13633     }
13634 
13635     return false;
13636   }
13637 
13638   return false;
13639 }
13640 
13641 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13642                               UnaryOperatorKind Opc, Expr *Input) {
13643   // First things first: handle placeholders so that the
13644   // overloaded-operator check considers the right type.
13645   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13646     // Increment and decrement of pseudo-object references.
13647     if (pty->getKind() == BuiltinType::PseudoObject &&
13648         UnaryOperator::isIncrementDecrementOp(Opc))
13649       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13650 
13651     // extension is always a builtin operator.
13652     if (Opc == UO_Extension)
13653       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13654 
13655     // & gets special logic for several kinds of placeholder.
13656     // The builtin code knows what to do.
13657     if (Opc == UO_AddrOf &&
13658         (pty->getKind() == BuiltinType::Overload ||
13659          pty->getKind() == BuiltinType::UnknownAny ||
13660          pty->getKind() == BuiltinType::BoundMember))
13661       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13662 
13663     // Anything else needs to be handled now.
13664     ExprResult Result = CheckPlaceholderExpr(Input);
13665     if (Result.isInvalid()) return ExprError();
13666     Input = Result.get();
13667   }
13668 
13669   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13670       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13671       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13672     // Find all of the overloaded operators visible from this
13673     // point. We perform both an operator-name lookup from the local
13674     // scope and an argument-dependent lookup based on the types of
13675     // the arguments.
13676     UnresolvedSet<16> Functions;
13677     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13678     if (S && OverOp != OO_None)
13679       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13680                                    Functions);
13681 
13682     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13683   }
13684 
13685   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13686 }
13687 
13688 // Unary Operators.  'Tok' is the token for the operator.
13689 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13690                               tok::TokenKind Op, Expr *Input) {
13691   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13692 }
13693 
13694 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13695 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13696                                 LabelDecl *TheDecl) {
13697   TheDecl->markUsed(Context);
13698   // Create the AST node.  The address of a label always has type 'void*'.
13699   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13700                                      Context.getPointerType(Context.VoidTy));
13701 }
13702 
13703 void Sema::ActOnStartStmtExpr() {
13704   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13705 }
13706 
13707 void Sema::ActOnStmtExprError() {
13708   // Note that function is also called by TreeTransform when leaving a
13709   // StmtExpr scope without rebuilding anything.
13710 
13711   DiscardCleanupsInEvaluationContext();
13712   PopExpressionEvaluationContext();
13713 }
13714 
13715 ExprResult
13716 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13717                     SourceLocation RPLoc) { // "({..})"
13718   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13719   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13720 
13721   if (hasAnyUnrecoverableErrorsInThisFunction())
13722     DiscardCleanupsInEvaluationContext();
13723   assert(!Cleanup.exprNeedsCleanups() &&
13724          "cleanups within StmtExpr not correctly bound!");
13725   PopExpressionEvaluationContext();
13726 
13727   // FIXME: there are a variety of strange constraints to enforce here, for
13728   // example, it is not possible to goto into a stmt expression apparently.
13729   // More semantic analysis is needed.
13730 
13731   // If there are sub-stmts in the compound stmt, take the type of the last one
13732   // as the type of the stmtexpr.
13733   QualType Ty = Context.VoidTy;
13734   bool StmtExprMayBindToTemp = false;
13735   if (!Compound->body_empty()) {
13736     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13737     if (const auto *LastStmt =
13738             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13739       if (const Expr *Value = LastStmt->getExprStmt()) {
13740         StmtExprMayBindToTemp = true;
13741         Ty = Value->getType();
13742       }
13743     }
13744   }
13745 
13746   // FIXME: Check that expression type is complete/non-abstract; statement
13747   // expressions are not lvalues.
13748   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13749   if (StmtExprMayBindToTemp)
13750     return MaybeBindToTemporary(ResStmtExpr);
13751   return ResStmtExpr;
13752 }
13753 
13754 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13755   if (ER.isInvalid())
13756     return ExprError();
13757 
13758   // Do function/array conversion on the last expression, but not
13759   // lvalue-to-rvalue.  However, initialize an unqualified type.
13760   ER = DefaultFunctionArrayConversion(ER.get());
13761   if (ER.isInvalid())
13762     return ExprError();
13763   Expr *E = ER.get();
13764 
13765   if (E->isTypeDependent())
13766     return E;
13767 
13768   // In ARC, if the final expression ends in a consume, splice
13769   // the consume out and bind it later.  In the alternate case
13770   // (when dealing with a retainable type), the result
13771   // initialization will create a produce.  In both cases the
13772   // result will be +1, and we'll need to balance that out with
13773   // a bind.
13774   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13775   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13776     return Cast->getSubExpr();
13777 
13778   // FIXME: Provide a better location for the initialization.
13779   return PerformCopyInitialization(
13780       InitializedEntity::InitializeStmtExprResult(
13781           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13782       SourceLocation(), E);
13783 }
13784 
13785 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13786                                       TypeSourceInfo *TInfo,
13787                                       ArrayRef<OffsetOfComponent> Components,
13788                                       SourceLocation RParenLoc) {
13789   QualType ArgTy = TInfo->getType();
13790   bool Dependent = ArgTy->isDependentType();
13791   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13792 
13793   // We must have at least one component that refers to the type, and the first
13794   // one is known to be a field designator.  Verify that the ArgTy represents
13795   // a struct/union/class.
13796   if (!Dependent && !ArgTy->isRecordType())
13797     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13798                        << ArgTy << TypeRange);
13799 
13800   // Type must be complete per C99 7.17p3 because a declaring a variable
13801   // with an incomplete type would be ill-formed.
13802   if (!Dependent
13803       && RequireCompleteType(BuiltinLoc, ArgTy,
13804                              diag::err_offsetof_incomplete_type, TypeRange))
13805     return ExprError();
13806 
13807   bool DidWarnAboutNonPOD = false;
13808   QualType CurrentType = ArgTy;
13809   SmallVector<OffsetOfNode, 4> Comps;
13810   SmallVector<Expr*, 4> Exprs;
13811   for (const OffsetOfComponent &OC : Components) {
13812     if (OC.isBrackets) {
13813       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13814       if (!CurrentType->isDependentType()) {
13815         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13816         if(!AT)
13817           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13818                            << CurrentType);
13819         CurrentType = AT->getElementType();
13820       } else
13821         CurrentType = Context.DependentTy;
13822 
13823       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13824       if (IdxRval.isInvalid())
13825         return ExprError();
13826       Expr *Idx = IdxRval.get();
13827 
13828       // The expression must be an integral expression.
13829       // FIXME: An integral constant expression?
13830       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13831           !Idx->getType()->isIntegerType())
13832         return ExprError(
13833             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13834             << Idx->getSourceRange());
13835 
13836       // Record this array index.
13837       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13838       Exprs.push_back(Idx);
13839       continue;
13840     }
13841 
13842     // Offset of a field.
13843     if (CurrentType->isDependentType()) {
13844       // We have the offset of a field, but we can't look into the dependent
13845       // type. Just record the identifier of the field.
13846       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13847       CurrentType = Context.DependentTy;
13848       continue;
13849     }
13850 
13851     // We need to have a complete type to look into.
13852     if (RequireCompleteType(OC.LocStart, CurrentType,
13853                             diag::err_offsetof_incomplete_type))
13854       return ExprError();
13855 
13856     // Look for the designated field.
13857     const RecordType *RC = CurrentType->getAs<RecordType>();
13858     if (!RC)
13859       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13860                        << CurrentType);
13861     RecordDecl *RD = RC->getDecl();
13862 
13863     // C++ [lib.support.types]p5:
13864     //   The macro offsetof accepts a restricted set of type arguments in this
13865     //   International Standard. type shall be a POD structure or a POD union
13866     //   (clause 9).
13867     // C++11 [support.types]p4:
13868     //   If type is not a standard-layout class (Clause 9), the results are
13869     //   undefined.
13870     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13871       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13872       unsigned DiagID =
13873         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13874                             : diag::ext_offsetof_non_pod_type;
13875 
13876       if (!IsSafe && !DidWarnAboutNonPOD &&
13877           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13878                               PDiag(DiagID)
13879                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13880                               << CurrentType))
13881         DidWarnAboutNonPOD = true;
13882     }
13883 
13884     // Look for the field.
13885     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13886     LookupQualifiedName(R, RD);
13887     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13888     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13889     if (!MemberDecl) {
13890       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13891         MemberDecl = IndirectMemberDecl->getAnonField();
13892     }
13893 
13894     if (!MemberDecl)
13895       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13896                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13897                                                               OC.LocEnd));
13898 
13899     // C99 7.17p3:
13900     //   (If the specified member is a bit-field, the behavior is undefined.)
13901     //
13902     // We diagnose this as an error.
13903     if (MemberDecl->isBitField()) {
13904       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13905         << MemberDecl->getDeclName()
13906         << SourceRange(BuiltinLoc, RParenLoc);
13907       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13908       return ExprError();
13909     }
13910 
13911     RecordDecl *Parent = MemberDecl->getParent();
13912     if (IndirectMemberDecl)
13913       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13914 
13915     // If the member was found in a base class, introduce OffsetOfNodes for
13916     // the base class indirections.
13917     CXXBasePaths Paths;
13918     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13919                       Paths)) {
13920       if (Paths.getDetectedVirtual()) {
13921         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13922           << MemberDecl->getDeclName()
13923           << SourceRange(BuiltinLoc, RParenLoc);
13924         return ExprError();
13925       }
13926 
13927       CXXBasePath &Path = Paths.front();
13928       for (const CXXBasePathElement &B : Path)
13929         Comps.push_back(OffsetOfNode(B.Base));
13930     }
13931 
13932     if (IndirectMemberDecl) {
13933       for (auto *FI : IndirectMemberDecl->chain()) {
13934         assert(isa<FieldDecl>(FI));
13935         Comps.push_back(OffsetOfNode(OC.LocStart,
13936                                      cast<FieldDecl>(FI), OC.LocEnd));
13937       }
13938     } else
13939       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13940 
13941     CurrentType = MemberDecl->getType().getNonReferenceType();
13942   }
13943 
13944   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13945                               Comps, Exprs, RParenLoc);
13946 }
13947 
13948 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13949                                       SourceLocation BuiltinLoc,
13950                                       SourceLocation TypeLoc,
13951                                       ParsedType ParsedArgTy,
13952                                       ArrayRef<OffsetOfComponent> Components,
13953                                       SourceLocation RParenLoc) {
13954 
13955   TypeSourceInfo *ArgTInfo;
13956   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13957   if (ArgTy.isNull())
13958     return ExprError();
13959 
13960   if (!ArgTInfo)
13961     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13962 
13963   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13964 }
13965 
13966 
13967 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13968                                  Expr *CondExpr,
13969                                  Expr *LHSExpr, Expr *RHSExpr,
13970                                  SourceLocation RPLoc) {
13971   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13972 
13973   ExprValueKind VK = VK_RValue;
13974   ExprObjectKind OK = OK_Ordinary;
13975   QualType resType;
13976   bool ValueDependent = false;
13977   bool CondIsTrue = false;
13978   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13979     resType = Context.DependentTy;
13980     ValueDependent = true;
13981   } else {
13982     // The conditional expression is required to be a constant expression.
13983     llvm::APSInt condEval(32);
13984     ExprResult CondICE
13985       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13986           diag::err_typecheck_choose_expr_requires_constant, false);
13987     if (CondICE.isInvalid())
13988       return ExprError();
13989     CondExpr = CondICE.get();
13990     CondIsTrue = condEval.getZExtValue();
13991 
13992     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13993     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13994 
13995     resType = ActiveExpr->getType();
13996     ValueDependent = ActiveExpr->isValueDependent();
13997     VK = ActiveExpr->getValueKind();
13998     OK = ActiveExpr->getObjectKind();
13999   }
14000 
14001   return new (Context)
14002       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14003                  CondIsTrue, resType->isDependentType(), ValueDependent);
14004 }
14005 
14006 //===----------------------------------------------------------------------===//
14007 // Clang Extensions.
14008 //===----------------------------------------------------------------------===//
14009 
14010 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14011 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14012   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14013 
14014   if (LangOpts.CPlusPlus) {
14015     Decl *ManglingContextDecl;
14016     if (MangleNumberingContext *MCtx =
14017             getCurrentMangleNumberContext(Block->getDeclContext(),
14018                                           ManglingContextDecl)) {
14019       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14020       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14021     }
14022   }
14023 
14024   PushBlockScope(CurScope, Block);
14025   CurContext->addDecl(Block);
14026   if (CurScope)
14027     PushDeclContext(CurScope, Block);
14028   else
14029     CurContext = Block;
14030 
14031   getCurBlock()->HasImplicitReturnType = true;
14032 
14033   // Enter a new evaluation context to insulate the block from any
14034   // cleanups from the enclosing full-expression.
14035   PushExpressionEvaluationContext(
14036       ExpressionEvaluationContext::PotentiallyEvaluated);
14037 }
14038 
14039 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14040                                Scope *CurScope) {
14041   assert(ParamInfo.getIdentifier() == nullptr &&
14042          "block-id should have no identifier!");
14043   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14044   BlockScopeInfo *CurBlock = getCurBlock();
14045 
14046   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14047   QualType T = Sig->getType();
14048 
14049   // FIXME: We should allow unexpanded parameter packs here, but that would,
14050   // in turn, make the block expression contain unexpanded parameter packs.
14051   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14052     // Drop the parameters.
14053     FunctionProtoType::ExtProtoInfo EPI;
14054     EPI.HasTrailingReturn = false;
14055     EPI.TypeQuals.addConst();
14056     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14057     Sig = Context.getTrivialTypeSourceInfo(T);
14058   }
14059 
14060   // GetTypeForDeclarator always produces a function type for a block
14061   // literal signature.  Furthermore, it is always a FunctionProtoType
14062   // unless the function was written with a typedef.
14063   assert(T->isFunctionType() &&
14064          "GetTypeForDeclarator made a non-function block signature");
14065 
14066   // Look for an explicit signature in that function type.
14067   FunctionProtoTypeLoc ExplicitSignature;
14068 
14069   if ((ExplicitSignature = Sig->getTypeLoc()
14070                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14071 
14072     // Check whether that explicit signature was synthesized by
14073     // GetTypeForDeclarator.  If so, don't save that as part of the
14074     // written signature.
14075     if (ExplicitSignature.getLocalRangeBegin() ==
14076         ExplicitSignature.getLocalRangeEnd()) {
14077       // This would be much cheaper if we stored TypeLocs instead of
14078       // TypeSourceInfos.
14079       TypeLoc Result = ExplicitSignature.getReturnLoc();
14080       unsigned Size = Result.getFullDataSize();
14081       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14082       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14083 
14084       ExplicitSignature = FunctionProtoTypeLoc();
14085     }
14086   }
14087 
14088   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14089   CurBlock->FunctionType = T;
14090 
14091   const FunctionType *Fn = T->getAs<FunctionType>();
14092   QualType RetTy = Fn->getReturnType();
14093   bool isVariadic =
14094     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14095 
14096   CurBlock->TheDecl->setIsVariadic(isVariadic);
14097 
14098   // Context.DependentTy is used as a placeholder for a missing block
14099   // return type.  TODO:  what should we do with declarators like:
14100   //   ^ * { ... }
14101   // If the answer is "apply template argument deduction"....
14102   if (RetTy != Context.DependentTy) {
14103     CurBlock->ReturnType = RetTy;
14104     CurBlock->TheDecl->setBlockMissingReturnType(false);
14105     CurBlock->HasImplicitReturnType = false;
14106   }
14107 
14108   // Push block parameters from the declarator if we had them.
14109   SmallVector<ParmVarDecl*, 8> Params;
14110   if (ExplicitSignature) {
14111     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14112       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14113       if (Param->getIdentifier() == nullptr &&
14114           !Param->isImplicit() &&
14115           !Param->isInvalidDecl() &&
14116           !getLangOpts().CPlusPlus)
14117         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14118       Params.push_back(Param);
14119     }
14120 
14121   // Fake up parameter variables if we have a typedef, like
14122   //   ^ fntype { ... }
14123   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14124     for (const auto &I : Fn->param_types()) {
14125       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14126           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14127       Params.push_back(Param);
14128     }
14129   }
14130 
14131   // Set the parameters on the block decl.
14132   if (!Params.empty()) {
14133     CurBlock->TheDecl->setParams(Params);
14134     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14135                              /*CheckParameterNames=*/false);
14136   }
14137 
14138   // Finally we can process decl attributes.
14139   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14140 
14141   // Put the parameter variables in scope.
14142   for (auto AI : CurBlock->TheDecl->parameters()) {
14143     AI->setOwningFunction(CurBlock->TheDecl);
14144 
14145     // If this has an identifier, add it to the scope stack.
14146     if (AI->getIdentifier()) {
14147       CheckShadow(CurBlock->TheScope, AI);
14148 
14149       PushOnScopeChains(AI, CurBlock->TheScope);
14150     }
14151   }
14152 }
14153 
14154 /// ActOnBlockError - If there is an error parsing a block, this callback
14155 /// is invoked to pop the information about the block from the action impl.
14156 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14157   // Leave the expression-evaluation context.
14158   DiscardCleanupsInEvaluationContext();
14159   PopExpressionEvaluationContext();
14160 
14161   // Pop off CurBlock, handle nested blocks.
14162   PopDeclContext();
14163   PopFunctionScopeInfo();
14164 }
14165 
14166 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14167 /// literal was successfully completed.  ^(int x){...}
14168 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14169                                     Stmt *Body, Scope *CurScope) {
14170   // If blocks are disabled, emit an error.
14171   if (!LangOpts.Blocks)
14172     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14173 
14174   // Leave the expression-evaluation context.
14175   if (hasAnyUnrecoverableErrorsInThisFunction())
14176     DiscardCleanupsInEvaluationContext();
14177   assert(!Cleanup.exprNeedsCleanups() &&
14178          "cleanups within block not correctly bound!");
14179   PopExpressionEvaluationContext();
14180 
14181   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14182   BlockDecl *BD = BSI->TheDecl;
14183 
14184   if (BSI->HasImplicitReturnType)
14185     deduceClosureReturnType(*BSI);
14186 
14187   QualType RetTy = Context.VoidTy;
14188   if (!BSI->ReturnType.isNull())
14189     RetTy = BSI->ReturnType;
14190 
14191   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14192   QualType BlockTy;
14193 
14194   // If the user wrote a function type in some form, try to use that.
14195   if (!BSI->FunctionType.isNull()) {
14196     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14197 
14198     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14199     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14200 
14201     // Turn protoless block types into nullary block types.
14202     if (isa<FunctionNoProtoType>(FTy)) {
14203       FunctionProtoType::ExtProtoInfo EPI;
14204       EPI.ExtInfo = Ext;
14205       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14206 
14207     // Otherwise, if we don't need to change anything about the function type,
14208     // preserve its sugar structure.
14209     } else if (FTy->getReturnType() == RetTy &&
14210                (!NoReturn || FTy->getNoReturnAttr())) {
14211       BlockTy = BSI->FunctionType;
14212 
14213     // Otherwise, make the minimal modifications to the function type.
14214     } else {
14215       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14216       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14217       EPI.TypeQuals = Qualifiers();
14218       EPI.ExtInfo = Ext;
14219       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14220     }
14221 
14222   // If we don't have a function type, just build one from nothing.
14223   } else {
14224     FunctionProtoType::ExtProtoInfo EPI;
14225     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14226     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14227   }
14228 
14229   DiagnoseUnusedParameters(BD->parameters());
14230   BlockTy = Context.getBlockPointerType(BlockTy);
14231 
14232   // If needed, diagnose invalid gotos and switches in the block.
14233   if (getCurFunction()->NeedsScopeChecking() &&
14234       !PP.isCodeCompletionEnabled())
14235     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14236 
14237   BD->setBody(cast<CompoundStmt>(Body));
14238 
14239   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14240     DiagnoseUnguardedAvailabilityViolations(BD);
14241 
14242   // Try to apply the named return value optimization. We have to check again
14243   // if we can do this, though, because blocks keep return statements around
14244   // to deduce an implicit return type.
14245   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14246       !BD->isDependentContext())
14247     computeNRVO(Body, BSI);
14248 
14249   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14250       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14251     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14252                           NTCUK_Destruct|NTCUK_Copy);
14253 
14254   PopDeclContext();
14255 
14256   // Pop the block scope now but keep it alive to the end of this function.
14257   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14258   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14259 
14260   // Set the captured variables on the block.
14261   SmallVector<BlockDecl::Capture, 4> Captures;
14262   for (Capture &Cap : BSI->Captures) {
14263     if (Cap.isInvalid() || Cap.isThisCapture())
14264       continue;
14265 
14266     VarDecl *Var = Cap.getVariable();
14267     Expr *CopyExpr = nullptr;
14268     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14269       if (const RecordType *Record =
14270               Cap.getCaptureType()->getAs<RecordType>()) {
14271         // The capture logic needs the destructor, so make sure we mark it.
14272         // Usually this is unnecessary because most local variables have
14273         // their destructors marked at declaration time, but parameters are
14274         // an exception because it's technically only the call site that
14275         // actually requires the destructor.
14276         if (isa<ParmVarDecl>(Var))
14277           FinalizeVarWithDestructor(Var, Record);
14278 
14279         // Enter a separate potentially-evaluated context while building block
14280         // initializers to isolate their cleanups from those of the block
14281         // itself.
14282         // FIXME: Is this appropriate even when the block itself occurs in an
14283         // unevaluated operand?
14284         EnterExpressionEvaluationContext EvalContext(
14285             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14286 
14287         SourceLocation Loc = Cap.getLocation();
14288 
14289         ExprResult Result = BuildDeclarationNameExpr(
14290             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14291 
14292         // According to the blocks spec, the capture of a variable from
14293         // the stack requires a const copy constructor.  This is not true
14294         // of the copy/move done to move a __block variable to the heap.
14295         if (!Result.isInvalid() &&
14296             !Result.get()->getType().isConstQualified()) {
14297           Result = ImpCastExprToType(Result.get(),
14298                                      Result.get()->getType().withConst(),
14299                                      CK_NoOp, VK_LValue);
14300         }
14301 
14302         if (!Result.isInvalid()) {
14303           Result = PerformCopyInitialization(
14304               InitializedEntity::InitializeBlock(Var->getLocation(),
14305                                                  Cap.getCaptureType(), false),
14306               Loc, Result.get());
14307         }
14308 
14309         // Build a full-expression copy expression if initialization
14310         // succeeded and used a non-trivial constructor.  Recover from
14311         // errors by pretending that the copy isn't necessary.
14312         if (!Result.isInvalid() &&
14313             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14314                 ->isTrivial()) {
14315           Result = MaybeCreateExprWithCleanups(Result);
14316           CopyExpr = Result.get();
14317         }
14318       }
14319     }
14320 
14321     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14322                               CopyExpr);
14323     Captures.push_back(NewCap);
14324   }
14325   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14326 
14327   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14328 
14329   // If the block isn't obviously global, i.e. it captures anything at
14330   // all, then we need to do a few things in the surrounding context:
14331   if (Result->getBlockDecl()->hasCaptures()) {
14332     // First, this expression has a new cleanup object.
14333     ExprCleanupObjects.push_back(Result->getBlockDecl());
14334     Cleanup.setExprNeedsCleanups(true);
14335 
14336     // It also gets a branch-protected scope if any of the captured
14337     // variables needs destruction.
14338     for (const auto &CI : Result->getBlockDecl()->captures()) {
14339       const VarDecl *var = CI.getVariable();
14340       if (var->getType().isDestructedType() != QualType::DK_none) {
14341         setFunctionHasBranchProtectedScope();
14342         break;
14343       }
14344     }
14345   }
14346 
14347   if (getCurFunction())
14348     getCurFunction()->addBlock(BD);
14349 
14350   return Result;
14351 }
14352 
14353 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14354                             SourceLocation RPLoc) {
14355   TypeSourceInfo *TInfo;
14356   GetTypeFromParser(Ty, &TInfo);
14357   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14358 }
14359 
14360 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14361                                 Expr *E, TypeSourceInfo *TInfo,
14362                                 SourceLocation RPLoc) {
14363   Expr *OrigExpr = E;
14364   bool IsMS = false;
14365 
14366   // CUDA device code does not support varargs.
14367   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14368     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14369       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14370       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14371         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14372     }
14373   }
14374 
14375   // NVPTX does not support va_arg expression.
14376   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14377       Context.getTargetInfo().getTriple().isNVPTX())
14378     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14379 
14380   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14381   // as Microsoft ABI on an actual Microsoft platform, where
14382   // __builtin_ms_va_list and __builtin_va_list are the same.)
14383   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14384       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14385     QualType MSVaListType = Context.getBuiltinMSVaListType();
14386     if (Context.hasSameType(MSVaListType, E->getType())) {
14387       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14388         return ExprError();
14389       IsMS = true;
14390     }
14391   }
14392 
14393   // Get the va_list type
14394   QualType VaListType = Context.getBuiltinVaListType();
14395   if (!IsMS) {
14396     if (VaListType->isArrayType()) {
14397       // Deal with implicit array decay; for example, on x86-64,
14398       // va_list is an array, but it's supposed to decay to
14399       // a pointer for va_arg.
14400       VaListType = Context.getArrayDecayedType(VaListType);
14401       // Make sure the input expression also decays appropriately.
14402       ExprResult Result = UsualUnaryConversions(E);
14403       if (Result.isInvalid())
14404         return ExprError();
14405       E = Result.get();
14406     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14407       // If va_list is a record type and we are compiling in C++ mode,
14408       // check the argument using reference binding.
14409       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14410           Context, Context.getLValueReferenceType(VaListType), false);
14411       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14412       if (Init.isInvalid())
14413         return ExprError();
14414       E = Init.getAs<Expr>();
14415     } else {
14416       // Otherwise, the va_list argument must be an l-value because
14417       // it is modified by va_arg.
14418       if (!E->isTypeDependent() &&
14419           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14420         return ExprError();
14421     }
14422   }
14423 
14424   if (!IsMS && !E->isTypeDependent() &&
14425       !Context.hasSameType(VaListType, E->getType()))
14426     return ExprError(
14427         Diag(E->getBeginLoc(),
14428              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14429         << OrigExpr->getType() << E->getSourceRange());
14430 
14431   if (!TInfo->getType()->isDependentType()) {
14432     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14433                             diag::err_second_parameter_to_va_arg_incomplete,
14434                             TInfo->getTypeLoc()))
14435       return ExprError();
14436 
14437     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14438                                TInfo->getType(),
14439                                diag::err_second_parameter_to_va_arg_abstract,
14440                                TInfo->getTypeLoc()))
14441       return ExprError();
14442 
14443     if (!TInfo->getType().isPODType(Context)) {
14444       Diag(TInfo->getTypeLoc().getBeginLoc(),
14445            TInfo->getType()->isObjCLifetimeType()
14446              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14447              : diag::warn_second_parameter_to_va_arg_not_pod)
14448         << TInfo->getType()
14449         << TInfo->getTypeLoc().getSourceRange();
14450     }
14451 
14452     // Check for va_arg where arguments of the given type will be promoted
14453     // (i.e. this va_arg is guaranteed to have undefined behavior).
14454     QualType PromoteType;
14455     if (TInfo->getType()->isPromotableIntegerType()) {
14456       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14457       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14458         PromoteType = QualType();
14459     }
14460     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14461       PromoteType = Context.DoubleTy;
14462     if (!PromoteType.isNull())
14463       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14464                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14465                           << TInfo->getType()
14466                           << PromoteType
14467                           << TInfo->getTypeLoc().getSourceRange());
14468   }
14469 
14470   QualType T = TInfo->getType().getNonLValueExprType(Context);
14471   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14472 }
14473 
14474 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14475   // The type of __null will be int or long, depending on the size of
14476   // pointers on the target.
14477   QualType Ty;
14478   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14479   if (pw == Context.getTargetInfo().getIntWidth())
14480     Ty = Context.IntTy;
14481   else if (pw == Context.getTargetInfo().getLongWidth())
14482     Ty = Context.LongTy;
14483   else if (pw == Context.getTargetInfo().getLongLongWidth())
14484     Ty = Context.LongLongTy;
14485   else {
14486     llvm_unreachable("I don't know size of pointer!");
14487   }
14488 
14489   return new (Context) GNUNullExpr(Ty, TokenLoc);
14490 }
14491 
14492 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14493                                     SourceLocation BuiltinLoc,
14494                                     SourceLocation RPLoc) {
14495   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14496 }
14497 
14498 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14499                                     SourceLocation BuiltinLoc,
14500                                     SourceLocation RPLoc,
14501                                     DeclContext *ParentContext) {
14502   return new (Context)
14503       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14504 }
14505 
14506 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14507                                               bool Diagnose) {
14508   if (!getLangOpts().ObjC)
14509     return false;
14510 
14511   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14512   if (!PT)
14513     return false;
14514 
14515   if (!PT->isObjCIdType()) {
14516     // Check if the destination is the 'NSString' interface.
14517     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14518     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14519       return false;
14520   }
14521 
14522   // Ignore any parens, implicit casts (should only be
14523   // array-to-pointer decays), and not-so-opaque values.  The last is
14524   // important for making this trigger for property assignments.
14525   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14526   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14527     if (OV->getSourceExpr())
14528       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14529 
14530   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14531   if (!SL || !SL->isAscii())
14532     return false;
14533   if (Diagnose) {
14534     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14535         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14536     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14537   }
14538   return true;
14539 }
14540 
14541 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14542                                               const Expr *SrcExpr) {
14543   if (!DstType->isFunctionPointerType() ||
14544       !SrcExpr->getType()->isFunctionType())
14545     return false;
14546 
14547   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14548   if (!DRE)
14549     return false;
14550 
14551   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14552   if (!FD)
14553     return false;
14554 
14555   return !S.checkAddressOfFunctionIsAvailable(FD,
14556                                               /*Complain=*/true,
14557                                               SrcExpr->getBeginLoc());
14558 }
14559 
14560 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14561                                     SourceLocation Loc,
14562                                     QualType DstType, QualType SrcType,
14563                                     Expr *SrcExpr, AssignmentAction Action,
14564                                     bool *Complained) {
14565   if (Complained)
14566     *Complained = false;
14567 
14568   // Decode the result (notice that AST's are still created for extensions).
14569   bool CheckInferredResultType = false;
14570   bool isInvalid = false;
14571   unsigned DiagKind = 0;
14572   FixItHint Hint;
14573   ConversionFixItGenerator ConvHints;
14574   bool MayHaveConvFixit = false;
14575   bool MayHaveFunctionDiff = false;
14576   const ObjCInterfaceDecl *IFace = nullptr;
14577   const ObjCProtocolDecl *PDecl = nullptr;
14578 
14579   switch (ConvTy) {
14580   case Compatible:
14581       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14582       return false;
14583 
14584   case PointerToInt:
14585     DiagKind = diag::ext_typecheck_convert_pointer_int;
14586     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14587     MayHaveConvFixit = true;
14588     break;
14589   case IntToPointer:
14590     DiagKind = diag::ext_typecheck_convert_int_pointer;
14591     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14592     MayHaveConvFixit = true;
14593     break;
14594   case IncompatiblePointer:
14595     if (Action == AA_Passing_CFAudited)
14596       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14597     else if (SrcType->isFunctionPointerType() &&
14598              DstType->isFunctionPointerType())
14599       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14600     else
14601       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14602 
14603     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14604       SrcType->isObjCObjectPointerType();
14605     if (Hint.isNull() && !CheckInferredResultType) {
14606       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14607     }
14608     else if (CheckInferredResultType) {
14609       SrcType = SrcType.getUnqualifiedType();
14610       DstType = DstType.getUnqualifiedType();
14611     }
14612     MayHaveConvFixit = true;
14613     break;
14614   case IncompatiblePointerSign:
14615     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14616     break;
14617   case FunctionVoidPointer:
14618     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14619     break;
14620   case IncompatiblePointerDiscardsQualifiers: {
14621     // Perform array-to-pointer decay if necessary.
14622     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14623 
14624     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14625     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14626     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14627       DiagKind = diag::err_typecheck_incompatible_address_space;
14628       break;
14629 
14630     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14631       DiagKind = diag::err_typecheck_incompatible_ownership;
14632       break;
14633     }
14634 
14635     llvm_unreachable("unknown error case for discarding qualifiers!");
14636     // fallthrough
14637   }
14638   case CompatiblePointerDiscardsQualifiers:
14639     // If the qualifiers lost were because we were applying the
14640     // (deprecated) C++ conversion from a string literal to a char*
14641     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14642     // Ideally, this check would be performed in
14643     // checkPointerTypesForAssignment. However, that would require a
14644     // bit of refactoring (so that the second argument is an
14645     // expression, rather than a type), which should be done as part
14646     // of a larger effort to fix checkPointerTypesForAssignment for
14647     // C++ semantics.
14648     if (getLangOpts().CPlusPlus &&
14649         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14650       return false;
14651     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14652     break;
14653   case IncompatibleNestedPointerQualifiers:
14654     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14655     break;
14656   case IncompatibleNestedPointerAddressSpaceMismatch:
14657     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14658     break;
14659   case IntToBlockPointer:
14660     DiagKind = diag::err_int_to_block_pointer;
14661     break;
14662   case IncompatibleBlockPointer:
14663     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14664     break;
14665   case IncompatibleObjCQualifiedId: {
14666     if (SrcType->isObjCQualifiedIdType()) {
14667       const ObjCObjectPointerType *srcOPT =
14668                 SrcType->castAs<ObjCObjectPointerType>();
14669       for (auto *srcProto : srcOPT->quals()) {
14670         PDecl = srcProto;
14671         break;
14672       }
14673       if (const ObjCInterfaceType *IFaceT =
14674             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14675         IFace = IFaceT->getDecl();
14676     }
14677     else if (DstType->isObjCQualifiedIdType()) {
14678       const ObjCObjectPointerType *dstOPT =
14679         DstType->castAs<ObjCObjectPointerType>();
14680       for (auto *dstProto : dstOPT->quals()) {
14681         PDecl = dstProto;
14682         break;
14683       }
14684       if (const ObjCInterfaceType *IFaceT =
14685             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14686         IFace = IFaceT->getDecl();
14687     }
14688     DiagKind = diag::warn_incompatible_qualified_id;
14689     break;
14690   }
14691   case IncompatibleVectors:
14692     DiagKind = diag::warn_incompatible_vectors;
14693     break;
14694   case IncompatibleObjCWeakRef:
14695     DiagKind = diag::err_arc_weak_unavailable_assign;
14696     break;
14697   case Incompatible:
14698     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14699       if (Complained)
14700         *Complained = true;
14701       return true;
14702     }
14703 
14704     DiagKind = diag::err_typecheck_convert_incompatible;
14705     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14706     MayHaveConvFixit = true;
14707     isInvalid = true;
14708     MayHaveFunctionDiff = true;
14709     break;
14710   }
14711 
14712   QualType FirstType, SecondType;
14713   switch (Action) {
14714   case AA_Assigning:
14715   case AA_Initializing:
14716     // The destination type comes first.
14717     FirstType = DstType;
14718     SecondType = SrcType;
14719     break;
14720 
14721   case AA_Returning:
14722   case AA_Passing:
14723   case AA_Passing_CFAudited:
14724   case AA_Converting:
14725   case AA_Sending:
14726   case AA_Casting:
14727     // The source type comes first.
14728     FirstType = SrcType;
14729     SecondType = DstType;
14730     break;
14731   }
14732 
14733   PartialDiagnostic FDiag = PDiag(DiagKind);
14734   if (Action == AA_Passing_CFAudited)
14735     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14736   else
14737     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14738 
14739   // If we can fix the conversion, suggest the FixIts.
14740   assert(ConvHints.isNull() || Hint.isNull());
14741   if (!ConvHints.isNull()) {
14742     for (FixItHint &H : ConvHints.Hints)
14743       FDiag << H;
14744   } else {
14745     FDiag << Hint;
14746   }
14747   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14748 
14749   if (MayHaveFunctionDiff)
14750     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14751 
14752   Diag(Loc, FDiag);
14753   if (DiagKind == diag::warn_incompatible_qualified_id &&
14754       PDecl && IFace && !IFace->hasDefinition())
14755       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14756         << IFace << PDecl;
14757 
14758   if (SecondType == Context.OverloadTy)
14759     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14760                               FirstType, /*TakingAddress=*/true);
14761 
14762   if (CheckInferredResultType)
14763     EmitRelatedResultTypeNote(SrcExpr);
14764 
14765   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14766     EmitRelatedResultTypeNoteForReturn(DstType);
14767 
14768   if (Complained)
14769     *Complained = true;
14770   return isInvalid;
14771 }
14772 
14773 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14774                                                  llvm::APSInt *Result) {
14775   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14776   public:
14777     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14778       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14779     }
14780   } Diagnoser;
14781 
14782   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14783 }
14784 
14785 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14786                                                  llvm::APSInt *Result,
14787                                                  unsigned DiagID,
14788                                                  bool AllowFold) {
14789   class IDDiagnoser : public VerifyICEDiagnoser {
14790     unsigned DiagID;
14791 
14792   public:
14793     IDDiagnoser(unsigned DiagID)
14794       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14795 
14796     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14797       S.Diag(Loc, DiagID) << SR;
14798     }
14799   } Diagnoser(DiagID);
14800 
14801   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14802 }
14803 
14804 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14805                                             SourceRange SR) {
14806   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14807 }
14808 
14809 ExprResult
14810 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14811                                       VerifyICEDiagnoser &Diagnoser,
14812                                       bool AllowFold) {
14813   SourceLocation DiagLoc = E->getBeginLoc();
14814 
14815   if (getLangOpts().CPlusPlus11) {
14816     // C++11 [expr.const]p5:
14817     //   If an expression of literal class type is used in a context where an
14818     //   integral constant expression is required, then that class type shall
14819     //   have a single non-explicit conversion function to an integral or
14820     //   unscoped enumeration type
14821     ExprResult Converted;
14822     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14823     public:
14824       CXX11ConvertDiagnoser(bool Silent)
14825           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14826                                 Silent, true) {}
14827 
14828       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14829                                            QualType T) override {
14830         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14831       }
14832 
14833       SemaDiagnosticBuilder diagnoseIncomplete(
14834           Sema &S, SourceLocation Loc, QualType T) override {
14835         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14836       }
14837 
14838       SemaDiagnosticBuilder diagnoseExplicitConv(
14839           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14840         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14841       }
14842 
14843       SemaDiagnosticBuilder noteExplicitConv(
14844           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14845         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14846                  << ConvTy->isEnumeralType() << ConvTy;
14847       }
14848 
14849       SemaDiagnosticBuilder diagnoseAmbiguous(
14850           Sema &S, SourceLocation Loc, QualType T) override {
14851         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14852       }
14853 
14854       SemaDiagnosticBuilder noteAmbiguous(
14855           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14856         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14857                  << ConvTy->isEnumeralType() << ConvTy;
14858       }
14859 
14860       SemaDiagnosticBuilder diagnoseConversion(
14861           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14862         llvm_unreachable("conversion functions are permitted");
14863       }
14864     } ConvertDiagnoser(Diagnoser.Suppress);
14865 
14866     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14867                                                     ConvertDiagnoser);
14868     if (Converted.isInvalid())
14869       return Converted;
14870     E = Converted.get();
14871     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14872       return ExprError();
14873   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14874     // An ICE must be of integral or unscoped enumeration type.
14875     if (!Diagnoser.Suppress)
14876       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14877     return ExprError();
14878   }
14879 
14880   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14881   // in the non-ICE case.
14882   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14883     if (Result)
14884       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14885     if (!isa<ConstantExpr>(E))
14886       E = ConstantExpr::Create(Context, E);
14887     return E;
14888   }
14889 
14890   Expr::EvalResult EvalResult;
14891   SmallVector<PartialDiagnosticAt, 8> Notes;
14892   EvalResult.Diag = &Notes;
14893 
14894   // Try to evaluate the expression, and produce diagnostics explaining why it's
14895   // not a constant expression as a side-effect.
14896   bool Folded =
14897       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14898       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14899 
14900   if (!isa<ConstantExpr>(E))
14901     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14902 
14903   // In C++11, we can rely on diagnostics being produced for any expression
14904   // which is not a constant expression. If no diagnostics were produced, then
14905   // this is a constant expression.
14906   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14907     if (Result)
14908       *Result = EvalResult.Val.getInt();
14909     return E;
14910   }
14911 
14912   // If our only note is the usual "invalid subexpression" note, just point
14913   // the caret at its location rather than producing an essentially
14914   // redundant note.
14915   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14916         diag::note_invalid_subexpr_in_const_expr) {
14917     DiagLoc = Notes[0].first;
14918     Notes.clear();
14919   }
14920 
14921   if (!Folded || !AllowFold) {
14922     if (!Diagnoser.Suppress) {
14923       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14924       for (const PartialDiagnosticAt &Note : Notes)
14925         Diag(Note.first, Note.second);
14926     }
14927 
14928     return ExprError();
14929   }
14930 
14931   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14932   for (const PartialDiagnosticAt &Note : Notes)
14933     Diag(Note.first, Note.second);
14934 
14935   if (Result)
14936     *Result = EvalResult.Val.getInt();
14937   return E;
14938 }
14939 
14940 namespace {
14941   // Handle the case where we conclude a expression which we speculatively
14942   // considered to be unevaluated is actually evaluated.
14943   class TransformToPE : public TreeTransform<TransformToPE> {
14944     typedef TreeTransform<TransformToPE> BaseTransform;
14945 
14946   public:
14947     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14948 
14949     // Make sure we redo semantic analysis
14950     bool AlwaysRebuild() { return true; }
14951     bool ReplacingOriginal() { return true; }
14952 
14953     // We need to special-case DeclRefExprs referring to FieldDecls which
14954     // are not part of a member pointer formation; normal TreeTransforming
14955     // doesn't catch this case because of the way we represent them in the AST.
14956     // FIXME: This is a bit ugly; is it really the best way to handle this
14957     // case?
14958     //
14959     // Error on DeclRefExprs referring to FieldDecls.
14960     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14961       if (isa<FieldDecl>(E->getDecl()) &&
14962           !SemaRef.isUnevaluatedContext())
14963         return SemaRef.Diag(E->getLocation(),
14964                             diag::err_invalid_non_static_member_use)
14965             << E->getDecl() << E->getSourceRange();
14966 
14967       return BaseTransform::TransformDeclRefExpr(E);
14968     }
14969 
14970     // Exception: filter out member pointer formation
14971     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14972       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14973         return E;
14974 
14975       return BaseTransform::TransformUnaryOperator(E);
14976     }
14977 
14978     // The body of a lambda-expression is in a separate expression evaluation
14979     // context so never needs to be transformed.
14980     // FIXME: Ideally we wouldn't transform the closure type either, and would
14981     // just recreate the capture expressions and lambda expression.
14982     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
14983       return SkipLambdaBody(E, Body);
14984     }
14985   };
14986 }
14987 
14988 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14989   assert(isUnevaluatedContext() &&
14990          "Should only transform unevaluated expressions");
14991   ExprEvalContexts.back().Context =
14992       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14993   if (isUnevaluatedContext())
14994     return E;
14995   return TransformToPE(*this).TransformExpr(E);
14996 }
14997 
14998 void
14999 Sema::PushExpressionEvaluationContext(
15000     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15001     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15002   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15003                                 LambdaContextDecl, ExprContext);
15004   Cleanup.reset();
15005   if (!MaybeODRUseExprs.empty())
15006     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15007 }
15008 
15009 void
15010 Sema::PushExpressionEvaluationContext(
15011     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15012     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15013   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15014   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15015 }
15016 
15017 namespace {
15018 
15019 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15020   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15021   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15022     if (E->getOpcode() == UO_Deref)
15023       return CheckPossibleDeref(S, E->getSubExpr());
15024   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15025     return CheckPossibleDeref(S, E->getBase());
15026   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15027     return CheckPossibleDeref(S, E->getBase());
15028   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15029     QualType Inner;
15030     QualType Ty = E->getType();
15031     if (const auto *Ptr = Ty->getAs<PointerType>())
15032       Inner = Ptr->getPointeeType();
15033     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15034       Inner = Arr->getElementType();
15035     else
15036       return nullptr;
15037 
15038     if (Inner->hasAttr(attr::NoDeref))
15039       return E;
15040   }
15041   return nullptr;
15042 }
15043 
15044 } // namespace
15045 
15046 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15047   for (const Expr *E : Rec.PossibleDerefs) {
15048     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15049     if (DeclRef) {
15050       const ValueDecl *Decl = DeclRef->getDecl();
15051       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15052           << Decl->getName() << E->getSourceRange();
15053       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15054     } else {
15055       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15056           << E->getSourceRange();
15057     }
15058   }
15059   Rec.PossibleDerefs.clear();
15060 }
15061 
15062 void Sema::PopExpressionEvaluationContext() {
15063   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15064   unsigned NumTypos = Rec.NumTypos;
15065 
15066   if (!Rec.Lambdas.empty()) {
15067     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15068     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15069         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15070       unsigned D;
15071       if (Rec.isUnevaluated()) {
15072         // C++11 [expr.prim.lambda]p2:
15073         //   A lambda-expression shall not appear in an unevaluated operand
15074         //   (Clause 5).
15075         D = diag::err_lambda_unevaluated_operand;
15076       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15077         // C++1y [expr.const]p2:
15078         //   A conditional-expression e is a core constant expression unless the
15079         //   evaluation of e, following the rules of the abstract machine, would
15080         //   evaluate [...] a lambda-expression.
15081         D = diag::err_lambda_in_constant_expression;
15082       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15083         // C++17 [expr.prim.lamda]p2:
15084         // A lambda-expression shall not appear [...] in a template-argument.
15085         D = diag::err_lambda_in_invalid_context;
15086       } else
15087         llvm_unreachable("Couldn't infer lambda error message.");
15088 
15089       for (const auto *L : Rec.Lambdas)
15090         Diag(L->getBeginLoc(), D);
15091     }
15092   }
15093 
15094   WarnOnPendingNoDerefs(Rec);
15095 
15096   // When are coming out of an unevaluated context, clear out any
15097   // temporaries that we may have created as part of the evaluation of
15098   // the expression in that context: they aren't relevant because they
15099   // will never be constructed.
15100   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15101     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15102                              ExprCleanupObjects.end());
15103     Cleanup = Rec.ParentCleanup;
15104     CleanupVarDeclMarking();
15105     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15106   // Otherwise, merge the contexts together.
15107   } else {
15108     Cleanup.mergeFrom(Rec.ParentCleanup);
15109     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15110                             Rec.SavedMaybeODRUseExprs.end());
15111   }
15112 
15113   // Pop the current expression evaluation context off the stack.
15114   ExprEvalContexts.pop_back();
15115 
15116   // The global expression evaluation context record is never popped.
15117   ExprEvalContexts.back().NumTypos += NumTypos;
15118 }
15119 
15120 void Sema::DiscardCleanupsInEvaluationContext() {
15121   ExprCleanupObjects.erase(
15122          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15123          ExprCleanupObjects.end());
15124   Cleanup.reset();
15125   MaybeODRUseExprs.clear();
15126 }
15127 
15128 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15129   ExprResult Result = CheckPlaceholderExpr(E);
15130   if (Result.isInvalid())
15131     return ExprError();
15132   E = Result.get();
15133   if (!E->getType()->isVariablyModifiedType())
15134     return E;
15135   return TransformToPotentiallyEvaluated(E);
15136 }
15137 
15138 /// Are we in a context that is potentially constant evaluated per C++20
15139 /// [expr.const]p12?
15140 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15141   /// C++2a [expr.const]p12:
15142   //   An expression or conversion is potentially constant evaluated if it is
15143   switch (SemaRef.ExprEvalContexts.back().Context) {
15144     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15145       // -- a manifestly constant-evaluated expression,
15146     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15147     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15148     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15149       // -- a potentially-evaluated expression,
15150     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15151       // -- an immediate subexpression of a braced-init-list,
15152 
15153       // -- [FIXME] an expression of the form & cast-expression that occurs
15154       //    within a templated entity
15155       // -- a subexpression of one of the above that is not a subexpression of
15156       // a nested unevaluated operand.
15157       return true;
15158 
15159     case Sema::ExpressionEvaluationContext::Unevaluated:
15160     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15161       // Expressions in this context are never evaluated.
15162       return false;
15163   }
15164   llvm_unreachable("Invalid context");
15165 }
15166 
15167 /// Return true if this function has a calling convention that requires mangling
15168 /// in the size of the parameter pack.
15169 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15170   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15171   // we don't need parameter type sizes.
15172   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15173   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
15174                             TT.getArch() != llvm::Triple::x86_64))
15175     return false;
15176 
15177   // If this is C++ and this isn't an extern "C" function, parameters do not
15178   // need to be complete. In this case, C++ mangling will apply, which doesn't
15179   // use the size of the parameters.
15180   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15181     return false;
15182 
15183   // Stdcall, fastcall, and vectorcall need this special treatment.
15184   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15185   switch (CC) {
15186   case CC_X86StdCall:
15187   case CC_X86FastCall:
15188   case CC_X86VectorCall:
15189     return true;
15190   default:
15191     break;
15192   }
15193   return false;
15194 }
15195 
15196 /// Require that all of the parameter types of function be complete. Normally,
15197 /// parameter types are only required to be complete when a function is called
15198 /// or defined, but to mangle functions with certain calling conventions, the
15199 /// mangler needs to know the size of the parameter list. In this situation,
15200 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15201 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15202 /// result in a linker error. Clang doesn't implement this behavior, and instead
15203 /// attempts to error at compile time.
15204 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15205                                                   SourceLocation Loc) {
15206   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15207     FunctionDecl *FD;
15208     ParmVarDecl *Param;
15209 
15210   public:
15211     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15212         : FD(FD), Param(Param) {}
15213 
15214     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15215       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15216       StringRef CCName;
15217       switch (CC) {
15218       case CC_X86StdCall:
15219         CCName = "stdcall";
15220         break;
15221       case CC_X86FastCall:
15222         CCName = "fastcall";
15223         break;
15224       case CC_X86VectorCall:
15225         CCName = "vectorcall";
15226         break;
15227       default:
15228         llvm_unreachable("CC does not need mangling");
15229       }
15230 
15231       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15232           << Param->getDeclName() << FD->getDeclName() << CCName;
15233     }
15234   };
15235 
15236   for (ParmVarDecl *Param : FD->parameters()) {
15237     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15238     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15239   }
15240 }
15241 
15242 namespace {
15243 enum class OdrUseContext {
15244   /// Declarations in this context are not odr-used.
15245   None,
15246   /// Declarations in this context are formally odr-used, but this is a
15247   /// dependent context.
15248   Dependent,
15249   /// Declarations in this context are odr-used but not actually used (yet).
15250   FormallyOdrUsed,
15251   /// Declarations in this context are used.
15252   Used
15253 };
15254 }
15255 
15256 /// Are we within a context in which references to resolved functions or to
15257 /// variables result in odr-use?
15258 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15259   OdrUseContext Result;
15260 
15261   switch (SemaRef.ExprEvalContexts.back().Context) {
15262     case Sema::ExpressionEvaluationContext::Unevaluated:
15263     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15264     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15265       return OdrUseContext::None;
15266 
15267     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15268     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15269       Result = OdrUseContext::Used;
15270       break;
15271 
15272     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15273       Result = OdrUseContext::FormallyOdrUsed;
15274       break;
15275 
15276     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15277       // A default argument formally results in odr-use, but doesn't actually
15278       // result in a use in any real sense until it itself is used.
15279       Result = OdrUseContext::FormallyOdrUsed;
15280       break;
15281   }
15282 
15283   if (SemaRef.CurContext->isDependentContext())
15284     return OdrUseContext::Dependent;
15285 
15286   return Result;
15287 }
15288 
15289 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15290   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
15291   return Func->isConstexpr() &&
15292          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
15293 }
15294 
15295 /// Mark a function referenced, and check whether it is odr-used
15296 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15297 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15298                                   bool MightBeOdrUse) {
15299   assert(Func && "No function?");
15300 
15301   Func->setReferenced();
15302 
15303   // Recursive functions aren't really used until they're used from some other
15304   // context.
15305   bool IsRecursiveCall = CurContext == Func;
15306 
15307   // C++11 [basic.def.odr]p3:
15308   //   A function whose name appears as a potentially-evaluated expression is
15309   //   odr-used if it is the unique lookup result or the selected member of a
15310   //   set of overloaded functions [...].
15311   //
15312   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15313   // can just check that here.
15314   OdrUseContext OdrUse =
15315       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15316   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15317     OdrUse = OdrUseContext::FormallyOdrUsed;
15318 
15319   // Trivial default constructors and destructors are never actually used.
15320   // FIXME: What about other special members?
15321   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15322       OdrUse == OdrUseContext::Used) {
15323     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15324       if (Constructor->isDefaultConstructor())
15325         OdrUse = OdrUseContext::FormallyOdrUsed;
15326     if (isa<CXXDestructorDecl>(Func))
15327       OdrUse = OdrUseContext::FormallyOdrUsed;
15328   }
15329 
15330   // C++20 [expr.const]p12:
15331   //   A function [...] is needed for constant evaluation if it is [...] a
15332   //   constexpr function that is named by an expression that is potentially
15333   //   constant evaluated
15334   bool NeededForConstantEvaluation =
15335       isPotentiallyConstantEvaluatedContext(*this) &&
15336       isImplicitlyDefinableConstexprFunction(Func);
15337 
15338   // Determine whether we require a function definition to exist, per
15339   // C++11 [temp.inst]p3:
15340   //   Unless a function template specialization has been explicitly
15341   //   instantiated or explicitly specialized, the function template
15342   //   specialization is implicitly instantiated when the specialization is
15343   //   referenced in a context that requires a function definition to exist.
15344   // C++20 [temp.inst]p7:
15345   //   The existence of a definition of a [...] function is considered to
15346   //   affect the semantics of the program if the [...] function is needed for
15347   //   constant evaluation by an expression
15348   // C++20 [basic.def.odr]p10:
15349   //   Every program shall contain exactly one definition of every non-inline
15350   //   function or variable that is odr-used in that program outside of a
15351   //   discarded statement
15352   // C++20 [special]p1:
15353   //   The implementation will implicitly define [defaulted special members]
15354   //   if they are odr-used or needed for constant evaluation.
15355   //
15356   // Note that we skip the implicit instantiation of templates that are only
15357   // used in unused default arguments or by recursive calls to themselves.
15358   // This is formally non-conforming, but seems reasonable in practice.
15359   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15360                                              NeededForConstantEvaluation);
15361 
15362   // C++14 [temp.expl.spec]p6:
15363   //   If a template [...] is explicitly specialized then that specialization
15364   //   shall be declared before the first use of that specialization that would
15365   //   cause an implicit instantiation to take place, in every translation unit
15366   //   in which such a use occurs
15367   if (NeedDefinition &&
15368       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15369        Func->getMemberSpecializationInfo()))
15370     checkSpecializationVisibility(Loc, Func);
15371 
15372   // C++14 [except.spec]p17:
15373   //   An exception-specification is considered to be needed when:
15374   //   - the function is odr-used or, if it appears in an unevaluated operand,
15375   //     would be odr-used if the expression were potentially-evaluated;
15376   //
15377   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15378   // function is a pure virtual function we're calling, and in that case the
15379   // function was selected by overload resolution and we need to resolve its
15380   // exception specification for a different reason.
15381   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15382   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15383     ResolveExceptionSpec(Loc, FPT);
15384 
15385   if (getLangOpts().CUDA)
15386     CheckCUDACall(Loc, Func);
15387 
15388   // If we need a definition, try to create one.
15389   if (NeedDefinition && !Func->getBody()) {
15390     runWithSufficientStackSpace(Loc, [&] {
15391       if (CXXConstructorDecl *Constructor =
15392               dyn_cast<CXXConstructorDecl>(Func)) {
15393         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15394         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15395           if (Constructor->isDefaultConstructor()) {
15396             if (Constructor->isTrivial() &&
15397                 !Constructor->hasAttr<DLLExportAttr>())
15398               return;
15399             DefineImplicitDefaultConstructor(Loc, Constructor);
15400           } else if (Constructor->isCopyConstructor()) {
15401             DefineImplicitCopyConstructor(Loc, Constructor);
15402           } else if (Constructor->isMoveConstructor()) {
15403             DefineImplicitMoveConstructor(Loc, Constructor);
15404           }
15405         } else if (Constructor->getInheritedConstructor()) {
15406           DefineInheritingConstructor(Loc, Constructor);
15407         }
15408       } else if (CXXDestructorDecl *Destructor =
15409                      dyn_cast<CXXDestructorDecl>(Func)) {
15410         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15411         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15412           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15413             return;
15414           DefineImplicitDestructor(Loc, Destructor);
15415         }
15416         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15417           MarkVTableUsed(Loc, Destructor->getParent());
15418       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15419         if (MethodDecl->isOverloadedOperator() &&
15420             MethodDecl->getOverloadedOperator() == OO_Equal) {
15421           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15422           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15423             if (MethodDecl->isCopyAssignmentOperator())
15424               DefineImplicitCopyAssignment(Loc, MethodDecl);
15425             else if (MethodDecl->isMoveAssignmentOperator())
15426               DefineImplicitMoveAssignment(Loc, MethodDecl);
15427           }
15428         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15429                    MethodDecl->getParent()->isLambda()) {
15430           CXXConversionDecl *Conversion =
15431               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15432           if (Conversion->isLambdaToBlockPointerConversion())
15433             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15434           else
15435             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15436         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15437           MarkVTableUsed(Loc, MethodDecl->getParent());
15438       }
15439 
15440       // Implicit instantiation of function templates and member functions of
15441       // class templates.
15442       if (Func->isImplicitlyInstantiable()) {
15443         TemplateSpecializationKind TSK =
15444             Func->getTemplateSpecializationKindForInstantiation();
15445         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15446         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15447         if (FirstInstantiation) {
15448           PointOfInstantiation = Loc;
15449           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15450         } else if (TSK != TSK_ImplicitInstantiation) {
15451           // Use the point of use as the point of instantiation, instead of the
15452           // point of explicit instantiation (which we track as the actual point
15453           // of instantiation). This gives better backtraces in diagnostics.
15454           PointOfInstantiation = Loc;
15455         }
15456 
15457         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15458             Func->isConstexpr()) {
15459           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15460               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15461               CodeSynthesisContexts.size())
15462             PendingLocalImplicitInstantiations.push_back(
15463                 std::make_pair(Func, PointOfInstantiation));
15464           else if (Func->isConstexpr())
15465             // Do not defer instantiations of constexpr functions, to avoid the
15466             // expression evaluator needing to call back into Sema if it sees a
15467             // call to such a function.
15468             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15469           else {
15470             Func->setInstantiationIsPending(true);
15471             PendingInstantiations.push_back(
15472                 std::make_pair(Func, PointOfInstantiation));
15473             // Notify the consumer that a function was implicitly instantiated.
15474             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15475           }
15476         }
15477       } else {
15478         // Walk redefinitions, as some of them may be instantiable.
15479         for (auto i : Func->redecls()) {
15480           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15481             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15482         }
15483       }
15484     });
15485   }
15486 
15487   // If this is the first "real" use, act on that.
15488   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15489     // Keep track of used but undefined functions.
15490     if (!Func->isDefined()) {
15491       if (mightHaveNonExternalLinkage(Func))
15492         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15493       else if (Func->getMostRecentDecl()->isInlined() &&
15494                !LangOpts.GNUInline &&
15495                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15496         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15497       else if (isExternalWithNoLinkageType(Func))
15498         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15499     }
15500 
15501     // Some x86 Windows calling conventions mangle the size of the parameter
15502     // pack into the name. Computing the size of the parameters requires the
15503     // parameter types to be complete. Check that now.
15504     if (funcHasParameterSizeMangling(*this, Func))
15505       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15506 
15507     Func->markUsed(Context);
15508   }
15509 
15510   if (LangOpts.OpenMP) {
15511     markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15512     if (LangOpts.OpenMPIsDevice)
15513       checkOpenMPDeviceFunction(Loc, Func);
15514     else
15515       checkOpenMPHostFunction(Loc, Func);
15516   }
15517 }
15518 
15519 /// Directly mark a variable odr-used. Given a choice, prefer to use
15520 /// MarkVariableReferenced since it does additional checks and then
15521 /// calls MarkVarDeclODRUsed.
15522 /// If the variable must be captured:
15523 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15524 ///  - else capture it in the DeclContext that maps to the
15525 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15526 static void
15527 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15528                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15529   // Keep track of used but undefined variables.
15530   // FIXME: We shouldn't suppress this warning for static data members.
15531   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15532       (!Var->isExternallyVisible() || Var->isInline() ||
15533        SemaRef.isExternalWithNoLinkageType(Var)) &&
15534       !(Var->isStaticDataMember() && Var->hasInit())) {
15535     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15536     if (old.isInvalid())
15537       old = Loc;
15538   }
15539   QualType CaptureType, DeclRefType;
15540   if (SemaRef.LangOpts.OpenMP)
15541     SemaRef.tryCaptureOpenMPLambdas(Var);
15542   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15543     /*EllipsisLoc*/ SourceLocation(),
15544     /*BuildAndDiagnose*/ true,
15545     CaptureType, DeclRefType,
15546     FunctionScopeIndexToStopAt);
15547 
15548   Var->markUsed(SemaRef.Context);
15549 }
15550 
15551 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15552                                              SourceLocation Loc,
15553                                              unsigned CapturingScopeIndex) {
15554   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15555 }
15556 
15557 static void
15558 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15559                                    ValueDecl *var, DeclContext *DC) {
15560   DeclContext *VarDC = var->getDeclContext();
15561 
15562   //  If the parameter still belongs to the translation unit, then
15563   //  we're actually just using one parameter in the declaration of
15564   //  the next.
15565   if (isa<ParmVarDecl>(var) &&
15566       isa<TranslationUnitDecl>(VarDC))
15567     return;
15568 
15569   // For C code, don't diagnose about capture if we're not actually in code
15570   // right now; it's impossible to write a non-constant expression outside of
15571   // function context, so we'll get other (more useful) diagnostics later.
15572   //
15573   // For C++, things get a bit more nasty... it would be nice to suppress this
15574   // diagnostic for certain cases like using a local variable in an array bound
15575   // for a member of a local class, but the correct predicate is not obvious.
15576   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15577     return;
15578 
15579   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15580   unsigned ContextKind = 3; // unknown
15581   if (isa<CXXMethodDecl>(VarDC) &&
15582       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15583     ContextKind = 2;
15584   } else if (isa<FunctionDecl>(VarDC)) {
15585     ContextKind = 0;
15586   } else if (isa<BlockDecl>(VarDC)) {
15587     ContextKind = 1;
15588   }
15589 
15590   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15591     << var << ValueKind << ContextKind << VarDC;
15592   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15593       << var;
15594 
15595   // FIXME: Add additional diagnostic info about class etc. which prevents
15596   // capture.
15597 }
15598 
15599 
15600 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15601                                       bool &SubCapturesAreNested,
15602                                       QualType &CaptureType,
15603                                       QualType &DeclRefType) {
15604    // Check whether we've already captured it.
15605   if (CSI->CaptureMap.count(Var)) {
15606     // If we found a capture, any subcaptures are nested.
15607     SubCapturesAreNested = true;
15608 
15609     // Retrieve the capture type for this variable.
15610     CaptureType = CSI->getCapture(Var).getCaptureType();
15611 
15612     // Compute the type of an expression that refers to this variable.
15613     DeclRefType = CaptureType.getNonReferenceType();
15614 
15615     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15616     // are mutable in the sense that user can change their value - they are
15617     // private instances of the captured declarations.
15618     const Capture &Cap = CSI->getCapture(Var);
15619     if (Cap.isCopyCapture() &&
15620         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15621         !(isa<CapturedRegionScopeInfo>(CSI) &&
15622           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15623       DeclRefType.addConst();
15624     return true;
15625   }
15626   return false;
15627 }
15628 
15629 // Only block literals, captured statements, and lambda expressions can
15630 // capture; other scopes don't work.
15631 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15632                                  SourceLocation Loc,
15633                                  const bool Diagnose, Sema &S) {
15634   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15635     return getLambdaAwareParentOfDeclContext(DC);
15636   else if (Var->hasLocalStorage()) {
15637     if (Diagnose)
15638        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15639   }
15640   return nullptr;
15641 }
15642 
15643 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15644 // certain types of variables (unnamed, variably modified types etc.)
15645 // so check for eligibility.
15646 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15647                                  SourceLocation Loc,
15648                                  const bool Diagnose, Sema &S) {
15649 
15650   bool IsBlock = isa<BlockScopeInfo>(CSI);
15651   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15652 
15653   // Lambdas are not allowed to capture unnamed variables
15654   // (e.g. anonymous unions).
15655   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15656   // assuming that's the intent.
15657   if (IsLambda && !Var->getDeclName()) {
15658     if (Diagnose) {
15659       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15660       S.Diag(Var->getLocation(), diag::note_declared_at);
15661     }
15662     return false;
15663   }
15664 
15665   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15666   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15667     if (Diagnose) {
15668       S.Diag(Loc, diag::err_ref_vm_type);
15669       S.Diag(Var->getLocation(), diag::note_previous_decl)
15670         << Var->getDeclName();
15671     }
15672     return false;
15673   }
15674   // Prohibit structs with flexible array members too.
15675   // We cannot capture what is in the tail end of the struct.
15676   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15677     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15678       if (Diagnose) {
15679         if (IsBlock)
15680           S.Diag(Loc, diag::err_ref_flexarray_type);
15681         else
15682           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15683             << Var->getDeclName();
15684         S.Diag(Var->getLocation(), diag::note_previous_decl)
15685           << Var->getDeclName();
15686       }
15687       return false;
15688     }
15689   }
15690   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15691   // Lambdas and captured statements are not allowed to capture __block
15692   // variables; they don't support the expected semantics.
15693   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15694     if (Diagnose) {
15695       S.Diag(Loc, diag::err_capture_block_variable)
15696         << Var->getDeclName() << !IsLambda;
15697       S.Diag(Var->getLocation(), diag::note_previous_decl)
15698         << Var->getDeclName();
15699     }
15700     return false;
15701   }
15702   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15703   if (S.getLangOpts().OpenCL && IsBlock &&
15704       Var->getType()->isBlockPointerType()) {
15705     if (Diagnose)
15706       S.Diag(Loc, diag::err_opencl_block_ref_block);
15707     return false;
15708   }
15709 
15710   return true;
15711 }
15712 
15713 // Returns true if the capture by block was successful.
15714 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15715                                  SourceLocation Loc,
15716                                  const bool BuildAndDiagnose,
15717                                  QualType &CaptureType,
15718                                  QualType &DeclRefType,
15719                                  const bool Nested,
15720                                  Sema &S, bool Invalid) {
15721   bool ByRef = false;
15722 
15723   // Blocks are not allowed to capture arrays, excepting OpenCL.
15724   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15725   // (decayed to pointers).
15726   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15727     if (BuildAndDiagnose) {
15728       S.Diag(Loc, diag::err_ref_array_type);
15729       S.Diag(Var->getLocation(), diag::note_previous_decl)
15730       << Var->getDeclName();
15731       Invalid = true;
15732     } else {
15733       return false;
15734     }
15735   }
15736 
15737   // Forbid the block-capture of autoreleasing variables.
15738   if (!Invalid &&
15739       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15740     if (BuildAndDiagnose) {
15741       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15742         << /*block*/ 0;
15743       S.Diag(Var->getLocation(), diag::note_previous_decl)
15744         << Var->getDeclName();
15745       Invalid = true;
15746     } else {
15747       return false;
15748     }
15749   }
15750 
15751   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15752   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15753     QualType PointeeTy = PT->getPointeeType();
15754 
15755     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15756         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15757         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15758       if (BuildAndDiagnose) {
15759         SourceLocation VarLoc = Var->getLocation();
15760         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15761         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15762       }
15763     }
15764   }
15765 
15766   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15767   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15768       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15769     // Block capture by reference does not change the capture or
15770     // declaration reference types.
15771     ByRef = true;
15772   } else {
15773     // Block capture by copy introduces 'const'.
15774     CaptureType = CaptureType.getNonReferenceType().withConst();
15775     DeclRefType = CaptureType;
15776   }
15777 
15778   // Actually capture the variable.
15779   if (BuildAndDiagnose)
15780     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15781                     CaptureType, Invalid);
15782 
15783   return !Invalid;
15784 }
15785 
15786 
15787 /// Capture the given variable in the captured region.
15788 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15789                                     VarDecl *Var,
15790                                     SourceLocation Loc,
15791                                     const bool BuildAndDiagnose,
15792                                     QualType &CaptureType,
15793                                     QualType &DeclRefType,
15794                                     const bool RefersToCapturedVariable,
15795                                     Sema &S, bool Invalid) {
15796   // By default, capture variables by reference.
15797   bool ByRef = true;
15798   // Using an LValue reference type is consistent with Lambdas (see below).
15799   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15800     if (S.isOpenMPCapturedDecl(Var)) {
15801       bool HasConst = DeclRefType.isConstQualified();
15802       DeclRefType = DeclRefType.getUnqualifiedType();
15803       // Don't lose diagnostics about assignments to const.
15804       if (HasConst)
15805         DeclRefType.addConst();
15806     }
15807     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
15808                                     RSI->OpenMPCaptureLevel);
15809   }
15810 
15811   if (ByRef)
15812     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15813   else
15814     CaptureType = DeclRefType;
15815 
15816   // Actually capture the variable.
15817   if (BuildAndDiagnose)
15818     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15819                     Loc, SourceLocation(), CaptureType, Invalid);
15820 
15821   return !Invalid;
15822 }
15823 
15824 /// Capture the given variable in the lambda.
15825 static bool captureInLambda(LambdaScopeInfo *LSI,
15826                             VarDecl *Var,
15827                             SourceLocation Loc,
15828                             const bool BuildAndDiagnose,
15829                             QualType &CaptureType,
15830                             QualType &DeclRefType,
15831                             const bool RefersToCapturedVariable,
15832                             const Sema::TryCaptureKind Kind,
15833                             SourceLocation EllipsisLoc,
15834                             const bool IsTopScope,
15835                             Sema &S, bool Invalid) {
15836   // Determine whether we are capturing by reference or by value.
15837   bool ByRef = false;
15838   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15839     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15840   } else {
15841     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15842   }
15843 
15844   // Compute the type of the field that will capture this variable.
15845   if (ByRef) {
15846     // C++11 [expr.prim.lambda]p15:
15847     //   An entity is captured by reference if it is implicitly or
15848     //   explicitly captured but not captured by copy. It is
15849     //   unspecified whether additional unnamed non-static data
15850     //   members are declared in the closure type for entities
15851     //   captured by reference.
15852     //
15853     // FIXME: It is not clear whether we want to build an lvalue reference
15854     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15855     // to do the former, while EDG does the latter. Core issue 1249 will
15856     // clarify, but for now we follow GCC because it's a more permissive and
15857     // easily defensible position.
15858     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15859   } else {
15860     // C++11 [expr.prim.lambda]p14:
15861     //   For each entity captured by copy, an unnamed non-static
15862     //   data member is declared in the closure type. The
15863     //   declaration order of these members is unspecified. The type
15864     //   of such a data member is the type of the corresponding
15865     //   captured entity if the entity is not a reference to an
15866     //   object, or the referenced type otherwise. [Note: If the
15867     //   captured entity is a reference to a function, the
15868     //   corresponding data member is also a reference to a
15869     //   function. - end note ]
15870     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15871       if (!RefType->getPointeeType()->isFunctionType())
15872         CaptureType = RefType->getPointeeType();
15873     }
15874 
15875     // Forbid the lambda copy-capture of autoreleasing variables.
15876     if (!Invalid &&
15877         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15878       if (BuildAndDiagnose) {
15879         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15880         S.Diag(Var->getLocation(), diag::note_previous_decl)
15881           << Var->getDeclName();
15882         Invalid = true;
15883       } else {
15884         return false;
15885       }
15886     }
15887 
15888     // Make sure that by-copy captures are of a complete and non-abstract type.
15889     if (!Invalid && BuildAndDiagnose) {
15890       if (!CaptureType->isDependentType() &&
15891           S.RequireCompleteType(Loc, CaptureType,
15892                                 diag::err_capture_of_incomplete_type,
15893                                 Var->getDeclName()))
15894         Invalid = true;
15895       else if (S.RequireNonAbstractType(Loc, CaptureType,
15896                                         diag::err_capture_of_abstract_type))
15897         Invalid = true;
15898     }
15899   }
15900 
15901   // Compute the type of a reference to this captured variable.
15902   if (ByRef)
15903     DeclRefType = CaptureType.getNonReferenceType();
15904   else {
15905     // C++ [expr.prim.lambda]p5:
15906     //   The closure type for a lambda-expression has a public inline
15907     //   function call operator [...]. This function call operator is
15908     //   declared const (9.3.1) if and only if the lambda-expression's
15909     //   parameter-declaration-clause is not followed by mutable.
15910     DeclRefType = CaptureType.getNonReferenceType();
15911     if (!LSI->Mutable && !CaptureType->isReferenceType())
15912       DeclRefType.addConst();
15913   }
15914 
15915   // Add the capture.
15916   if (BuildAndDiagnose)
15917     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
15918                     Loc, EllipsisLoc, CaptureType, Invalid);
15919 
15920   return !Invalid;
15921 }
15922 
15923 bool Sema::tryCaptureVariable(
15924     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15925     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15926     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15927   // An init-capture is notionally from the context surrounding its
15928   // declaration, but its parent DC is the lambda class.
15929   DeclContext *VarDC = Var->getDeclContext();
15930   if (Var->isInitCapture())
15931     VarDC = VarDC->getParent();
15932 
15933   DeclContext *DC = CurContext;
15934   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15935       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15936   // We need to sync up the Declaration Context with the
15937   // FunctionScopeIndexToStopAt
15938   if (FunctionScopeIndexToStopAt) {
15939     unsigned FSIndex = FunctionScopes.size() - 1;
15940     while (FSIndex != MaxFunctionScopesIndex) {
15941       DC = getLambdaAwareParentOfDeclContext(DC);
15942       --FSIndex;
15943     }
15944   }
15945 
15946 
15947   // If the variable is declared in the current context, there is no need to
15948   // capture it.
15949   if (VarDC == DC) return true;
15950 
15951   // Capture global variables if it is required to use private copy of this
15952   // variable.
15953   bool IsGlobal = !Var->hasLocalStorage();
15954   if (IsGlobal &&
15955       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
15956                                                 MaxFunctionScopesIndex)))
15957     return true;
15958   Var = Var->getCanonicalDecl();
15959 
15960   // Walk up the stack to determine whether we can capture the variable,
15961   // performing the "simple" checks that don't depend on type. We stop when
15962   // we've either hit the declared scope of the variable or find an existing
15963   // capture of that variable.  We start from the innermost capturing-entity
15964   // (the DC) and ensure that all intervening capturing-entities
15965   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15966   // declcontext can either capture the variable or have already captured
15967   // the variable.
15968   CaptureType = Var->getType();
15969   DeclRefType = CaptureType.getNonReferenceType();
15970   bool Nested = false;
15971   bool Explicit = (Kind != TryCapture_Implicit);
15972   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15973   do {
15974     // Only block literals, captured statements, and lambda expressions can
15975     // capture; other scopes don't work.
15976     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15977                                                               ExprLoc,
15978                                                               BuildAndDiagnose,
15979                                                               *this);
15980     // We need to check for the parent *first* because, if we *have*
15981     // private-captured a global variable, we need to recursively capture it in
15982     // intermediate blocks, lambdas, etc.
15983     if (!ParentDC) {
15984       if (IsGlobal) {
15985         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15986         break;
15987       }
15988       return true;
15989     }
15990 
15991     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15992     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15993 
15994 
15995     // Check whether we've already captured it.
15996     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15997                                              DeclRefType)) {
15998       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15999       break;
16000     }
16001     // If we are instantiating a generic lambda call operator body,
16002     // we do not want to capture new variables.  What was captured
16003     // during either a lambdas transformation or initial parsing
16004     // should be used.
16005     if (isGenericLambdaCallOperatorSpecialization(DC)) {
16006       if (BuildAndDiagnose) {
16007         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16008         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16009           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16010           Diag(Var->getLocation(), diag::note_previous_decl)
16011              << Var->getDeclName();
16012           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16013         } else
16014           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16015       }
16016       return true;
16017     }
16018 
16019     // Try to capture variable-length arrays types.
16020     if (Var->getType()->isVariablyModifiedType()) {
16021       // We're going to walk down into the type and look for VLA
16022       // expressions.
16023       QualType QTy = Var->getType();
16024       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16025         QTy = PVD->getOriginalType();
16026       captureVariablyModifiedType(Context, QTy, CSI);
16027     }
16028 
16029     if (getLangOpts().OpenMP) {
16030       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16031         // OpenMP private variables should not be captured in outer scope, so
16032         // just break here. Similarly, global variables that are captured in a
16033         // target region should not be captured outside the scope of the region.
16034         if (RSI->CapRegionKind == CR_OpenMP) {
16035           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16036           auto IsTargetCap = !IsOpenMPPrivateDecl &&
16037                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16038           // When we detect target captures we are looking from inside the
16039           // target region, therefore we need to propagate the capture from the
16040           // enclosing region. Therefore, the capture is not initially nested.
16041           if (IsTargetCap)
16042             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16043 
16044           if (IsTargetCap || IsOpenMPPrivateDecl) {
16045             Nested = !IsTargetCap;
16046             DeclRefType = DeclRefType.getUnqualifiedType();
16047             CaptureType = Context.getLValueReferenceType(DeclRefType);
16048             break;
16049           }
16050         }
16051       }
16052     }
16053     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16054       // No capture-default, and this is not an explicit capture
16055       // so cannot capture this variable.
16056       if (BuildAndDiagnose) {
16057         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16058         Diag(Var->getLocation(), diag::note_previous_decl)
16059           << Var->getDeclName();
16060         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16061           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16062                diag::note_lambda_decl);
16063         // FIXME: If we error out because an outer lambda can not implicitly
16064         // capture a variable that an inner lambda explicitly captures, we
16065         // should have the inner lambda do the explicit capture - because
16066         // it makes for cleaner diagnostics later.  This would purely be done
16067         // so that the diagnostic does not misleadingly claim that a variable
16068         // can not be captured by a lambda implicitly even though it is captured
16069         // explicitly.  Suggestion:
16070         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16071         //    at the function head
16072         //  - cache the StartingDeclContext - this must be a lambda
16073         //  - captureInLambda in the innermost lambda the variable.
16074       }
16075       return true;
16076     }
16077 
16078     FunctionScopesIndex--;
16079     DC = ParentDC;
16080     Explicit = false;
16081   } while (!VarDC->Equals(DC));
16082 
16083   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16084   // computing the type of the capture at each step, checking type-specific
16085   // requirements, and adding captures if requested.
16086   // If the variable had already been captured previously, we start capturing
16087   // at the lambda nested within that one.
16088   bool Invalid = false;
16089   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16090        ++I) {
16091     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16092 
16093     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16094     // certain types of variables (unnamed, variably modified types etc.)
16095     // so check for eligibility.
16096     if (!Invalid)
16097       Invalid =
16098           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16099 
16100     // After encountering an error, if we're actually supposed to capture, keep
16101     // capturing in nested contexts to suppress any follow-on diagnostics.
16102     if (Invalid && !BuildAndDiagnose)
16103       return true;
16104 
16105     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16106       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16107                                DeclRefType, Nested, *this, Invalid);
16108       Nested = true;
16109     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16110       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16111                                          CaptureType, DeclRefType, Nested,
16112                                          *this, Invalid);
16113       Nested = true;
16114     } else {
16115       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16116       Invalid =
16117           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16118                            DeclRefType, Nested, Kind, EllipsisLoc,
16119                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16120       Nested = true;
16121     }
16122 
16123     if (Invalid && !BuildAndDiagnose)
16124       return true;
16125   }
16126   return Invalid;
16127 }
16128 
16129 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16130                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16131   QualType CaptureType;
16132   QualType DeclRefType;
16133   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16134                             /*BuildAndDiagnose=*/true, CaptureType,
16135                             DeclRefType, nullptr);
16136 }
16137 
16138 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16139   QualType CaptureType;
16140   QualType DeclRefType;
16141   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16142                              /*BuildAndDiagnose=*/false, CaptureType,
16143                              DeclRefType, nullptr);
16144 }
16145 
16146 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16147   QualType CaptureType;
16148   QualType DeclRefType;
16149 
16150   // Determine whether we can capture this variable.
16151   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16152                          /*BuildAndDiagnose=*/false, CaptureType,
16153                          DeclRefType, nullptr))
16154     return QualType();
16155 
16156   return DeclRefType;
16157 }
16158 
16159 namespace {
16160 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16161 // The produced TemplateArgumentListInfo* points to data stored within this
16162 // object, so should only be used in contexts where the pointer will not be
16163 // used after the CopiedTemplateArgs object is destroyed.
16164 class CopiedTemplateArgs {
16165   bool HasArgs;
16166   TemplateArgumentListInfo TemplateArgStorage;
16167 public:
16168   template<typename RefExpr>
16169   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16170     if (HasArgs)
16171       E->copyTemplateArgumentsInto(TemplateArgStorage);
16172   }
16173   operator TemplateArgumentListInfo*()
16174 #ifdef __has_cpp_attribute
16175 #if __has_cpp_attribute(clang::lifetimebound)
16176   [[clang::lifetimebound]]
16177 #endif
16178 #endif
16179   {
16180     return HasArgs ? &TemplateArgStorage : nullptr;
16181   }
16182 };
16183 }
16184 
16185 /// Walk the set of potential results of an expression and mark them all as
16186 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16187 ///
16188 /// \return A new expression if we found any potential results, ExprEmpty() if
16189 ///         not, and ExprError() if we diagnosed an error.
16190 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16191                                                       NonOdrUseReason NOUR) {
16192   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16193   // an object that satisfies the requirements for appearing in a
16194   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16195   // is immediately applied."  This function handles the lvalue-to-rvalue
16196   // conversion part.
16197   //
16198   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16199   // transform it into the relevant kind of non-odr-use node and rebuild the
16200   // tree of nodes leading to it.
16201   //
16202   // This is a mini-TreeTransform that only transforms a restricted subset of
16203   // nodes (and only certain operands of them).
16204 
16205   // Rebuild a subexpression.
16206   auto Rebuild = [&](Expr *Sub) {
16207     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16208   };
16209 
16210   // Check whether a potential result satisfies the requirements of NOUR.
16211   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16212     // Any entity other than a VarDecl is always odr-used whenever it's named
16213     // in a potentially-evaluated expression.
16214     auto *VD = dyn_cast<VarDecl>(D);
16215     if (!VD)
16216       return true;
16217 
16218     // C++2a [basic.def.odr]p4:
16219     //   A variable x whose name appears as a potentially-evalauted expression
16220     //   e is odr-used by e unless
16221     //   -- x is a reference that is usable in constant expressions, or
16222     //   -- x is a variable of non-reference type that is usable in constant
16223     //      expressions and has no mutable subobjects, and e is an element of
16224     //      the set of potential results of an expression of
16225     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16226     //      conversion is applied, or
16227     //   -- x is a variable of non-reference type, and e is an element of the
16228     //      set of potential results of a discarded-value expression to which
16229     //      the lvalue-to-rvalue conversion is not applied
16230     //
16231     // We check the first bullet and the "potentially-evaluated" condition in
16232     // BuildDeclRefExpr. We check the type requirements in the second bullet
16233     // in CheckLValueToRValueConversionOperand below.
16234     switch (NOUR) {
16235     case NOUR_None:
16236     case NOUR_Unevaluated:
16237       llvm_unreachable("unexpected non-odr-use-reason");
16238 
16239     case NOUR_Constant:
16240       // Constant references were handled when they were built.
16241       if (VD->getType()->isReferenceType())
16242         return true;
16243       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16244         if (RD->hasMutableFields())
16245           return true;
16246       if (!VD->isUsableInConstantExpressions(S.Context))
16247         return true;
16248       break;
16249 
16250     case NOUR_Discarded:
16251       if (VD->getType()->isReferenceType())
16252         return true;
16253       break;
16254     }
16255     return false;
16256   };
16257 
16258   // Mark that this expression does not constitute an odr-use.
16259   auto MarkNotOdrUsed = [&] {
16260     S.MaybeODRUseExprs.erase(E);
16261     if (LambdaScopeInfo *LSI = S.getCurLambda())
16262       LSI->markVariableExprAsNonODRUsed(E);
16263   };
16264 
16265   // C++2a [basic.def.odr]p2:
16266   //   The set of potential results of an expression e is defined as follows:
16267   switch (E->getStmtClass()) {
16268   //   -- If e is an id-expression, ...
16269   case Expr::DeclRefExprClass: {
16270     auto *DRE = cast<DeclRefExpr>(E);
16271     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16272       break;
16273 
16274     // Rebuild as a non-odr-use DeclRefExpr.
16275     MarkNotOdrUsed();
16276     return DeclRefExpr::Create(
16277         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16278         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16279         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16280         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16281   }
16282 
16283   case Expr::FunctionParmPackExprClass: {
16284     auto *FPPE = cast<FunctionParmPackExpr>(E);
16285     // If any of the declarations in the pack is odr-used, then the expression
16286     // as a whole constitutes an odr-use.
16287     for (VarDecl *D : *FPPE)
16288       if (IsPotentialResultOdrUsed(D))
16289         return ExprEmpty();
16290 
16291     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16292     // nothing cares about whether we marked this as an odr-use, but it might
16293     // be useful for non-compiler tools.
16294     MarkNotOdrUsed();
16295     break;
16296   }
16297 
16298   //   -- If e is a subscripting operation with an array operand...
16299   case Expr::ArraySubscriptExprClass: {
16300     auto *ASE = cast<ArraySubscriptExpr>(E);
16301     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16302     if (!OldBase->getType()->isArrayType())
16303       break;
16304     ExprResult Base = Rebuild(OldBase);
16305     if (!Base.isUsable())
16306       return Base;
16307     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16308     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16309     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16310     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16311                                      ASE->getRBracketLoc());
16312   }
16313 
16314   case Expr::MemberExprClass: {
16315     auto *ME = cast<MemberExpr>(E);
16316     // -- If e is a class member access expression [...] naming a non-static
16317     //    data member...
16318     if (isa<FieldDecl>(ME->getMemberDecl())) {
16319       ExprResult Base = Rebuild(ME->getBase());
16320       if (!Base.isUsable())
16321         return Base;
16322       return MemberExpr::Create(
16323           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16324           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16325           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16326           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16327           ME->getObjectKind(), ME->isNonOdrUse());
16328     }
16329 
16330     if (ME->getMemberDecl()->isCXXInstanceMember())
16331       break;
16332 
16333     // -- If e is a class member access expression naming a static data member,
16334     //    ...
16335     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16336       break;
16337 
16338     // Rebuild as a non-odr-use MemberExpr.
16339     MarkNotOdrUsed();
16340     return MemberExpr::Create(
16341         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16342         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16343         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16344         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16345     return ExprEmpty();
16346   }
16347 
16348   case Expr::BinaryOperatorClass: {
16349     auto *BO = cast<BinaryOperator>(E);
16350     Expr *LHS = BO->getLHS();
16351     Expr *RHS = BO->getRHS();
16352     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16353     if (BO->getOpcode() == BO_PtrMemD) {
16354       ExprResult Sub = Rebuild(LHS);
16355       if (!Sub.isUsable())
16356         return Sub;
16357       LHS = Sub.get();
16358     //   -- If e is a comma expression, ...
16359     } else if (BO->getOpcode() == BO_Comma) {
16360       ExprResult Sub = Rebuild(RHS);
16361       if (!Sub.isUsable())
16362         return Sub;
16363       RHS = Sub.get();
16364     } else {
16365       break;
16366     }
16367     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16368                         LHS, RHS);
16369   }
16370 
16371   //   -- If e has the form (e1)...
16372   case Expr::ParenExprClass: {
16373     auto *PE = cast<ParenExpr>(E);
16374     ExprResult Sub = Rebuild(PE->getSubExpr());
16375     if (!Sub.isUsable())
16376       return Sub;
16377     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16378   }
16379 
16380   //   -- If e is a glvalue conditional expression, ...
16381   // We don't apply this to a binary conditional operator. FIXME: Should we?
16382   case Expr::ConditionalOperatorClass: {
16383     auto *CO = cast<ConditionalOperator>(E);
16384     ExprResult LHS = Rebuild(CO->getLHS());
16385     if (LHS.isInvalid())
16386       return ExprError();
16387     ExprResult RHS = Rebuild(CO->getRHS());
16388     if (RHS.isInvalid())
16389       return ExprError();
16390     if (!LHS.isUsable() && !RHS.isUsable())
16391       return ExprEmpty();
16392     if (!LHS.isUsable())
16393       LHS = CO->getLHS();
16394     if (!RHS.isUsable())
16395       RHS = CO->getRHS();
16396     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16397                                 CO->getCond(), LHS.get(), RHS.get());
16398   }
16399 
16400   // [Clang extension]
16401   //   -- If e has the form __extension__ e1...
16402   case Expr::UnaryOperatorClass: {
16403     auto *UO = cast<UnaryOperator>(E);
16404     if (UO->getOpcode() != UO_Extension)
16405       break;
16406     ExprResult Sub = Rebuild(UO->getSubExpr());
16407     if (!Sub.isUsable())
16408       return Sub;
16409     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16410                           Sub.get());
16411   }
16412 
16413   // [Clang extension]
16414   //   -- If e has the form _Generic(...), the set of potential results is the
16415   //      union of the sets of potential results of the associated expressions.
16416   case Expr::GenericSelectionExprClass: {
16417     auto *GSE = cast<GenericSelectionExpr>(E);
16418 
16419     SmallVector<Expr *, 4> AssocExprs;
16420     bool AnyChanged = false;
16421     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16422       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16423       if (AssocExpr.isInvalid())
16424         return ExprError();
16425       if (AssocExpr.isUsable()) {
16426         AssocExprs.push_back(AssocExpr.get());
16427         AnyChanged = true;
16428       } else {
16429         AssocExprs.push_back(OrigAssocExpr);
16430       }
16431     }
16432 
16433     return AnyChanged ? S.CreateGenericSelectionExpr(
16434                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16435                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16436                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16437                       : ExprEmpty();
16438   }
16439 
16440   // [Clang extension]
16441   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16442   //      results is the union of the sets of potential results of the
16443   //      second and third subexpressions.
16444   case Expr::ChooseExprClass: {
16445     auto *CE = cast<ChooseExpr>(E);
16446 
16447     ExprResult LHS = Rebuild(CE->getLHS());
16448     if (LHS.isInvalid())
16449       return ExprError();
16450 
16451     ExprResult RHS = Rebuild(CE->getLHS());
16452     if (RHS.isInvalid())
16453       return ExprError();
16454 
16455     if (!LHS.get() && !RHS.get())
16456       return ExprEmpty();
16457     if (!LHS.isUsable())
16458       LHS = CE->getLHS();
16459     if (!RHS.isUsable())
16460       RHS = CE->getRHS();
16461 
16462     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16463                              RHS.get(), CE->getRParenLoc());
16464   }
16465 
16466   // Step through non-syntactic nodes.
16467   case Expr::ConstantExprClass: {
16468     auto *CE = cast<ConstantExpr>(E);
16469     ExprResult Sub = Rebuild(CE->getSubExpr());
16470     if (!Sub.isUsable())
16471       return Sub;
16472     return ConstantExpr::Create(S.Context, Sub.get());
16473   }
16474 
16475   // We could mostly rely on the recursive rebuilding to rebuild implicit
16476   // casts, but not at the top level, so rebuild them here.
16477   case Expr::ImplicitCastExprClass: {
16478     auto *ICE = cast<ImplicitCastExpr>(E);
16479     // Only step through the narrow set of cast kinds we expect to encounter.
16480     // Anything else suggests we've left the region in which potential results
16481     // can be found.
16482     switch (ICE->getCastKind()) {
16483     case CK_NoOp:
16484     case CK_DerivedToBase:
16485     case CK_UncheckedDerivedToBase: {
16486       ExprResult Sub = Rebuild(ICE->getSubExpr());
16487       if (!Sub.isUsable())
16488         return Sub;
16489       CXXCastPath Path(ICE->path());
16490       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16491                                  ICE->getValueKind(), &Path);
16492     }
16493 
16494     default:
16495       break;
16496     }
16497     break;
16498   }
16499 
16500   default:
16501     break;
16502   }
16503 
16504   // Can't traverse through this node. Nothing to do.
16505   return ExprEmpty();
16506 }
16507 
16508 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16509   // Check whether the operand is or contains an object of non-trivial C union
16510   // type.
16511   if (E->getType().isVolatileQualified() &&
16512       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16513        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16514     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16515                           Sema::NTCUC_LValueToRValueVolatile,
16516                           NTCUK_Destruct|NTCUK_Copy);
16517 
16518   // C++2a [basic.def.odr]p4:
16519   //   [...] an expression of non-volatile-qualified non-class type to which
16520   //   the lvalue-to-rvalue conversion is applied [...]
16521   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16522     return E;
16523 
16524   ExprResult Result =
16525       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16526   if (Result.isInvalid())
16527     return ExprError();
16528   return Result.get() ? Result : E;
16529 }
16530 
16531 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16532   Res = CorrectDelayedTyposInExpr(Res);
16533 
16534   if (!Res.isUsable())
16535     return Res;
16536 
16537   // If a constant-expression is a reference to a variable where we delay
16538   // deciding whether it is an odr-use, just assume we will apply the
16539   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16540   // (a non-type template argument), we have special handling anyway.
16541   return CheckLValueToRValueConversionOperand(Res.get());
16542 }
16543 
16544 void Sema::CleanupVarDeclMarking() {
16545   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16546   // call.
16547   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16548   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16549 
16550   for (Expr *E : LocalMaybeODRUseExprs) {
16551     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16552       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16553                          DRE->getLocation(), *this);
16554     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16555       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16556                          *this);
16557     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16558       for (VarDecl *VD : *FP)
16559         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16560     } else {
16561       llvm_unreachable("Unexpected expression");
16562     }
16563   }
16564 
16565   assert(MaybeODRUseExprs.empty() &&
16566          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16567 }
16568 
16569 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16570                                     VarDecl *Var, Expr *E) {
16571   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16572           isa<FunctionParmPackExpr>(E)) &&
16573          "Invalid Expr argument to DoMarkVarDeclReferenced");
16574   Var->setReferenced();
16575 
16576   if (Var->isInvalidDecl())
16577     return;
16578 
16579   auto *MSI = Var->getMemberSpecializationInfo();
16580   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16581                                        : Var->getTemplateSpecializationKind();
16582 
16583   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16584   bool UsableInConstantExpr =
16585       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16586 
16587   // C++20 [expr.const]p12:
16588   //   A variable [...] is needed for constant evaluation if it is [...] a
16589   //   variable whose name appears as a potentially constant evaluated
16590   //   expression that is either a contexpr variable or is of non-volatile
16591   //   const-qualified integral type or of reference type
16592   bool NeededForConstantEvaluation =
16593       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16594 
16595   bool NeedDefinition =
16596       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16597 
16598   VarTemplateSpecializationDecl *VarSpec =
16599       dyn_cast<VarTemplateSpecializationDecl>(Var);
16600   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16601          "Can't instantiate a partial template specialization.");
16602 
16603   // If this might be a member specialization of a static data member, check
16604   // the specialization is visible. We already did the checks for variable
16605   // template specializations when we created them.
16606   if (NeedDefinition && TSK != TSK_Undeclared &&
16607       !isa<VarTemplateSpecializationDecl>(Var))
16608     SemaRef.checkSpecializationVisibility(Loc, Var);
16609 
16610   // Perform implicit instantiation of static data members, static data member
16611   // templates of class templates, and variable template specializations. Delay
16612   // instantiations of variable templates, except for those that could be used
16613   // in a constant expression.
16614   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16615     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16616     // instantiation declaration if a variable is usable in a constant
16617     // expression (among other cases).
16618     bool TryInstantiating =
16619         TSK == TSK_ImplicitInstantiation ||
16620         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16621 
16622     if (TryInstantiating) {
16623       SourceLocation PointOfInstantiation =
16624           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16625       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16626       if (FirstInstantiation) {
16627         PointOfInstantiation = Loc;
16628         if (MSI)
16629           MSI->setPointOfInstantiation(PointOfInstantiation);
16630         else
16631           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16632       }
16633 
16634       bool InstantiationDependent = false;
16635       bool IsNonDependent =
16636           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16637                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16638                   : true;
16639 
16640       // Do not instantiate specializations that are still type-dependent.
16641       if (IsNonDependent) {
16642         if (UsableInConstantExpr) {
16643           // Do not defer instantiations of variables that could be used in a
16644           // constant expression.
16645           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16646             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16647           });
16648         } else if (FirstInstantiation ||
16649                    isa<VarTemplateSpecializationDecl>(Var)) {
16650           // FIXME: For a specialization of a variable template, we don't
16651           // distinguish between "declaration and type implicitly instantiated"
16652           // and "implicit instantiation of definition requested", so we have
16653           // no direct way to avoid enqueueing the pending instantiation
16654           // multiple times.
16655           SemaRef.PendingInstantiations
16656               .push_back(std::make_pair(Var, PointOfInstantiation));
16657         }
16658       }
16659     }
16660   }
16661 
16662   // C++2a [basic.def.odr]p4:
16663   //   A variable x whose name appears as a potentially-evaluated expression e
16664   //   is odr-used by e unless
16665   //   -- x is a reference that is usable in constant expressions
16666   //   -- x is a variable of non-reference type that is usable in constant
16667   //      expressions and has no mutable subobjects [FIXME], and e is an
16668   //      element of the set of potential results of an expression of
16669   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16670   //      conversion is applied
16671   //   -- x is a variable of non-reference type, and e is an element of the set
16672   //      of potential results of a discarded-value expression to which the
16673   //      lvalue-to-rvalue conversion is not applied [FIXME]
16674   //
16675   // We check the first part of the second bullet here, and
16676   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16677   // FIXME: To get the third bullet right, we need to delay this even for
16678   // variables that are not usable in constant expressions.
16679 
16680   // If we already know this isn't an odr-use, there's nothing more to do.
16681   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16682     if (DRE->isNonOdrUse())
16683       return;
16684   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16685     if (ME->isNonOdrUse())
16686       return;
16687 
16688   switch (OdrUse) {
16689   case OdrUseContext::None:
16690     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16691            "missing non-odr-use marking for unevaluated decl ref");
16692     break;
16693 
16694   case OdrUseContext::FormallyOdrUsed:
16695     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16696     // behavior.
16697     break;
16698 
16699   case OdrUseContext::Used:
16700     // If we might later find that this expression isn't actually an odr-use,
16701     // delay the marking.
16702     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16703       SemaRef.MaybeODRUseExprs.insert(E);
16704     else
16705       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16706     break;
16707 
16708   case OdrUseContext::Dependent:
16709     // If this is a dependent context, we don't need to mark variables as
16710     // odr-used, but we may still need to track them for lambda capture.
16711     // FIXME: Do we also need to do this inside dependent typeid expressions
16712     // (which are modeled as unevaluated at this point)?
16713     const bool RefersToEnclosingScope =
16714         (SemaRef.CurContext != Var->getDeclContext() &&
16715          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16716     if (RefersToEnclosingScope) {
16717       LambdaScopeInfo *const LSI =
16718           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16719       if (LSI && (!LSI->CallOperator ||
16720                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16721         // If a variable could potentially be odr-used, defer marking it so
16722         // until we finish analyzing the full expression for any
16723         // lvalue-to-rvalue
16724         // or discarded value conversions that would obviate odr-use.
16725         // Add it to the list of potential captures that will be analyzed
16726         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16727         // unless the variable is a reference that was initialized by a constant
16728         // expression (this will never need to be captured or odr-used).
16729         //
16730         // FIXME: We can simplify this a lot after implementing P0588R1.
16731         assert(E && "Capture variable should be used in an expression.");
16732         if (!Var->getType()->isReferenceType() ||
16733             !Var->isUsableInConstantExpressions(SemaRef.Context))
16734           LSI->addPotentialCapture(E->IgnoreParens());
16735       }
16736     }
16737     break;
16738   }
16739 }
16740 
16741 /// Mark a variable referenced, and check whether it is odr-used
16742 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16743 /// used directly for normal expressions referring to VarDecl.
16744 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16745   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16746 }
16747 
16748 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16749                                Decl *D, Expr *E, bool MightBeOdrUse) {
16750   if (SemaRef.isInOpenMPDeclareTargetContext())
16751     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16752 
16753   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16754     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16755     return;
16756   }
16757 
16758   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16759 
16760   // If this is a call to a method via a cast, also mark the method in the
16761   // derived class used in case codegen can devirtualize the call.
16762   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16763   if (!ME)
16764     return;
16765   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16766   if (!MD)
16767     return;
16768   // Only attempt to devirtualize if this is truly a virtual call.
16769   bool IsVirtualCall = MD->isVirtual() &&
16770                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16771   if (!IsVirtualCall)
16772     return;
16773 
16774   // If it's possible to devirtualize the call, mark the called function
16775   // referenced.
16776   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16777       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16778   if (DM)
16779     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16780 }
16781 
16782 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16783 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16784   // TODO: update this with DR# once a defect report is filed.
16785   // C++11 defect. The address of a pure member should not be an ODR use, even
16786   // if it's a qualified reference.
16787   bool OdrUse = true;
16788   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16789     if (Method->isVirtual() &&
16790         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16791       OdrUse = false;
16792   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16793 }
16794 
16795 /// Perform reference-marking and odr-use handling for a MemberExpr.
16796 void Sema::MarkMemberReferenced(MemberExpr *E) {
16797   // C++11 [basic.def.odr]p2:
16798   //   A non-overloaded function whose name appears as a potentially-evaluated
16799   //   expression or a member of a set of candidate functions, if selected by
16800   //   overload resolution when referred to from a potentially-evaluated
16801   //   expression, is odr-used, unless it is a pure virtual function and its
16802   //   name is not explicitly qualified.
16803   bool MightBeOdrUse = true;
16804   if (E->performsVirtualDispatch(getLangOpts())) {
16805     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16806       if (Method->isPure())
16807         MightBeOdrUse = false;
16808   }
16809   SourceLocation Loc =
16810       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16811   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16812 }
16813 
16814 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16815 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16816   for (VarDecl *VD : *E)
16817     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16818 }
16819 
16820 /// Perform marking for a reference to an arbitrary declaration.  It
16821 /// marks the declaration referenced, and performs odr-use checking for
16822 /// functions and variables. This method should not be used when building a
16823 /// normal expression which refers to a variable.
16824 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16825                                  bool MightBeOdrUse) {
16826   if (MightBeOdrUse) {
16827     if (auto *VD = dyn_cast<VarDecl>(D)) {
16828       MarkVariableReferenced(Loc, VD);
16829       return;
16830     }
16831   }
16832   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16833     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16834     return;
16835   }
16836   D->setReferenced();
16837 }
16838 
16839 namespace {
16840   // Mark all of the declarations used by a type as referenced.
16841   // FIXME: Not fully implemented yet! We need to have a better understanding
16842   // of when we're entering a context we should not recurse into.
16843   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16844   // TreeTransforms rebuilding the type in a new context. Rather than
16845   // duplicating the TreeTransform logic, we should consider reusing it here.
16846   // Currently that causes problems when rebuilding LambdaExprs.
16847   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16848     Sema &S;
16849     SourceLocation Loc;
16850 
16851   public:
16852     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16853 
16854     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16855 
16856     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16857   };
16858 }
16859 
16860 bool MarkReferencedDecls::TraverseTemplateArgument(
16861     const TemplateArgument &Arg) {
16862   {
16863     // A non-type template argument is a constant-evaluated context.
16864     EnterExpressionEvaluationContext Evaluated(
16865         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16866     if (Arg.getKind() == TemplateArgument::Declaration) {
16867       if (Decl *D = Arg.getAsDecl())
16868         S.MarkAnyDeclReferenced(Loc, D, true);
16869     } else if (Arg.getKind() == TemplateArgument::Expression) {
16870       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16871     }
16872   }
16873 
16874   return Inherited::TraverseTemplateArgument(Arg);
16875 }
16876 
16877 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16878   MarkReferencedDecls Marker(*this, Loc);
16879   Marker.TraverseType(T);
16880 }
16881 
16882 namespace {
16883   /// Helper class that marks all of the declarations referenced by
16884   /// potentially-evaluated subexpressions as "referenced".
16885   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16886     Sema &S;
16887     bool SkipLocalVariables;
16888 
16889   public:
16890     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16891 
16892     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16893       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16894 
16895     void VisitDeclRefExpr(DeclRefExpr *E) {
16896       // If we were asked not to visit local variables, don't.
16897       if (SkipLocalVariables) {
16898         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16899           if (VD->hasLocalStorage())
16900             return;
16901       }
16902 
16903       S.MarkDeclRefReferenced(E);
16904     }
16905 
16906     void VisitMemberExpr(MemberExpr *E) {
16907       S.MarkMemberReferenced(E);
16908       Inherited::VisitMemberExpr(E);
16909     }
16910 
16911     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16912       S.MarkFunctionReferenced(
16913           E->getBeginLoc(),
16914           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16915       Visit(E->getSubExpr());
16916     }
16917 
16918     void VisitCXXNewExpr(CXXNewExpr *E) {
16919       if (E->getOperatorNew())
16920         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16921       if (E->getOperatorDelete())
16922         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16923       Inherited::VisitCXXNewExpr(E);
16924     }
16925 
16926     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16927       if (E->getOperatorDelete())
16928         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16929       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16930       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16931         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16932         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16933       }
16934 
16935       Inherited::VisitCXXDeleteExpr(E);
16936     }
16937 
16938     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16939       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16940       Inherited::VisitCXXConstructExpr(E);
16941     }
16942 
16943     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16944       Visit(E->getExpr());
16945     }
16946   };
16947 }
16948 
16949 /// Mark any declarations that appear within this expression or any
16950 /// potentially-evaluated subexpressions as "referenced".
16951 ///
16952 /// \param SkipLocalVariables If true, don't mark local variables as
16953 /// 'referenced'.
16954 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16955                                             bool SkipLocalVariables) {
16956   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16957 }
16958 
16959 /// Emit a diagnostic that describes an effect on the run-time behavior
16960 /// of the program being compiled.
16961 ///
16962 /// This routine emits the given diagnostic when the code currently being
16963 /// type-checked is "potentially evaluated", meaning that there is a
16964 /// possibility that the code will actually be executable. Code in sizeof()
16965 /// expressions, code used only during overload resolution, etc., are not
16966 /// potentially evaluated. This routine will suppress such diagnostics or,
16967 /// in the absolutely nutty case of potentially potentially evaluated
16968 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16969 /// later.
16970 ///
16971 /// This routine should be used for all diagnostics that describe the run-time
16972 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16973 /// Failure to do so will likely result in spurious diagnostics or failures
16974 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16975 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
16976                                const PartialDiagnostic &PD) {
16977   switch (ExprEvalContexts.back().Context) {
16978   case ExpressionEvaluationContext::Unevaluated:
16979   case ExpressionEvaluationContext::UnevaluatedList:
16980   case ExpressionEvaluationContext::UnevaluatedAbstract:
16981   case ExpressionEvaluationContext::DiscardedStatement:
16982     // The argument will never be evaluated, so don't complain.
16983     break;
16984 
16985   case ExpressionEvaluationContext::ConstantEvaluated:
16986     // Relevant diagnostics should be produced by constant evaluation.
16987     break;
16988 
16989   case ExpressionEvaluationContext::PotentiallyEvaluated:
16990   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16991     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
16992       FunctionScopes.back()->PossiblyUnreachableDiags.
16993         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
16994       return true;
16995     }
16996 
16997     // The initializer of a constexpr variable or of the first declaration of a
16998     // static data member is not syntactically a constant evaluated constant,
16999     // but nonetheless is always required to be a constant expression, so we
17000     // can skip diagnosing.
17001     // FIXME: Using the mangling context here is a hack.
17002     if (auto *VD = dyn_cast_or_null<VarDecl>(
17003             ExprEvalContexts.back().ManglingContextDecl)) {
17004       if (VD->isConstexpr() ||
17005           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17006         break;
17007       // FIXME: For any other kind of variable, we should build a CFG for its
17008       // initializer and check whether the context in question is reachable.
17009     }
17010 
17011     Diag(Loc, PD);
17012     return true;
17013   }
17014 
17015   return false;
17016 }
17017 
17018 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17019                                const PartialDiagnostic &PD) {
17020   return DiagRuntimeBehavior(
17021       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17022 }
17023 
17024 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17025                                CallExpr *CE, FunctionDecl *FD) {
17026   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17027     return false;
17028 
17029   // If we're inside a decltype's expression, don't check for a valid return
17030   // type or construct temporaries until we know whether this is the last call.
17031   if (ExprEvalContexts.back().ExprContext ==
17032       ExpressionEvaluationContextRecord::EK_Decltype) {
17033     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17034     return false;
17035   }
17036 
17037   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17038     FunctionDecl *FD;
17039     CallExpr *CE;
17040 
17041   public:
17042     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17043       : FD(FD), CE(CE) { }
17044 
17045     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17046       if (!FD) {
17047         S.Diag(Loc, diag::err_call_incomplete_return)
17048           << T << CE->getSourceRange();
17049         return;
17050       }
17051 
17052       S.Diag(Loc, diag::err_call_function_incomplete_return)
17053         << CE->getSourceRange() << FD->getDeclName() << T;
17054       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17055           << FD->getDeclName();
17056     }
17057   } Diagnoser(FD, CE);
17058 
17059   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17060     return true;
17061 
17062   return false;
17063 }
17064 
17065 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17066 // will prevent this condition from triggering, which is what we want.
17067 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17068   SourceLocation Loc;
17069 
17070   unsigned diagnostic = diag::warn_condition_is_assignment;
17071   bool IsOrAssign = false;
17072 
17073   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17074     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17075       return;
17076 
17077     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17078 
17079     // Greylist some idioms by putting them into a warning subcategory.
17080     if (ObjCMessageExpr *ME
17081           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17082       Selector Sel = ME->getSelector();
17083 
17084       // self = [<foo> init...]
17085       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17086         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17087 
17088       // <foo> = [<bar> nextObject]
17089       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17090         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17091     }
17092 
17093     Loc = Op->getOperatorLoc();
17094   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17095     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17096       return;
17097 
17098     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17099     Loc = Op->getOperatorLoc();
17100   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17101     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17102   else {
17103     // Not an assignment.
17104     return;
17105   }
17106 
17107   Diag(Loc, diagnostic) << E->getSourceRange();
17108 
17109   SourceLocation Open = E->getBeginLoc();
17110   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17111   Diag(Loc, diag::note_condition_assign_silence)
17112         << FixItHint::CreateInsertion(Open, "(")
17113         << FixItHint::CreateInsertion(Close, ")");
17114 
17115   if (IsOrAssign)
17116     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17117       << FixItHint::CreateReplacement(Loc, "!=");
17118   else
17119     Diag(Loc, diag::note_condition_assign_to_comparison)
17120       << FixItHint::CreateReplacement(Loc, "==");
17121 }
17122 
17123 /// Redundant parentheses over an equality comparison can indicate
17124 /// that the user intended an assignment used as condition.
17125 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17126   // Don't warn if the parens came from a macro.
17127   SourceLocation parenLoc = ParenE->getBeginLoc();
17128   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17129     return;
17130   // Don't warn for dependent expressions.
17131   if (ParenE->isTypeDependent())
17132     return;
17133 
17134   Expr *E = ParenE->IgnoreParens();
17135 
17136   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17137     if (opE->getOpcode() == BO_EQ &&
17138         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17139                                                            == Expr::MLV_Valid) {
17140       SourceLocation Loc = opE->getOperatorLoc();
17141 
17142       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17143       SourceRange ParenERange = ParenE->getSourceRange();
17144       Diag(Loc, diag::note_equality_comparison_silence)
17145         << FixItHint::CreateRemoval(ParenERange.getBegin())
17146         << FixItHint::CreateRemoval(ParenERange.getEnd());
17147       Diag(Loc, diag::note_equality_comparison_to_assign)
17148         << FixItHint::CreateReplacement(Loc, "=");
17149     }
17150 }
17151 
17152 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17153                                        bool IsConstexpr) {
17154   DiagnoseAssignmentAsCondition(E);
17155   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17156     DiagnoseEqualityWithExtraParens(parenE);
17157 
17158   ExprResult result = CheckPlaceholderExpr(E);
17159   if (result.isInvalid()) return ExprError();
17160   E = result.get();
17161 
17162   if (!E->isTypeDependent()) {
17163     if (getLangOpts().CPlusPlus)
17164       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17165 
17166     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17167     if (ERes.isInvalid())
17168       return ExprError();
17169     E = ERes.get();
17170 
17171     QualType T = E->getType();
17172     if (!T->isScalarType()) { // C99 6.8.4.1p1
17173       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17174         << T << E->getSourceRange();
17175       return ExprError();
17176     }
17177     CheckBoolLikeConversion(E, Loc);
17178   }
17179 
17180   return E;
17181 }
17182 
17183 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17184                                            Expr *SubExpr, ConditionKind CK) {
17185   // Empty conditions are valid in for-statements.
17186   if (!SubExpr)
17187     return ConditionResult();
17188 
17189   ExprResult Cond;
17190   switch (CK) {
17191   case ConditionKind::Boolean:
17192     Cond = CheckBooleanCondition(Loc, SubExpr);
17193     break;
17194 
17195   case ConditionKind::ConstexprIf:
17196     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17197     break;
17198 
17199   case ConditionKind::Switch:
17200     Cond = CheckSwitchCondition(Loc, SubExpr);
17201     break;
17202   }
17203   if (Cond.isInvalid())
17204     return ConditionError();
17205 
17206   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17207   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17208   if (!FullExpr.get())
17209     return ConditionError();
17210 
17211   return ConditionResult(*this, nullptr, FullExpr,
17212                          CK == ConditionKind::ConstexprIf);
17213 }
17214 
17215 namespace {
17216   /// A visitor for rebuilding a call to an __unknown_any expression
17217   /// to have an appropriate type.
17218   struct RebuildUnknownAnyFunction
17219     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17220 
17221     Sema &S;
17222 
17223     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17224 
17225     ExprResult VisitStmt(Stmt *S) {
17226       llvm_unreachable("unexpected statement!");
17227     }
17228 
17229     ExprResult VisitExpr(Expr *E) {
17230       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17231         << E->getSourceRange();
17232       return ExprError();
17233     }
17234 
17235     /// Rebuild an expression which simply semantically wraps another
17236     /// expression which it shares the type and value kind of.
17237     template <class T> ExprResult rebuildSugarExpr(T *E) {
17238       ExprResult SubResult = Visit(E->getSubExpr());
17239       if (SubResult.isInvalid()) return ExprError();
17240 
17241       Expr *SubExpr = SubResult.get();
17242       E->setSubExpr(SubExpr);
17243       E->setType(SubExpr->getType());
17244       E->setValueKind(SubExpr->getValueKind());
17245       assert(E->getObjectKind() == OK_Ordinary);
17246       return E;
17247     }
17248 
17249     ExprResult VisitParenExpr(ParenExpr *E) {
17250       return rebuildSugarExpr(E);
17251     }
17252 
17253     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17254       return rebuildSugarExpr(E);
17255     }
17256 
17257     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17258       ExprResult SubResult = Visit(E->getSubExpr());
17259       if (SubResult.isInvalid()) return ExprError();
17260 
17261       Expr *SubExpr = SubResult.get();
17262       E->setSubExpr(SubExpr);
17263       E->setType(S.Context.getPointerType(SubExpr->getType()));
17264       assert(E->getValueKind() == VK_RValue);
17265       assert(E->getObjectKind() == OK_Ordinary);
17266       return E;
17267     }
17268 
17269     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17270       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17271 
17272       E->setType(VD->getType());
17273 
17274       assert(E->getValueKind() == VK_RValue);
17275       if (S.getLangOpts().CPlusPlus &&
17276           !(isa<CXXMethodDecl>(VD) &&
17277             cast<CXXMethodDecl>(VD)->isInstance()))
17278         E->setValueKind(VK_LValue);
17279 
17280       return E;
17281     }
17282 
17283     ExprResult VisitMemberExpr(MemberExpr *E) {
17284       return resolveDecl(E, E->getMemberDecl());
17285     }
17286 
17287     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17288       return resolveDecl(E, E->getDecl());
17289     }
17290   };
17291 }
17292 
17293 /// Given a function expression of unknown-any type, try to rebuild it
17294 /// to have a function type.
17295 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17296   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17297   if (Result.isInvalid()) return ExprError();
17298   return S.DefaultFunctionArrayConversion(Result.get());
17299 }
17300 
17301 namespace {
17302   /// A visitor for rebuilding an expression of type __unknown_anytype
17303   /// into one which resolves the type directly on the referring
17304   /// expression.  Strict preservation of the original source
17305   /// structure is not a goal.
17306   struct RebuildUnknownAnyExpr
17307     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17308 
17309     Sema &S;
17310 
17311     /// The current destination type.
17312     QualType DestType;
17313 
17314     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17315       : S(S), DestType(CastType) {}
17316 
17317     ExprResult VisitStmt(Stmt *S) {
17318       llvm_unreachable("unexpected statement!");
17319     }
17320 
17321     ExprResult VisitExpr(Expr *E) {
17322       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17323         << E->getSourceRange();
17324       return ExprError();
17325     }
17326 
17327     ExprResult VisitCallExpr(CallExpr *E);
17328     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17329 
17330     /// Rebuild an expression which simply semantically wraps another
17331     /// expression which it shares the type and value kind of.
17332     template <class T> ExprResult rebuildSugarExpr(T *E) {
17333       ExprResult SubResult = Visit(E->getSubExpr());
17334       if (SubResult.isInvalid()) return ExprError();
17335       Expr *SubExpr = SubResult.get();
17336       E->setSubExpr(SubExpr);
17337       E->setType(SubExpr->getType());
17338       E->setValueKind(SubExpr->getValueKind());
17339       assert(E->getObjectKind() == OK_Ordinary);
17340       return E;
17341     }
17342 
17343     ExprResult VisitParenExpr(ParenExpr *E) {
17344       return rebuildSugarExpr(E);
17345     }
17346 
17347     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17348       return rebuildSugarExpr(E);
17349     }
17350 
17351     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17352       const PointerType *Ptr = DestType->getAs<PointerType>();
17353       if (!Ptr) {
17354         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17355           << E->getSourceRange();
17356         return ExprError();
17357       }
17358 
17359       if (isa<CallExpr>(E->getSubExpr())) {
17360         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17361           << E->getSourceRange();
17362         return ExprError();
17363       }
17364 
17365       assert(E->getValueKind() == VK_RValue);
17366       assert(E->getObjectKind() == OK_Ordinary);
17367       E->setType(DestType);
17368 
17369       // Build the sub-expression as if it were an object of the pointee type.
17370       DestType = Ptr->getPointeeType();
17371       ExprResult SubResult = Visit(E->getSubExpr());
17372       if (SubResult.isInvalid()) return ExprError();
17373       E->setSubExpr(SubResult.get());
17374       return E;
17375     }
17376 
17377     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17378 
17379     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17380 
17381     ExprResult VisitMemberExpr(MemberExpr *E) {
17382       return resolveDecl(E, E->getMemberDecl());
17383     }
17384 
17385     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17386       return resolveDecl(E, E->getDecl());
17387     }
17388   };
17389 }
17390 
17391 /// Rebuilds a call expression which yielded __unknown_anytype.
17392 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17393   Expr *CalleeExpr = E->getCallee();
17394 
17395   enum FnKind {
17396     FK_MemberFunction,
17397     FK_FunctionPointer,
17398     FK_BlockPointer
17399   };
17400 
17401   FnKind Kind;
17402   QualType CalleeType = CalleeExpr->getType();
17403   if (CalleeType == S.Context.BoundMemberTy) {
17404     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17405     Kind = FK_MemberFunction;
17406     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17407   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17408     CalleeType = Ptr->getPointeeType();
17409     Kind = FK_FunctionPointer;
17410   } else {
17411     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17412     Kind = FK_BlockPointer;
17413   }
17414   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17415 
17416   // Verify that this is a legal result type of a function.
17417   if (DestType->isArrayType() || DestType->isFunctionType()) {
17418     unsigned diagID = diag::err_func_returning_array_function;
17419     if (Kind == FK_BlockPointer)
17420       diagID = diag::err_block_returning_array_function;
17421 
17422     S.Diag(E->getExprLoc(), diagID)
17423       << DestType->isFunctionType() << DestType;
17424     return ExprError();
17425   }
17426 
17427   // Otherwise, go ahead and set DestType as the call's result.
17428   E->setType(DestType.getNonLValueExprType(S.Context));
17429   E->setValueKind(Expr::getValueKindForType(DestType));
17430   assert(E->getObjectKind() == OK_Ordinary);
17431 
17432   // Rebuild the function type, replacing the result type with DestType.
17433   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17434   if (Proto) {
17435     // __unknown_anytype(...) is a special case used by the debugger when
17436     // it has no idea what a function's signature is.
17437     //
17438     // We want to build this call essentially under the K&R
17439     // unprototyped rules, but making a FunctionNoProtoType in C++
17440     // would foul up all sorts of assumptions.  However, we cannot
17441     // simply pass all arguments as variadic arguments, nor can we
17442     // portably just call the function under a non-variadic type; see
17443     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17444     // However, it turns out that in practice it is generally safe to
17445     // call a function declared as "A foo(B,C,D);" under the prototype
17446     // "A foo(B,C,D,...);".  The only known exception is with the
17447     // Windows ABI, where any variadic function is implicitly cdecl
17448     // regardless of its normal CC.  Therefore we change the parameter
17449     // types to match the types of the arguments.
17450     //
17451     // This is a hack, but it is far superior to moving the
17452     // corresponding target-specific code from IR-gen to Sema/AST.
17453 
17454     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17455     SmallVector<QualType, 8> ArgTypes;
17456     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17457       ArgTypes.reserve(E->getNumArgs());
17458       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17459         Expr *Arg = E->getArg(i);
17460         QualType ArgType = Arg->getType();
17461         if (E->isLValue()) {
17462           ArgType = S.Context.getLValueReferenceType(ArgType);
17463         } else if (E->isXValue()) {
17464           ArgType = S.Context.getRValueReferenceType(ArgType);
17465         }
17466         ArgTypes.push_back(ArgType);
17467       }
17468       ParamTypes = ArgTypes;
17469     }
17470     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17471                                          Proto->getExtProtoInfo());
17472   } else {
17473     DestType = S.Context.getFunctionNoProtoType(DestType,
17474                                                 FnType->getExtInfo());
17475   }
17476 
17477   // Rebuild the appropriate pointer-to-function type.
17478   switch (Kind) {
17479   case FK_MemberFunction:
17480     // Nothing to do.
17481     break;
17482 
17483   case FK_FunctionPointer:
17484     DestType = S.Context.getPointerType(DestType);
17485     break;
17486 
17487   case FK_BlockPointer:
17488     DestType = S.Context.getBlockPointerType(DestType);
17489     break;
17490   }
17491 
17492   // Finally, we can recurse.
17493   ExprResult CalleeResult = Visit(CalleeExpr);
17494   if (!CalleeResult.isUsable()) return ExprError();
17495   E->setCallee(CalleeResult.get());
17496 
17497   // Bind a temporary if necessary.
17498   return S.MaybeBindToTemporary(E);
17499 }
17500 
17501 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17502   // Verify that this is a legal result type of a call.
17503   if (DestType->isArrayType() || DestType->isFunctionType()) {
17504     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17505       << DestType->isFunctionType() << DestType;
17506     return ExprError();
17507   }
17508 
17509   // Rewrite the method result type if available.
17510   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17511     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17512     Method->setReturnType(DestType);
17513   }
17514 
17515   // Change the type of the message.
17516   E->setType(DestType.getNonReferenceType());
17517   E->setValueKind(Expr::getValueKindForType(DestType));
17518 
17519   return S.MaybeBindToTemporary(E);
17520 }
17521 
17522 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17523   // The only case we should ever see here is a function-to-pointer decay.
17524   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17525     assert(E->getValueKind() == VK_RValue);
17526     assert(E->getObjectKind() == OK_Ordinary);
17527 
17528     E->setType(DestType);
17529 
17530     // Rebuild the sub-expression as the pointee (function) type.
17531     DestType = DestType->castAs<PointerType>()->getPointeeType();
17532 
17533     ExprResult Result = Visit(E->getSubExpr());
17534     if (!Result.isUsable()) return ExprError();
17535 
17536     E->setSubExpr(Result.get());
17537     return E;
17538   } else if (E->getCastKind() == CK_LValueToRValue) {
17539     assert(E->getValueKind() == VK_RValue);
17540     assert(E->getObjectKind() == OK_Ordinary);
17541 
17542     assert(isa<BlockPointerType>(E->getType()));
17543 
17544     E->setType(DestType);
17545 
17546     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17547     DestType = S.Context.getLValueReferenceType(DestType);
17548 
17549     ExprResult Result = Visit(E->getSubExpr());
17550     if (!Result.isUsable()) return ExprError();
17551 
17552     E->setSubExpr(Result.get());
17553     return E;
17554   } else {
17555     llvm_unreachable("Unhandled cast type!");
17556   }
17557 }
17558 
17559 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17560   ExprValueKind ValueKind = VK_LValue;
17561   QualType Type = DestType;
17562 
17563   // We know how to make this work for certain kinds of decls:
17564 
17565   //  - functions
17566   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17567     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17568       DestType = Ptr->getPointeeType();
17569       ExprResult Result = resolveDecl(E, VD);
17570       if (Result.isInvalid()) return ExprError();
17571       return S.ImpCastExprToType(Result.get(), Type,
17572                                  CK_FunctionToPointerDecay, VK_RValue);
17573     }
17574 
17575     if (!Type->isFunctionType()) {
17576       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17577         << VD << E->getSourceRange();
17578       return ExprError();
17579     }
17580     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17581       // We must match the FunctionDecl's type to the hack introduced in
17582       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17583       // type. See the lengthy commentary in that routine.
17584       QualType FDT = FD->getType();
17585       const FunctionType *FnType = FDT->castAs<FunctionType>();
17586       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17587       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17588       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17589         SourceLocation Loc = FD->getLocation();
17590         FunctionDecl *NewFD = FunctionDecl::Create(
17591             S.Context, FD->getDeclContext(), Loc, Loc,
17592             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17593             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17594             /*ConstexprKind*/ CSK_unspecified);
17595 
17596         if (FD->getQualifier())
17597           NewFD->setQualifierInfo(FD->getQualifierLoc());
17598 
17599         SmallVector<ParmVarDecl*, 16> Params;
17600         for (const auto &AI : FT->param_types()) {
17601           ParmVarDecl *Param =
17602             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17603           Param->setScopeInfo(0, Params.size());
17604           Params.push_back(Param);
17605         }
17606         NewFD->setParams(Params);
17607         DRE->setDecl(NewFD);
17608         VD = DRE->getDecl();
17609       }
17610     }
17611 
17612     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17613       if (MD->isInstance()) {
17614         ValueKind = VK_RValue;
17615         Type = S.Context.BoundMemberTy;
17616       }
17617 
17618     // Function references aren't l-values in C.
17619     if (!S.getLangOpts().CPlusPlus)
17620       ValueKind = VK_RValue;
17621 
17622   //  - variables
17623   } else if (isa<VarDecl>(VD)) {
17624     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17625       Type = RefTy->getPointeeType();
17626     } else if (Type->isFunctionType()) {
17627       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17628         << VD << E->getSourceRange();
17629       return ExprError();
17630     }
17631 
17632   //  - nothing else
17633   } else {
17634     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17635       << VD << E->getSourceRange();
17636     return ExprError();
17637   }
17638 
17639   // Modifying the declaration like this is friendly to IR-gen but
17640   // also really dangerous.
17641   VD->setType(DestType);
17642   E->setType(Type);
17643   E->setValueKind(ValueKind);
17644   return E;
17645 }
17646 
17647 /// Check a cast of an unknown-any type.  We intentionally only
17648 /// trigger this for C-style casts.
17649 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17650                                      Expr *CastExpr, CastKind &CastKind,
17651                                      ExprValueKind &VK, CXXCastPath &Path) {
17652   // The type we're casting to must be either void or complete.
17653   if (!CastType->isVoidType() &&
17654       RequireCompleteType(TypeRange.getBegin(), CastType,
17655                           diag::err_typecheck_cast_to_incomplete))
17656     return ExprError();
17657 
17658   // Rewrite the casted expression from scratch.
17659   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17660   if (!result.isUsable()) return ExprError();
17661 
17662   CastExpr = result.get();
17663   VK = CastExpr->getValueKind();
17664   CastKind = CK_NoOp;
17665 
17666   return CastExpr;
17667 }
17668 
17669 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17670   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17671 }
17672 
17673 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17674                                     Expr *arg, QualType &paramType) {
17675   // If the syntactic form of the argument is not an explicit cast of
17676   // any sort, just do default argument promotion.
17677   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17678   if (!castArg) {
17679     ExprResult result = DefaultArgumentPromotion(arg);
17680     if (result.isInvalid()) return ExprError();
17681     paramType = result.get()->getType();
17682     return result;
17683   }
17684 
17685   // Otherwise, use the type that was written in the explicit cast.
17686   assert(!arg->hasPlaceholderType());
17687   paramType = castArg->getTypeAsWritten();
17688 
17689   // Copy-initialize a parameter of that type.
17690   InitializedEntity entity =
17691     InitializedEntity::InitializeParameter(Context, paramType,
17692                                            /*consumed*/ false);
17693   return PerformCopyInitialization(entity, callLoc, arg);
17694 }
17695 
17696 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17697   Expr *orig = E;
17698   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17699   while (true) {
17700     E = E->IgnoreParenImpCasts();
17701     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17702       E = call->getCallee();
17703       diagID = diag::err_uncasted_call_of_unknown_any;
17704     } else {
17705       break;
17706     }
17707   }
17708 
17709   SourceLocation loc;
17710   NamedDecl *d;
17711   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17712     loc = ref->getLocation();
17713     d = ref->getDecl();
17714   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17715     loc = mem->getMemberLoc();
17716     d = mem->getMemberDecl();
17717   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17718     diagID = diag::err_uncasted_call_of_unknown_any;
17719     loc = msg->getSelectorStartLoc();
17720     d = msg->getMethodDecl();
17721     if (!d) {
17722       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17723         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17724         << orig->getSourceRange();
17725       return ExprError();
17726     }
17727   } else {
17728     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17729       << E->getSourceRange();
17730     return ExprError();
17731   }
17732 
17733   S.Diag(loc, diagID) << d << orig->getSourceRange();
17734 
17735   // Never recoverable.
17736   return ExprError();
17737 }
17738 
17739 /// Check for operands with placeholder types and complain if found.
17740 /// Returns ExprError() if there was an error and no recovery was possible.
17741 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17742   if (!getLangOpts().CPlusPlus) {
17743     // C cannot handle TypoExpr nodes on either side of a binop because it
17744     // doesn't handle dependent types properly, so make sure any TypoExprs have
17745     // been dealt with before checking the operands.
17746     ExprResult Result = CorrectDelayedTyposInExpr(E);
17747     if (!Result.isUsable()) return ExprError();
17748     E = Result.get();
17749   }
17750 
17751   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17752   if (!placeholderType) return E;
17753 
17754   switch (placeholderType->getKind()) {
17755 
17756   // Overloaded expressions.
17757   case BuiltinType::Overload: {
17758     // Try to resolve a single function template specialization.
17759     // This is obligatory.
17760     ExprResult Result = E;
17761     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17762       return Result;
17763 
17764     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17765     // leaves Result unchanged on failure.
17766     Result = E;
17767     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17768       return Result;
17769 
17770     // If that failed, try to recover with a call.
17771     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17772                          /*complain*/ true);
17773     return Result;
17774   }
17775 
17776   // Bound member functions.
17777   case BuiltinType::BoundMember: {
17778     ExprResult result = E;
17779     const Expr *BME = E->IgnoreParens();
17780     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17781     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17782     if (isa<CXXPseudoDestructorExpr>(BME)) {
17783       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17784     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17785       if (ME->getMemberNameInfo().getName().getNameKind() ==
17786           DeclarationName::CXXDestructorName)
17787         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17788     }
17789     tryToRecoverWithCall(result, PD,
17790                          /*complain*/ true);
17791     return result;
17792   }
17793 
17794   // ARC unbridged casts.
17795   case BuiltinType::ARCUnbridgedCast: {
17796     Expr *realCast = stripARCUnbridgedCast(E);
17797     diagnoseARCUnbridgedCast(realCast);
17798     return realCast;
17799   }
17800 
17801   // Expressions of unknown type.
17802   case BuiltinType::UnknownAny:
17803     return diagnoseUnknownAnyExpr(*this, E);
17804 
17805   // Pseudo-objects.
17806   case BuiltinType::PseudoObject:
17807     return checkPseudoObjectRValue(E);
17808 
17809   case BuiltinType::BuiltinFn: {
17810     // Accept __noop without parens by implicitly converting it to a call expr.
17811     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17812     if (DRE) {
17813       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17814       if (FD->getBuiltinID() == Builtin::BI__noop) {
17815         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17816                               CK_BuiltinFnToFnPtr)
17817                 .get();
17818         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17819                                 VK_RValue, SourceLocation());
17820       }
17821     }
17822 
17823     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17824     return ExprError();
17825   }
17826 
17827   // Expressions of unknown type.
17828   case BuiltinType::OMPArraySection:
17829     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17830     return ExprError();
17831 
17832   // Everything else should be impossible.
17833 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17834   case BuiltinType::Id:
17835 #include "clang/Basic/OpenCLImageTypes.def"
17836 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17837   case BuiltinType::Id:
17838 #include "clang/Basic/OpenCLExtensionTypes.def"
17839 #define SVE_TYPE(Name, Id, SingletonId) \
17840   case BuiltinType::Id:
17841 #include "clang/Basic/AArch64SVEACLETypes.def"
17842 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17843 #define PLACEHOLDER_TYPE(Id, SingletonId)
17844 #include "clang/AST/BuiltinTypes.def"
17845     break;
17846   }
17847 
17848   llvm_unreachable("invalid placeholder type!");
17849 }
17850 
17851 bool Sema::CheckCaseExpression(Expr *E) {
17852   if (E->isTypeDependent())
17853     return true;
17854   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17855     return E->getType()->isIntegralOrEnumerationType();
17856   return false;
17857 }
17858 
17859 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17860 ExprResult
17861 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17862   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17863          "Unknown Objective-C Boolean value!");
17864   QualType BoolT = Context.ObjCBuiltinBoolTy;
17865   if (!Context.getBOOLDecl()) {
17866     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17867                         Sema::LookupOrdinaryName);
17868     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17869       NamedDecl *ND = Result.getFoundDecl();
17870       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17871         Context.setBOOLDecl(TD);
17872     }
17873   }
17874   if (Context.getBOOLDecl())
17875     BoolT = Context.getBOOLType();
17876   return new (Context)
17877       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17878 }
17879 
17880 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17881     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17882     SourceLocation RParen) {
17883 
17884   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17885 
17886   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17887     return Spec.getPlatform() == Platform;
17888   });
17889 
17890   VersionTuple Version;
17891   if (Spec != AvailSpecs.end())
17892     Version = Spec->getVersion();
17893 
17894   // The use of `@available` in the enclosing function should be analyzed to
17895   // warn when it's used inappropriately (i.e. not if(@available)).
17896   if (getCurFunctionOrMethodDecl())
17897     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17898   else if (getCurBlock() || getCurLambda())
17899     getCurFunction()->HasPotentialAvailabilityViolations = true;
17900 
17901   return new (Context)
17902       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
17903 }
17904