]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - clang/lib/Sema/SemaExpr.cpp
Vendor import of llvm-project branch release/11.x
[FreeBSD/FreeBSD.git] / clang / lib / Sema / SemaExpr.cpp
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 "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84
85   return true;
86 }
87
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
98     }
99   }
100 }
101
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180
181   S.MaybeSuggestAddingStaticToDecl(Current);
182
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296
297     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298       return true;
299   }
300
301   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302     // Lambdas are only default-constructible or assignable in C++2a onwards.
303     if (MD->getParent()->isLambda() &&
304         ((isa<CXXConstructorDecl>(MD) &&
305           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308         << !isa<CXXConstructorDecl>(MD);
309     }
310   }
311
312   auto getReferencedObjCProp = [](const NamedDecl *D) ->
313                                       const ObjCPropertyDecl * {
314     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315       return MD->findPropertyDecl();
316     return nullptr;
317   };
318   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320       return true;
321   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322       return true;
323   }
324
325   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326   // Only the variables omp_in and omp_out are allowed in the combiner.
327   // Only the variables omp_priv and omp_orig are allowed in the
328   // initializer-clause.
329   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331       isa<VarDecl>(D)) {
332     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333         << getCurFunction()->HasOMPDeclareReductionCombiner;
334     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335     return true;
336   }
337
338   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339   //  List-items in map clauses on this construct may only refer to the declared
340   //  variable var and entities that could be referenced by a procedure defined
341   //  at the same location
342   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
344       isa<VarDecl>(D)) {
345     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346         << DMD->getVarName().getAsString();
347     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348     return true;
349   }
350
351   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352                              AvoidPartialAvailabilityChecks, ClassReceiver);
353
354   DiagnoseUnusedOfDecl(*this, D, Loc);
355
356   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357
358   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
359     if (const auto *VD = dyn_cast<ValueDecl>(D))
360       checkDeviceDecl(VD, Loc);
361
362     if (!Context.getTargetInfo().isTLSSupported())
363       if (const auto *VD = dyn_cast<VarDecl>(D))
364         if (VD->getTLSKind() != VarDecl::TLS_None)
365           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
366   }
367
368   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
369       !isUnevaluatedContext()) {
370     // C++ [expr.prim.req.nested] p3
371     //   A local parameter shall only appear as an unevaluated operand
372     //   (Clause 8) within the constraint-expression.
373     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
374         << D;
375     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
376     return true;
377   }
378
379   return false;
380 }
381
382 /// DiagnoseSentinelCalls - This routine checks whether a call or
383 /// message-send is to a declaration with the sentinel attribute, and
384 /// if so, it checks that the requirements of the sentinel are
385 /// satisfied.
386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
387                                  ArrayRef<Expr *> Args) {
388   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
389   if (!attr)
390     return;
391
392   // The number of formal parameters of the declaration.
393   unsigned numFormalParams;
394
395   // The kind of declaration.  This is also an index into a %select in
396   // the diagnostic.
397   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
398
399   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
400     numFormalParams = MD->param_size();
401     calleeType = CT_Method;
402   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403     numFormalParams = FD->param_size();
404     calleeType = CT_Function;
405   } else if (isa<VarDecl>(D)) {
406     QualType type = cast<ValueDecl>(D)->getType();
407     const FunctionType *fn = nullptr;
408     if (const PointerType *ptr = type->getAs<PointerType>()) {
409       fn = ptr->getPointeeType()->getAs<FunctionType>();
410       if (!fn) return;
411       calleeType = CT_Function;
412     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
413       fn = ptr->getPointeeType()->castAs<FunctionType>();
414       calleeType = CT_Block;
415     } else {
416       return;
417     }
418
419     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
420       numFormalParams = proto->getNumParams();
421     } else {
422       numFormalParams = 0;
423     }
424   } else {
425     return;
426   }
427
428   // "nullPos" is the number of formal parameters at the end which
429   // effectively count as part of the variadic arguments.  This is
430   // useful if you would prefer to not have *any* formal parameters,
431   // but the language forces you to have at least one.
432   unsigned nullPos = attr->getNullPos();
433   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
434   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
435
436   // The number of arguments which should follow the sentinel.
437   unsigned numArgsAfterSentinel = attr->getSentinel();
438
439   // If there aren't enough arguments for all the formal parameters,
440   // the sentinel, and the args after the sentinel, complain.
441   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
442     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
443     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
444     return;
445   }
446
447   // Otherwise, find the sentinel expression.
448   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
449   if (!sentinelExpr) return;
450   if (sentinelExpr->isValueDependent()) return;
451   if (Context.isSentinelNullExpr(sentinelExpr)) return;
452
453   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
454   // or 'NULL' if those are actually defined in the context.  Only use
455   // 'nil' for ObjC methods, where it's much more likely that the
456   // variadic arguments form a list of object pointers.
457   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
458   std::string NullValue;
459   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
460     NullValue = "nil";
461   else if (getLangOpts().CPlusPlus11)
462     NullValue = "nullptr";
463   else if (PP.isMacroDefined("NULL"))
464     NullValue = "NULL";
465   else
466     NullValue = "(void*) 0";
467
468   if (MissingNilLoc.isInvalid())
469     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
470   else
471     Diag(MissingNilLoc, diag::warn_missing_sentinel)
472       << int(calleeType)
473       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
474   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
475 }
476
477 SourceRange Sema::getExprRange(Expr *E) const {
478   return E ? E->getSourceRange() : SourceRange();
479 }
480
481 //===----------------------------------------------------------------------===//
482 //  Standard Promotions and Conversions
483 //===----------------------------------------------------------------------===//
484
485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
487   // Handle any placeholder expressions which made it here.
488   if (E->getType()->isPlaceholderType()) {
489     ExprResult result = CheckPlaceholderExpr(E);
490     if (result.isInvalid()) return ExprError();
491     E = result.get();
492   }
493
494   QualType Ty = E->getType();
495   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
496
497   if (Ty->isFunctionType()) {
498     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
499       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
500         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
501           return ExprError();
502
503     E = ImpCastExprToType(E, Context.getPointerType(Ty),
504                           CK_FunctionToPointerDecay).get();
505   } else if (Ty->isArrayType()) {
506     // In C90 mode, arrays only promote to pointers if the array expression is
507     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
508     // type 'array of type' is converted to an expression that has type 'pointer
509     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
510     // that has type 'array of type' ...".  The relevant change is "an lvalue"
511     // (C90) to "an expression" (C99).
512     //
513     // C++ 4.2p1:
514     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
515     // T" can be converted to an rvalue of type "pointer to T".
516     //
517     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
518       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
519                             CK_ArrayToPointerDecay).get();
520   }
521   return E;
522 }
523
524 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
525   // Check to see if we are dereferencing a null pointer.  If so,
526   // and if not volatile-qualified, this is undefined behavior that the
527   // optimizer will delete, so warn about it.  People sometimes try to use this
528   // to get a deterministic trap and are surprised by clang's behavior.  This
529   // only handles the pattern "*null", which is a very syntactic check.
530   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
531   if (UO && UO->getOpcode() == UO_Deref &&
532       UO->getSubExpr()->getType()->isPointerType()) {
533     const LangAS AS =
534         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
535     if ((!isTargetAddressSpace(AS) ||
536          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
537         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
538             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
539         !UO->getType().isVolatileQualified()) {
540       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
541                             S.PDiag(diag::warn_indirection_through_null)
542                                 << UO->getSubExpr()->getSourceRange());
543       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
544                             S.PDiag(diag::note_indirection_through_null));
545     }
546   }
547 }
548
549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
550                                     SourceLocation AssignLoc,
551                                     const Expr* RHS) {
552   const ObjCIvarDecl *IV = OIRE->getDecl();
553   if (!IV)
554     return;
555
556   DeclarationName MemberName = IV->getDeclName();
557   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558   if (!Member || !Member->isStr("isa"))
559     return;
560
561   const Expr *Base = OIRE->getBase();
562   QualType BaseType = Base->getType();
563   if (OIRE->isArrow())
564     BaseType = BaseType->getPointeeType();
565   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
566     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
567       ObjCInterfaceDecl *ClassDeclared = nullptr;
568       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
569       if (!ClassDeclared->getSuperClass()
570           && (*ClassDeclared->ivar_begin()) == IV) {
571         if (RHS) {
572           NamedDecl *ObjectSetClass =
573             S.LookupSingleName(S.TUScope,
574                                &S.Context.Idents.get("object_setClass"),
575                                SourceLocation(), S.LookupOrdinaryName);
576           if (ObjectSetClass) {
577             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
578             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
579                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580                                               "object_setClass(")
581                 << FixItHint::CreateReplacement(
582                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
583                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
584           }
585           else
586             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
587         } else {
588           NamedDecl *ObjectGetClass =
589             S.LookupSingleName(S.TUScope,
590                                &S.Context.Idents.get("object_getClass"),
591                                SourceLocation(), S.LookupOrdinaryName);
592           if (ObjectGetClass)
593             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
594                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595                                               "object_getClass(")
596                 << FixItHint::CreateReplacement(
597                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
598           else
599             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
600         }
601         S.Diag(IV->getLocation(), diag::note_ivar_decl);
602       }
603     }
604 }
605
606 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
607   // Handle any placeholder expressions which made it here.
608   if (E->getType()->isPlaceholderType()) {
609     ExprResult result = CheckPlaceholderExpr(E);
610     if (result.isInvalid()) return ExprError();
611     E = result.get();
612   }
613
614   // C++ [conv.lval]p1:
615   //   A glvalue of a non-function, non-array type T can be
616   //   converted to a prvalue.
617   if (!E->isGLValue()) return E;
618
619   QualType T = E->getType();
620   assert(!T.isNull() && "r-value conversion on typeless expression?");
621
622   // lvalue-to-rvalue conversion cannot be applied to function or array types.
623   if (T->isFunctionType() || T->isArrayType())
624     return E;
625
626   // We don't want to throw lvalue-to-rvalue casts on top of
627   // expressions of certain types in C++.
628   if (getLangOpts().CPlusPlus &&
629       (E->getType() == Context.OverloadTy ||
630        T->isDependentType() ||
631        T->isRecordType()))
632     return E;
633
634   // The C standard is actually really unclear on this point, and
635   // DR106 tells us what the result should be but not why.  It's
636   // generally best to say that void types just doesn't undergo
637   // lvalue-to-rvalue at all.  Note that expressions of unqualified
638   // 'void' type are never l-values, but qualified void can be.
639   if (T->isVoidType())
640     return E;
641
642   // OpenCL usually rejects direct accesses to values of 'half' type.
643   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
644       T->isHalfType()) {
645     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
646       << 0 << T;
647     return ExprError();
648   }
649
650   CheckForNullPointerDereference(*this, E);
651   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
652     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
653                                      &Context.Idents.get("object_getClass"),
654                                      SourceLocation(), LookupOrdinaryName);
655     if (ObjectGetClass)
656       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
657           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
658           << FixItHint::CreateReplacement(
659                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
660     else
661       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
662   }
663   else if (const ObjCIvarRefExpr *OIRE =
664             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
665     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
666
667   // C++ [conv.lval]p1:
668   //   [...] If T is a non-class type, the type of the prvalue is the
669   //   cv-unqualified version of T. Otherwise, the type of the
670   //   rvalue is T.
671   //
672   // C99 6.3.2.1p2:
673   //   If the lvalue has qualified type, the value has the unqualified
674   //   version of the type of the lvalue; otherwise, the value has the
675   //   type of the lvalue.
676   if (T.hasQualifiers())
677     T = T.getUnqualifiedType();
678
679   // Under the MS ABI, lock down the inheritance model now.
680   if (T->isMemberPointerType() &&
681       Context.getTargetInfo().getCXXABI().isMicrosoft())
682     (void)isCompleteType(E->getExprLoc(), T);
683
684   ExprResult Res = CheckLValueToRValueConversionOperand(E);
685   if (Res.isInvalid())
686     return Res;
687   E = Res.get();
688
689   // Loading a __weak object implicitly retains the value, so we need a cleanup to
690   // balance that.
691   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
692     Cleanup.setExprNeedsCleanups(true);
693
694   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
695     Cleanup.setExprNeedsCleanups(true);
696
697   // C++ [conv.lval]p3:
698   //   If T is cv std::nullptr_t, the result is a null pointer constant.
699   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
700   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
701
702   // C11 6.3.2.1p2:
703   //   ... if the lvalue has atomic type, the value has the non-atomic version
704   //   of the type of the lvalue ...
705   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
706     T = Atomic->getValueType().getUnqualifiedType();
707     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
708                                    nullptr, VK_RValue);
709   }
710
711   return Res;
712 }
713
714 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
715   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
716   if (Res.isInvalid())
717     return ExprError();
718   Res = DefaultLvalueConversion(Res.get());
719   if (Res.isInvalid())
720     return ExprError();
721   return Res;
722 }
723
724 /// CallExprUnaryConversions - a special case of an unary conversion
725 /// performed on a function designator of a call expression.
726 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
727   QualType Ty = E->getType();
728   ExprResult Res = E;
729   // Only do implicit cast for a function type, but not for a pointer
730   // to function type.
731   if (Ty->isFunctionType()) {
732     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
733                             CK_FunctionToPointerDecay);
734     if (Res.isInvalid())
735       return ExprError();
736   }
737   Res = DefaultLvalueConversion(Res.get());
738   if (Res.isInvalid())
739     return ExprError();
740   return Res.get();
741 }
742
743 /// UsualUnaryConversions - Performs various conversions that are common to most
744 /// operators (C99 6.3). The conversions of array and function types are
745 /// sometimes suppressed. For example, the array->pointer conversion doesn't
746 /// apply if the array is an argument to the sizeof or address (&) operators.
747 /// In these instances, this routine should *not* be called.
748 ExprResult Sema::UsualUnaryConversions(Expr *E) {
749   // First, convert to an r-value.
750   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
751   if (Res.isInvalid())
752     return ExprError();
753   E = Res.get();
754
755   QualType Ty = E->getType();
756   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
757
758   // Half FP have to be promoted to float unless it is natively supported
759   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
760     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
761
762   // Try to perform integral promotions if the object has a theoretically
763   // promotable type.
764   if (Ty->isIntegralOrUnscopedEnumerationType()) {
765     // C99 6.3.1.1p2:
766     //
767     //   The following may be used in an expression wherever an int or
768     //   unsigned int may be used:
769     //     - an object or expression with an integer type whose integer
770     //       conversion rank is less than or equal to the rank of int
771     //       and unsigned int.
772     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
773     //
774     //   If an int can represent all values of the original type, the
775     //   value is converted to an int; otherwise, it is converted to an
776     //   unsigned int. These are called the integer promotions. All
777     //   other types are unchanged by the integer promotions.
778
779     QualType PTy = Context.isPromotableBitField(E);
780     if (!PTy.isNull()) {
781       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
782       return E;
783     }
784     if (Ty->isPromotableIntegerType()) {
785       QualType PT = Context.getPromotedIntegerType(Ty);
786       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
787       return E;
788     }
789   }
790   return E;
791 }
792
793 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
794 /// do not have a prototype. Arguments that have type float or __fp16
795 /// are promoted to double. All other argument types are converted by
796 /// UsualUnaryConversions().
797 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
798   QualType Ty = E->getType();
799   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
800
801   ExprResult Res = UsualUnaryConversions(E);
802   if (Res.isInvalid())
803     return ExprError();
804   E = Res.get();
805
806   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
807   // promote to double.
808   // Note that default argument promotion applies only to float (and
809   // half/fp16); it does not apply to _Float16.
810   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811   if (BTy && (BTy->getKind() == BuiltinType::Half ||
812               BTy->getKind() == BuiltinType::Float)) {
813     if (getLangOpts().OpenCL &&
814         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
815         if (BTy->getKind() == BuiltinType::Half) {
816             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
817         }
818     } else {
819       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
820     }
821   }
822
823   // C++ performs lvalue-to-rvalue conversion as a default argument
824   // promotion, even on class types, but note:
825   //   C++11 [conv.lval]p2:
826   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
827   //     operand or a subexpression thereof the value contained in the
828   //     referenced object is not accessed. Otherwise, if the glvalue
829   //     has a class type, the conversion copy-initializes a temporary
830   //     of type T from the glvalue and the result of the conversion
831   //     is a prvalue for the temporary.
832   // FIXME: add some way to gate this entire thing for correctness in
833   // potentially potentially evaluated contexts.
834   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835     ExprResult Temp = PerformCopyInitialization(
836                        InitializedEntity::InitializeTemporary(E->getType()),
837                                                 E->getExprLoc(), E);
838     if (Temp.isInvalid())
839       return ExprError();
840     E = Temp.get();
841   }
842
843   return E;
844 }
845
846 /// Determine the degree of POD-ness for an expression.
847 /// Incomplete types are considered POD, since this check can be performed
848 /// when we're in an unevaluated context.
849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850   if (Ty->isIncompleteType()) {
851     // C++11 [expr.call]p7:
852     //   After these conversions, if the argument does not have arithmetic,
853     //   enumeration, pointer, pointer to member, or class type, the program
854     //   is ill-formed.
855     //
856     // Since we've already performed array-to-pointer and function-to-pointer
857     // decay, the only such type in C++ is cv void. This also handles
858     // initializer lists as variadic arguments.
859     if (Ty->isVoidType())
860       return VAK_Invalid;
861
862     if (Ty->isObjCObjectType())
863       return VAK_Invalid;
864     return VAK_Valid;
865   }
866
867   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
868     return VAK_Invalid;
869
870   if (Ty.isCXX98PODType(Context))
871     return VAK_Valid;
872
873   // C++11 [expr.call]p7:
874   //   Passing a potentially-evaluated argument of class type (Clause 9)
875   //   having a non-trivial copy constructor, a non-trivial move constructor,
876   //   or a non-trivial destructor, with no corresponding parameter,
877   //   is conditionally-supported with implementation-defined semantics.
878   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880       if (!Record->hasNonTrivialCopyConstructor() &&
881           !Record->hasNonTrivialMoveConstructor() &&
882           !Record->hasNonTrivialDestructor())
883         return VAK_ValidInCXX11;
884
885   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
886     return VAK_Valid;
887
888   if (Ty->isObjCObjectType())
889     return VAK_Invalid;
890
891   if (getLangOpts().MSVCCompat)
892     return VAK_MSVCUndefined;
893
894   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895   // permitted to reject them. We should consider doing so.
896   return VAK_Undefined;
897 }
898
899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900   // Don't allow one to pass an Objective-C interface to a vararg.
901   const QualType &Ty = E->getType();
902   VarArgKind VAK = isValidVarArgType(Ty);
903
904   // Complain about passing non-POD types through varargs.
905   switch (VAK) {
906   case VAK_ValidInCXX11:
907     DiagRuntimeBehavior(
908         E->getBeginLoc(), nullptr,
909         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
910     LLVM_FALLTHROUGH;
911   case VAK_Valid:
912     if (Ty->isRecordType()) {
913       // This is unlikely to be what the user intended. If the class has a
914       // 'c_str' member function, the user probably meant to call that.
915       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
916                           PDiag(diag::warn_pass_class_arg_to_vararg)
917                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
918     }
919     break;
920
921   case VAK_Undefined:
922   case VAK_MSVCUndefined:
923     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
924                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
925                             << getLangOpts().CPlusPlus11 << Ty << CT);
926     break;
927
928   case VAK_Invalid:
929     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
930       Diag(E->getBeginLoc(),
931            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
932           << Ty << CT;
933     else if (Ty->isObjCObjectType())
934       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
935                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
936                               << Ty << CT);
937     else
938       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
939           << isa<InitListExpr>(E) << Ty << CT;
940     break;
941   }
942 }
943
944 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
945 /// will create a trap if the resulting type is not a POD type.
946 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
947                                                   FunctionDecl *FDecl) {
948   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
949     // Strip the unbridged-cast placeholder expression off, if applicable.
950     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
951         (CT == VariadicMethod ||
952          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
953       E = stripARCUnbridgedCast(E);
954
955     // Otherwise, do normal placeholder checking.
956     } else {
957       ExprResult ExprRes = CheckPlaceholderExpr(E);
958       if (ExprRes.isInvalid())
959         return ExprError();
960       E = ExprRes.get();
961     }
962   }
963
964   ExprResult ExprRes = DefaultArgumentPromotion(E);
965   if (ExprRes.isInvalid())
966     return ExprError();
967
968   // Copy blocks to the heap.
969   if (ExprRes.get()->getType()->isBlockPointerType())
970     maybeExtendBlockObject(ExprRes);
971
972   E = ExprRes.get();
973
974   // Diagnostics regarding non-POD argument types are
975   // emitted along with format string checking in Sema::CheckFunctionCall().
976   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977     // Turn this into a trap.
978     CXXScopeSpec SS;
979     SourceLocation TemplateKWLoc;
980     UnqualifiedId Name;
981     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
982                        E->getBeginLoc());
983     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
984                                           /*HasTrailingLParen=*/true,
985                                           /*IsAddressOfOperand=*/false);
986     if (TrapFn.isInvalid())
987       return ExprError();
988
989     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
990                                     None, E->getEndLoc());
991     if (Call.isInvalid())
992       return ExprError();
993
994     ExprResult Comma =
995         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
996     if (Comma.isInvalid())
997       return ExprError();
998     return Comma.get();
999   }
1000
1001   if (!getLangOpts().CPlusPlus &&
1002       RequireCompleteType(E->getExprLoc(), E->getType(),
1003                           diag::err_call_incomplete_argument))
1004     return ExprError();
1005
1006   return E;
1007 }
1008
1009 /// Converts an integer to complex float type.  Helper function of
1010 /// UsualArithmeticConversions()
1011 ///
1012 /// \return false if the integer expression is an integer type and is
1013 /// successfully converted to the complex type.
1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015                                                   ExprResult &ComplexExpr,
1016                                                   QualType IntTy,
1017                                                   QualType ComplexTy,
1018                                                   bool SkipCast) {
1019   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020   if (SkipCast) return false;
1021   if (IntTy->isIntegerType()) {
1022     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025                                   CK_FloatingRealToComplex);
1026   } else {
1027     assert(IntTy->isComplexIntegerType());
1028     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029                                   CK_IntegralComplexToFloatingComplex);
1030   }
1031   return false;
1032 }
1033
1034 /// Handle arithmetic conversion with complex types.  Helper function of
1035 /// UsualArithmeticConversions()
1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037                                              ExprResult &RHS, QualType LHSType,
1038                                              QualType RHSType,
1039                                              bool IsCompAssign) {
1040   // if we have an integer operand, the result is the complex type.
1041   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1042                                              /*skipCast*/false))
1043     return LHSType;
1044   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045                                              /*skipCast*/IsCompAssign))
1046     return RHSType;
1047
1048   // This handles complex/complex, complex/float, or float/complex.
1049   // When both operands are complex, the shorter operand is converted to the
1050   // type of the longer, and that is the type of the result. This corresponds
1051   // to what is done when combining two real floating-point operands.
1052   // The fun begins when size promotion occur across type domains.
1053   // From H&S 6.3.4: When one operand is complex and the other is a real
1054   // floating-point type, the less precise type is converted, within it's
1055   // real or complex domain, to the precision of the other type. For example,
1056   // when combining a "long double" with a "double _Complex", the
1057   // "double _Complex" is promoted to "long double _Complex".
1058
1059   // Compute the rank of the two types, regardless of whether they are complex.
1060   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061
1062   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064   QualType LHSElementType =
1065       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066   QualType RHSElementType =
1067       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1068
1069   QualType ResultType = S.Context.getComplexType(LHSElementType);
1070   if (Order < 0) {
1071     // Promote the precision of the LHS if not an assignment.
1072     ResultType = S.Context.getComplexType(RHSElementType);
1073     if (!IsCompAssign) {
1074       if (LHSComplexType)
1075         LHS =
1076             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1077       else
1078         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1079     }
1080   } else if (Order > 0) {
1081     // Promote the precision of the RHS.
1082     if (RHSComplexType)
1083       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1084     else
1085       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1086   }
1087   return ResultType;
1088 }
1089
1090 /// Handle arithmetic conversion from integer to float.  Helper function
1091 /// of UsualArithmeticConversions()
1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093                                            ExprResult &IntExpr,
1094                                            QualType FloatTy, QualType IntTy,
1095                                            bool ConvertFloat, bool ConvertInt) {
1096   if (IntTy->isIntegerType()) {
1097     if (ConvertInt)
1098       // Convert intExpr to the lhs floating point type.
1099       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100                                     CK_IntegralToFloating);
1101     return FloatTy;
1102   }
1103
1104   // Convert both sides to the appropriate complex float.
1105   assert(IntTy->isComplexIntegerType());
1106   QualType result = S.Context.getComplexType(FloatTy);
1107
1108   // _Complex int -> _Complex float
1109   if (ConvertInt)
1110     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111                                   CK_IntegralComplexToFloatingComplex);
1112
1113   // float -> _Complex float
1114   if (ConvertFloat)
1115     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116                                     CK_FloatingRealToComplex);
1117
1118   return result;
1119 }
1120
1121 /// Handle arithmethic conversion with floating point types.  Helper
1122 /// function of UsualArithmeticConversions()
1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124                                       ExprResult &RHS, QualType LHSType,
1125                                       QualType RHSType, bool IsCompAssign) {
1126   bool LHSFloat = LHSType->isRealFloatingType();
1127   bool RHSFloat = RHSType->isRealFloatingType();
1128
1129   // If we have two real floating types, convert the smaller operand
1130   // to the bigger result.
1131   if (LHSFloat && RHSFloat) {
1132     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1133     if (order > 0) {
1134       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1135       return LHSType;
1136     }
1137
1138     assert(order < 0 && "illegal float comparison");
1139     if (!IsCompAssign)
1140       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1141     return RHSType;
1142   }
1143
1144   if (LHSFloat) {
1145     // Half FP has to be promoted to float unless it is natively supported
1146     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1147       LHSType = S.Context.FloatTy;
1148
1149     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1150                                       /*ConvertFloat=*/!IsCompAssign,
1151                                       /*ConvertInt=*/ true);
1152   }
1153   assert(RHSFloat);
1154   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1155                                     /*convertInt=*/ true,
1156                                     /*convertFloat=*/!IsCompAssign);
1157 }
1158
1159 /// Diagnose attempts to convert between __float128 and long double if
1160 /// there is no support for such conversion. Helper function of
1161 /// UsualArithmeticConversions().
1162 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1163                                       QualType RHSType) {
1164   /*  No issue converting if at least one of the types is not a floating point
1165       type or the two types have the same rank.
1166   */
1167   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1168       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1169     return false;
1170
1171   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1172          "The remaining types must be floating point types.");
1173
1174   auto *LHSComplex = LHSType->getAs<ComplexType>();
1175   auto *RHSComplex = RHSType->getAs<ComplexType>();
1176
1177   QualType LHSElemType = LHSComplex ?
1178     LHSComplex->getElementType() : LHSType;
1179   QualType RHSElemType = RHSComplex ?
1180     RHSComplex->getElementType() : RHSType;
1181
1182   // No issue if the two types have the same representation
1183   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1184       &S.Context.getFloatTypeSemantics(RHSElemType))
1185     return false;
1186
1187   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1188                                 RHSElemType == S.Context.LongDoubleTy);
1189   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1190                             RHSElemType == S.Context.Float128Ty);
1191
1192   // We've handled the situation where __float128 and long double have the same
1193   // representation. We allow all conversions for all possible long double types
1194   // except PPC's double double.
1195   return Float128AndLongDouble &&
1196     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1197      &llvm::APFloat::PPCDoubleDouble());
1198 }
1199
1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1201
1202 namespace {
1203 /// These helper callbacks are placed in an anonymous namespace to
1204 /// permit their use as function template parameters.
1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1207 }
1208
1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211                              CK_IntegralComplexCast);
1212 }
1213 }
1214
1215 /// Handle integer arithmetic conversions.  Helper function of
1216 /// UsualArithmeticConversions()
1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219                                         ExprResult &RHS, QualType LHSType,
1220                                         QualType RHSType, bool IsCompAssign) {
1221   // The rules for this case are in C99 6.3.1.8
1222   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225   if (LHSSigned == RHSSigned) {
1226     // Same signedness; use the higher-ranked type
1227     if (order >= 0) {
1228       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1229       return LHSType;
1230     } else if (!IsCompAssign)
1231       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1232     return RHSType;
1233   } else if (order != (LHSSigned ? 1 : -1)) {
1234     // The unsigned type has greater than or equal rank to the
1235     // signed type, so use the unsigned type
1236     if (RHSSigned) {
1237       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1238       return LHSType;
1239     } else if (!IsCompAssign)
1240       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1241     return RHSType;
1242   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1243     // The two types are different widths; if we are here, that
1244     // means the signed type is larger than the unsigned type, so
1245     // use the signed type.
1246     if (LHSSigned) {
1247       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1248       return LHSType;
1249     } else if (!IsCompAssign)
1250       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1251     return RHSType;
1252   } else {
1253     // The signed type is higher-ranked than the unsigned type,
1254     // but isn't actually any bigger (like unsigned int and long
1255     // on most 32-bit systems).  Use the unsigned type corresponding
1256     // to the signed type.
1257     QualType result =
1258       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1259     RHS = (*doRHSCast)(S, RHS.get(), result);
1260     if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), result);
1262     return result;
1263   }
1264 }
1265
1266 /// Handle conversions with GCC complex int extension.  Helper function
1267 /// of UsualArithmeticConversions()
1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269                                            ExprResult &RHS, QualType LHSType,
1270                                            QualType RHSType,
1271                                            bool IsCompAssign) {
1272   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1274
1275   if (LHSComplexInt && RHSComplexInt) {
1276     QualType LHSEltType = LHSComplexInt->getElementType();
1277     QualType RHSEltType = RHSComplexInt->getElementType();
1278     QualType ScalarType =
1279       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1281
1282     return S.Context.getComplexType(ScalarType);
1283   }
1284
1285   if (LHSComplexInt) {
1286     QualType LHSEltType = LHSComplexInt->getElementType();
1287     QualType ScalarType =
1288       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290     QualType ComplexType = S.Context.getComplexType(ScalarType);
1291     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1292                               CK_IntegralRealToComplex);
1293
1294     return ComplexType;
1295   }
1296
1297   assert(RHSComplexInt);
1298
1299   QualType RHSEltType = RHSComplexInt->getElementType();
1300   QualType ScalarType =
1301     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303   QualType ComplexType = S.Context.getComplexType(ScalarType);
1304
1305   if (!IsCompAssign)
1306     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1307                               CK_IntegralRealToComplex);
1308   return ComplexType;
1309 }
1310
1311 /// Return the rank of a given fixed point or integer type. The value itself
1312 /// doesn't matter, but the values must be increasing with proper increasing
1313 /// rank as described in N1169 4.1.1.
1314 static unsigned GetFixedPointRank(QualType Ty) {
1315   const auto *BTy = Ty->getAs<BuiltinType>();
1316   assert(BTy && "Expected a builtin type.");
1317
1318   switch (BTy->getKind()) {
1319   case BuiltinType::ShortFract:
1320   case BuiltinType::UShortFract:
1321   case BuiltinType::SatShortFract:
1322   case BuiltinType::SatUShortFract:
1323     return 1;
1324   case BuiltinType::Fract:
1325   case BuiltinType::UFract:
1326   case BuiltinType::SatFract:
1327   case BuiltinType::SatUFract:
1328     return 2;
1329   case BuiltinType::LongFract:
1330   case BuiltinType::ULongFract:
1331   case BuiltinType::SatLongFract:
1332   case BuiltinType::SatULongFract:
1333     return 3;
1334   case BuiltinType::ShortAccum:
1335   case BuiltinType::UShortAccum:
1336   case BuiltinType::SatShortAccum:
1337   case BuiltinType::SatUShortAccum:
1338     return 4;
1339   case BuiltinType::Accum:
1340   case BuiltinType::UAccum:
1341   case BuiltinType::SatAccum:
1342   case BuiltinType::SatUAccum:
1343     return 5;
1344   case BuiltinType::LongAccum:
1345   case BuiltinType::ULongAccum:
1346   case BuiltinType::SatLongAccum:
1347   case BuiltinType::SatULongAccum:
1348     return 6;
1349   default:
1350     if (BTy->isInteger())
1351       return 0;
1352     llvm_unreachable("Unexpected fixed point or integer type");
1353   }
1354 }
1355
1356 /// handleFixedPointConversion - Fixed point operations between fixed
1357 /// point types and integers or other fixed point types do not fall under
1358 /// usual arithmetic conversion since these conversions could result in loss
1359 /// of precsision (N1169 4.1.4). These operations should be calculated with
1360 /// the full precision of their result type (N1169 4.1.6.2.1).
1361 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1362                                            QualType RHSTy) {
1363   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1364          "Expected at least one of the operands to be a fixed point type");
1365   assert((LHSTy->isFixedPointOrIntegerType() ||
1366           RHSTy->isFixedPointOrIntegerType()) &&
1367          "Special fixed point arithmetic operation conversions are only "
1368          "applied to ints or other fixed point types");
1369
1370   // If one operand has signed fixed-point type and the other operand has
1371   // unsigned fixed-point type, then the unsigned fixed-point operand is
1372   // converted to its corresponding signed fixed-point type and the resulting
1373   // type is the type of the converted operand.
1374   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1375     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1376   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1377     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1378
1379   // The result type is the type with the highest rank, whereby a fixed-point
1380   // conversion rank is always greater than an integer conversion rank; if the
1381   // type of either of the operands is a saturating fixedpoint type, the result
1382   // type shall be the saturating fixed-point type corresponding to the type
1383   // with the highest rank; the resulting value is converted (taking into
1384   // account rounding and overflow) to the precision of the resulting type.
1385   // Same ranks between signed and unsigned types are resolved earlier, so both
1386   // types are either signed or both unsigned at this point.
1387   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1388   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1389
1390   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1391
1392   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1393     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1394
1395   return ResultTy;
1396 }
1397
1398 /// Check that the usual arithmetic conversions can be performed on this pair of
1399 /// expressions that might be of enumeration type.
1400 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1401                                            SourceLocation Loc,
1402                                            Sema::ArithConvKind ACK) {
1403   // C++2a [expr.arith.conv]p1:
1404   //   If one operand is of enumeration type and the other operand is of a
1405   //   different enumeration type or a floating-point type, this behavior is
1406   //   deprecated ([depr.arith.conv.enum]).
1407   //
1408   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1409   // Eventually we will presumably reject these cases (in C++23 onwards?).
1410   QualType L = LHS->getType(), R = RHS->getType();
1411   bool LEnum = L->isUnscopedEnumerationType(),
1412        REnum = R->isUnscopedEnumerationType();
1413   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1414   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1415       (REnum && L->isFloatingType())) {
1416     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1417                     ? diag::warn_arith_conv_enum_float_cxx20
1418                     : diag::warn_arith_conv_enum_float)
1419         << LHS->getSourceRange() << RHS->getSourceRange()
1420         << (int)ACK << LEnum << L << R;
1421   } else if (!IsCompAssign && LEnum && REnum &&
1422              !S.Context.hasSameUnqualifiedType(L, R)) {
1423     unsigned DiagID;
1424     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1425         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1426       // If either enumeration type is unnamed, it's less likely that the
1427       // user cares about this, but this situation is still deprecated in
1428       // C++2a. Use a different warning group.
1429       DiagID = S.getLangOpts().CPlusPlus20
1430                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1431                     : diag::warn_arith_conv_mixed_anon_enum_types;
1432     } else if (ACK == Sema::ACK_Conditional) {
1433       // Conditional expressions are separated out because they have
1434       // historically had a different warning flag.
1435       DiagID = S.getLangOpts().CPlusPlus20
1436                    ? diag::warn_conditional_mixed_enum_types_cxx20
1437                    : diag::warn_conditional_mixed_enum_types;
1438     } else if (ACK == Sema::ACK_Comparison) {
1439       // Comparison expressions are separated out because they have
1440       // historically had a different warning flag.
1441       DiagID = S.getLangOpts().CPlusPlus20
1442                    ? diag::warn_comparison_mixed_enum_types_cxx20
1443                    : diag::warn_comparison_mixed_enum_types;
1444     } else {
1445       DiagID = S.getLangOpts().CPlusPlus20
1446                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1447                    : diag::warn_arith_conv_mixed_enum_types;
1448     }
1449     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1450                         << (int)ACK << L << R;
1451   }
1452 }
1453
1454 /// UsualArithmeticConversions - Performs various conversions that are common to
1455 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1456 /// routine returns the first non-arithmetic type found. The client is
1457 /// responsible for emitting appropriate error diagnostics.
1458 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1459                                           SourceLocation Loc,
1460                                           ArithConvKind ACK) {
1461   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1462
1463   if (ACK != ACK_CompAssign) {
1464     LHS = UsualUnaryConversions(LHS.get());
1465     if (LHS.isInvalid())
1466       return QualType();
1467   }
1468
1469   RHS = UsualUnaryConversions(RHS.get());
1470   if (RHS.isInvalid())
1471     return QualType();
1472
1473   // For conversion purposes, we ignore any qualifiers.
1474   // For example, "const float" and "float" are equivalent.
1475   QualType LHSType =
1476     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1477   QualType RHSType =
1478     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1479
1480   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1481   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1482     LHSType = AtomicLHS->getValueType();
1483
1484   // If both types are identical, no conversion is needed.
1485   if (LHSType == RHSType)
1486     return LHSType;
1487
1488   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1489   // The caller can deal with this (e.g. pointer + int).
1490   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1491     return QualType();
1492
1493   // Apply unary and bitfield promotions to the LHS's type.
1494   QualType LHSUnpromotedType = LHSType;
1495   if (LHSType->isPromotableIntegerType())
1496     LHSType = Context.getPromotedIntegerType(LHSType);
1497   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1498   if (!LHSBitfieldPromoteTy.isNull())
1499     LHSType = LHSBitfieldPromoteTy;
1500   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1501     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1502
1503   // If both types are identical, no conversion is needed.
1504   if (LHSType == RHSType)
1505     return LHSType;
1506
1507   // ExtInt types aren't subject to conversions between them or normal integers,
1508   // so this fails.
1509   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1510     return QualType();
1511
1512   // At this point, we have two different arithmetic types.
1513
1514   // Diagnose attempts to convert between __float128 and long double where
1515   // such conversions currently can't be handled.
1516   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1517     return QualType();
1518
1519   // Handle complex types first (C99 6.3.1.8p1).
1520   if (LHSType->isComplexType() || RHSType->isComplexType())
1521     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1522                                         ACK == ACK_CompAssign);
1523
1524   // Now handle "real" floating types (i.e. float, double, long double).
1525   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1526     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1527                                  ACK == ACK_CompAssign);
1528
1529   // Handle GCC complex int extension.
1530   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1531     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1532                                       ACK == ACK_CompAssign);
1533
1534   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1535     return handleFixedPointConversion(*this, LHSType, RHSType);
1536
1537   // Finally, we have two differing integer types.
1538   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1539            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1540 }
1541
1542 //===----------------------------------------------------------------------===//
1543 //  Semantic Analysis for various Expression Types
1544 //===----------------------------------------------------------------------===//
1545
1546
1547 ExprResult
1548 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1549                                 SourceLocation DefaultLoc,
1550                                 SourceLocation RParenLoc,
1551                                 Expr *ControllingExpr,
1552                                 ArrayRef<ParsedType> ArgTypes,
1553                                 ArrayRef<Expr *> ArgExprs) {
1554   unsigned NumAssocs = ArgTypes.size();
1555   assert(NumAssocs == ArgExprs.size());
1556
1557   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1558   for (unsigned i = 0; i < NumAssocs; ++i) {
1559     if (ArgTypes[i])
1560       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1561     else
1562       Types[i] = nullptr;
1563   }
1564
1565   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1566                                              ControllingExpr,
1567                                              llvm::makeArrayRef(Types, NumAssocs),
1568                                              ArgExprs);
1569   delete [] Types;
1570   return ER;
1571 }
1572
1573 ExprResult
1574 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1575                                  SourceLocation DefaultLoc,
1576                                  SourceLocation RParenLoc,
1577                                  Expr *ControllingExpr,
1578                                  ArrayRef<TypeSourceInfo *> Types,
1579                                  ArrayRef<Expr *> Exprs) {
1580   unsigned NumAssocs = Types.size();
1581   assert(NumAssocs == Exprs.size());
1582
1583   // Decay and strip qualifiers for the controlling expression type, and handle
1584   // placeholder type replacement. See committee discussion from WG14 DR423.
1585   {
1586     EnterExpressionEvaluationContext Unevaluated(
1587         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1588     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1589     if (R.isInvalid())
1590       return ExprError();
1591     ControllingExpr = R.get();
1592   }
1593
1594   // The controlling expression is an unevaluated operand, so side effects are
1595   // likely unintended.
1596   if (!inTemplateInstantiation() &&
1597       ControllingExpr->HasSideEffects(Context, false))
1598     Diag(ControllingExpr->getExprLoc(),
1599          diag::warn_side_effects_unevaluated_context);
1600
1601   bool TypeErrorFound = false,
1602        IsResultDependent = ControllingExpr->isTypeDependent(),
1603        ContainsUnexpandedParameterPack
1604          = ControllingExpr->containsUnexpandedParameterPack();
1605
1606   for (unsigned i = 0; i < NumAssocs; ++i) {
1607     if (Exprs[i]->containsUnexpandedParameterPack())
1608       ContainsUnexpandedParameterPack = true;
1609
1610     if (Types[i]) {
1611       if (Types[i]->getType()->containsUnexpandedParameterPack())
1612         ContainsUnexpandedParameterPack = true;
1613
1614       if (Types[i]->getType()->isDependentType()) {
1615         IsResultDependent = true;
1616       } else {
1617         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1618         // complete object type other than a variably modified type."
1619         unsigned D = 0;
1620         if (Types[i]->getType()->isIncompleteType())
1621           D = diag::err_assoc_type_incomplete;
1622         else if (!Types[i]->getType()->isObjectType())
1623           D = diag::err_assoc_type_nonobject;
1624         else if (Types[i]->getType()->isVariablyModifiedType())
1625           D = diag::err_assoc_type_variably_modified;
1626
1627         if (D != 0) {
1628           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1629             << Types[i]->getTypeLoc().getSourceRange()
1630             << Types[i]->getType();
1631           TypeErrorFound = true;
1632         }
1633
1634         // C11 6.5.1.1p2 "No two generic associations in the same generic
1635         // selection shall specify compatible types."
1636         for (unsigned j = i+1; j < NumAssocs; ++j)
1637           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1638               Context.typesAreCompatible(Types[i]->getType(),
1639                                          Types[j]->getType())) {
1640             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1641                  diag::err_assoc_compatible_types)
1642               << Types[j]->getTypeLoc().getSourceRange()
1643               << Types[j]->getType()
1644               << Types[i]->getType();
1645             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1646                  diag::note_compat_assoc)
1647               << Types[i]->getTypeLoc().getSourceRange()
1648               << Types[i]->getType();
1649             TypeErrorFound = true;
1650           }
1651       }
1652     }
1653   }
1654   if (TypeErrorFound)
1655     return ExprError();
1656
1657   // If we determined that the generic selection is result-dependent, don't
1658   // try to compute the result expression.
1659   if (IsResultDependent)
1660     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1661                                         Exprs, DefaultLoc, RParenLoc,
1662                                         ContainsUnexpandedParameterPack);
1663
1664   SmallVector<unsigned, 1> CompatIndices;
1665   unsigned DefaultIndex = -1U;
1666   for (unsigned i = 0; i < NumAssocs; ++i) {
1667     if (!Types[i])
1668       DefaultIndex = i;
1669     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1670                                         Types[i]->getType()))
1671       CompatIndices.push_back(i);
1672   }
1673
1674   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1675   // type compatible with at most one of the types named in its generic
1676   // association list."
1677   if (CompatIndices.size() > 1) {
1678     // We strip parens here because the controlling expression is typically
1679     // parenthesized in macro definitions.
1680     ControllingExpr = ControllingExpr->IgnoreParens();
1681     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1682         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1683         << (unsigned)CompatIndices.size();
1684     for (unsigned I : CompatIndices) {
1685       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1686            diag::note_compat_assoc)
1687         << Types[I]->getTypeLoc().getSourceRange()
1688         << Types[I]->getType();
1689     }
1690     return ExprError();
1691   }
1692
1693   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1694   // its controlling expression shall have type compatible with exactly one of
1695   // the types named in its generic association list."
1696   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1697     // We strip parens here because the controlling expression is typically
1698     // parenthesized in macro definitions.
1699     ControllingExpr = ControllingExpr->IgnoreParens();
1700     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1701         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1702     return ExprError();
1703   }
1704
1705   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1706   // type name that is compatible with the type of the controlling expression,
1707   // then the result expression of the generic selection is the expression
1708   // in that generic association. Otherwise, the result expression of the
1709   // generic selection is the expression in the default generic association."
1710   unsigned ResultIndex =
1711     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1712
1713   return GenericSelectionExpr::Create(
1714       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1715       ContainsUnexpandedParameterPack, ResultIndex);
1716 }
1717
1718 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1719 /// location of the token and the offset of the ud-suffix within it.
1720 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1721                                      unsigned Offset) {
1722   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1723                                         S.getLangOpts());
1724 }
1725
1726 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1727 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1728 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1729                                                  IdentifierInfo *UDSuffix,
1730                                                  SourceLocation UDSuffixLoc,
1731                                                  ArrayRef<Expr*> Args,
1732                                                  SourceLocation LitEndLoc) {
1733   assert(Args.size() <= 2 && "too many arguments for literal operator");
1734
1735   QualType ArgTy[2];
1736   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1737     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1738     if (ArgTy[ArgIdx]->isArrayType())
1739       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1740   }
1741
1742   DeclarationName OpName =
1743     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1744   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1745   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1746
1747   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1748   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1749                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1750                               /*AllowStringTemplate*/ false,
1751                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1752     return ExprError();
1753
1754   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1755 }
1756
1757 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1758 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1759 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1760 /// multiple tokens.  However, the common case is that StringToks points to one
1761 /// string.
1762 ///
1763 ExprResult
1764 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1765   assert(!StringToks.empty() && "Must have at least one string!");
1766
1767   StringLiteralParser Literal(StringToks, PP);
1768   if (Literal.hadError)
1769     return ExprError();
1770
1771   SmallVector<SourceLocation, 4> StringTokLocs;
1772   for (const Token &Tok : StringToks)
1773     StringTokLocs.push_back(Tok.getLocation());
1774
1775   QualType CharTy = Context.CharTy;
1776   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1777   if (Literal.isWide()) {
1778     CharTy = Context.getWideCharType();
1779     Kind = StringLiteral::Wide;
1780   } else if (Literal.isUTF8()) {
1781     if (getLangOpts().Char8)
1782       CharTy = Context.Char8Ty;
1783     Kind = StringLiteral::UTF8;
1784   } else if (Literal.isUTF16()) {
1785     CharTy = Context.Char16Ty;
1786     Kind = StringLiteral::UTF16;
1787   } else if (Literal.isUTF32()) {
1788     CharTy = Context.Char32Ty;
1789     Kind = StringLiteral::UTF32;
1790   } else if (Literal.isPascal()) {
1791     CharTy = Context.UnsignedCharTy;
1792   }
1793
1794   // Warn on initializing an array of char from a u8 string literal; this
1795   // becomes ill-formed in C++2a.
1796   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1797       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1798     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1799
1800     // Create removals for all 'u8' prefixes in the string literal(s). This
1801     // ensures C++2a compatibility (but may change the program behavior when
1802     // built by non-Clang compilers for which the execution character set is
1803     // not always UTF-8).
1804     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1805     SourceLocation RemovalDiagLoc;
1806     for (const Token &Tok : StringToks) {
1807       if (Tok.getKind() == tok::utf8_string_literal) {
1808         if (RemovalDiagLoc.isInvalid())
1809           RemovalDiagLoc = Tok.getLocation();
1810         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1811             Tok.getLocation(),
1812             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1813                                            getSourceManager(), getLangOpts())));
1814       }
1815     }
1816     Diag(RemovalDiagLoc, RemovalDiag);
1817   }
1818
1819   QualType StrTy =
1820       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1821
1822   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1823   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1824                                              Kind, Literal.Pascal, StrTy,
1825                                              &StringTokLocs[0],
1826                                              StringTokLocs.size());
1827   if (Literal.getUDSuffix().empty())
1828     return Lit;
1829
1830   // We're building a user-defined literal.
1831   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1832   SourceLocation UDSuffixLoc =
1833     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1834                    Literal.getUDSuffixOffset());
1835
1836   // Make sure we're allowed user-defined literals here.
1837   if (!UDLScope)
1838     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1839
1840   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1841   //   operator "" X (str, len)
1842   QualType SizeType = Context.getSizeType();
1843
1844   DeclarationName OpName =
1845     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1846   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1847   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1848
1849   QualType ArgTy[] = {
1850     Context.getArrayDecayedType(StrTy), SizeType
1851   };
1852
1853   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1854   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1855                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1856                                 /*AllowStringTemplate*/ true,
1857                                 /*DiagnoseMissing*/ true)) {
1858
1859   case LOLR_Cooked: {
1860     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1861     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1862                                                     StringTokLocs[0]);
1863     Expr *Args[] = { Lit, LenArg };
1864
1865     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1866   }
1867
1868   case LOLR_StringTemplate: {
1869     TemplateArgumentListInfo ExplicitArgs;
1870
1871     unsigned CharBits = Context.getIntWidth(CharTy);
1872     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1873     llvm::APSInt Value(CharBits, CharIsUnsigned);
1874
1875     TemplateArgument TypeArg(CharTy);
1876     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1877     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1878
1879     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1880       Value = Lit->getCodeUnit(I);
1881       TemplateArgument Arg(Context, Value, CharTy);
1882       TemplateArgumentLocInfo ArgInfo;
1883       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1884     }
1885     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1886                                     &ExplicitArgs);
1887   }
1888   case LOLR_Raw:
1889   case LOLR_Template:
1890   case LOLR_ErrorNoDiagnostic:
1891     llvm_unreachable("unexpected literal operator lookup result");
1892   case LOLR_Error:
1893     return ExprError();
1894   }
1895   llvm_unreachable("unexpected literal operator lookup result");
1896 }
1897
1898 DeclRefExpr *
1899 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1900                        SourceLocation Loc,
1901                        const CXXScopeSpec *SS) {
1902   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1903   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1904 }
1905
1906 DeclRefExpr *
1907 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1908                        const DeclarationNameInfo &NameInfo,
1909                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1910                        SourceLocation TemplateKWLoc,
1911                        const TemplateArgumentListInfo *TemplateArgs) {
1912   NestedNameSpecifierLoc NNS =
1913       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1914   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1915                           TemplateArgs);
1916 }
1917
1918 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1919   // A declaration named in an unevaluated operand never constitutes an odr-use.
1920   if (isUnevaluatedContext())
1921     return NOUR_Unevaluated;
1922
1923   // C++2a [basic.def.odr]p4:
1924   //   A variable x whose name appears as a potentially-evaluated expression e
1925   //   is odr-used by e unless [...] x is a reference that is usable in
1926   //   constant expressions.
1927   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1928     if (VD->getType()->isReferenceType() &&
1929         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1930         VD->isUsableInConstantExpressions(Context))
1931       return NOUR_Constant;
1932   }
1933
1934   // All remaining non-variable cases constitute an odr-use. For variables, we
1935   // need to wait and see how the expression is used.
1936   return NOUR_None;
1937 }
1938
1939 /// BuildDeclRefExpr - Build an expression that references a
1940 /// declaration that does not require a closure capture.
1941 DeclRefExpr *
1942 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1943                        const DeclarationNameInfo &NameInfo,
1944                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1945                        SourceLocation TemplateKWLoc,
1946                        const TemplateArgumentListInfo *TemplateArgs) {
1947   bool RefersToCapturedVariable =
1948       isa<VarDecl>(D) &&
1949       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1950
1951   DeclRefExpr *E = DeclRefExpr::Create(
1952       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1953       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1954   MarkDeclRefReferenced(E);
1955
1956   // C++ [except.spec]p17:
1957   //   An exception-specification is considered to be needed when:
1958   //   - in an expression, the function is the unique lookup result or
1959   //     the selected member of a set of overloaded functions.
1960   //
1961   // We delay doing this until after we've built the function reference and
1962   // marked it as used so that:
1963   //  a) if the function is defaulted, we get errors from defining it before /
1964   //     instead of errors from computing its exception specification, and
1965   //  b) if the function is a defaulted comparison, we can use the body we
1966   //     build when defining it as input to the exception specification
1967   //     computation rather than computing a new body.
1968   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1969     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1970       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1971         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1972     }
1973   }
1974
1975   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1976       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1977       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1978     getCurFunction()->recordUseOfWeak(E);
1979
1980   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1981   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1982     FD = IFD->getAnonField();
1983   if (FD) {
1984     UnusedPrivateFields.remove(FD);
1985     // Just in case we're building an illegal pointer-to-member.
1986     if (FD->isBitField())
1987       E->setObjectKind(OK_BitField);
1988   }
1989
1990   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1991   // designates a bit-field.
1992   if (auto *BD = dyn_cast<BindingDecl>(D))
1993     if (auto *BE = BD->getBinding())
1994       E->setObjectKind(BE->getObjectKind());
1995
1996   return E;
1997 }
1998
1999 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2000 /// possibly a list of template arguments.
2001 ///
2002 /// If this produces template arguments, it is permitted to call
2003 /// DecomposeTemplateName.
2004 ///
2005 /// This actually loses a lot of source location information for
2006 /// non-standard name kinds; we should consider preserving that in
2007 /// some way.
2008 void
2009 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2010                              TemplateArgumentListInfo &Buffer,
2011                              DeclarationNameInfo &NameInfo,
2012                              const TemplateArgumentListInfo *&TemplateArgs) {
2013   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2014     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2015     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2016
2017     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2018                                        Id.TemplateId->NumArgs);
2019     translateTemplateArguments(TemplateArgsPtr, Buffer);
2020
2021     TemplateName TName = Id.TemplateId->Template.get();
2022     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2023     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2024     TemplateArgs = &Buffer;
2025   } else {
2026     NameInfo = GetNameFromUnqualifiedId(Id);
2027     TemplateArgs = nullptr;
2028   }
2029 }
2030
2031 static void emitEmptyLookupTypoDiagnostic(
2032     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2033     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2034     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2035   DeclContext *Ctx =
2036       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2037   if (!TC) {
2038     // Emit a special diagnostic for failed member lookups.
2039     // FIXME: computing the declaration context might fail here (?)
2040     if (Ctx)
2041       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2042                                                  << SS.getRange();
2043     else
2044       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2045     return;
2046   }
2047
2048   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2049   bool DroppedSpecifier =
2050       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2051   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2052                         ? diag::note_implicit_param_decl
2053                         : diag::note_previous_decl;
2054   if (!Ctx)
2055     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2056                          SemaRef.PDiag(NoteID));
2057   else
2058     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2059                                  << Typo << Ctx << DroppedSpecifier
2060                                  << SS.getRange(),
2061                          SemaRef.PDiag(NoteID));
2062 }
2063
2064 /// Diagnose an empty lookup.
2065 ///
2066 /// \return false if new lookup candidates were found
2067 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2068                                CorrectionCandidateCallback &CCC,
2069                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2070                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2071   DeclarationName Name = R.getLookupName();
2072
2073   unsigned diagnostic = diag::err_undeclared_var_use;
2074   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2075   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2076       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2077       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2078     diagnostic = diag::err_undeclared_use;
2079     diagnostic_suggest = diag::err_undeclared_use_suggest;
2080   }
2081
2082   // If the original lookup was an unqualified lookup, fake an
2083   // unqualified lookup.  This is useful when (for example) the
2084   // original lookup would not have found something because it was a
2085   // dependent name.
2086   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2087   while (DC) {
2088     if (isa<CXXRecordDecl>(DC)) {
2089       LookupQualifiedName(R, DC);
2090
2091       if (!R.empty()) {
2092         // Don't give errors about ambiguities in this lookup.
2093         R.suppressDiagnostics();
2094
2095         // During a default argument instantiation the CurContext points
2096         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2097         // function parameter list, hence add an explicit check.
2098         bool isDefaultArgument =
2099             !CodeSynthesisContexts.empty() &&
2100             CodeSynthesisContexts.back().Kind ==
2101                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2102         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2103         bool isInstance = CurMethod &&
2104                           CurMethod->isInstance() &&
2105                           DC == CurMethod->getParent() && !isDefaultArgument;
2106
2107         // Give a code modification hint to insert 'this->'.
2108         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2109         // Actually quite difficult!
2110         if (getLangOpts().MSVCCompat)
2111           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2112         if (isInstance) {
2113           Diag(R.getNameLoc(), diagnostic) << Name
2114             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2115           CheckCXXThisCapture(R.getNameLoc());
2116         } else {
2117           Diag(R.getNameLoc(), diagnostic) << Name;
2118         }
2119
2120         // Do we really want to note all of these?
2121         for (NamedDecl *D : R)
2122           Diag(D->getLocation(), diag::note_dependent_var_use);
2123
2124         // Return true if we are inside a default argument instantiation
2125         // and the found name refers to an instance member function, otherwise
2126         // the function calling DiagnoseEmptyLookup will try to create an
2127         // implicit member call and this is wrong for default argument.
2128         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2129           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2130           return true;
2131         }
2132
2133         // Tell the callee to try to recover.
2134         return false;
2135       }
2136
2137       R.clear();
2138     }
2139
2140     DC = DC->getLookupParent();
2141   }
2142
2143   // We didn't find anything, so try to correct for a typo.
2144   TypoCorrection Corrected;
2145   if (S && Out) {
2146     SourceLocation TypoLoc = R.getNameLoc();
2147     assert(!ExplicitTemplateArgs &&
2148            "Diagnosing an empty lookup with explicit template args!");
2149     *Out = CorrectTypoDelayed(
2150         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2151         [=](const TypoCorrection &TC) {
2152           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2153                                         diagnostic, diagnostic_suggest);
2154         },
2155         nullptr, CTK_ErrorRecovery);
2156     if (*Out)
2157       return true;
2158   } else if (S &&
2159              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2160                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2161     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2162     bool DroppedSpecifier =
2163         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2164     R.setLookupName(Corrected.getCorrection());
2165
2166     bool AcceptableWithRecovery = false;
2167     bool AcceptableWithoutRecovery = false;
2168     NamedDecl *ND = Corrected.getFoundDecl();
2169     if (ND) {
2170       if (Corrected.isOverloaded()) {
2171         OverloadCandidateSet OCS(R.getNameLoc(),
2172                                  OverloadCandidateSet::CSK_Normal);
2173         OverloadCandidateSet::iterator Best;
2174         for (NamedDecl *CD : Corrected) {
2175           if (FunctionTemplateDecl *FTD =
2176                    dyn_cast<FunctionTemplateDecl>(CD))
2177             AddTemplateOverloadCandidate(
2178                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2179                 Args, OCS);
2180           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2181             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2182               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2183                                    Args, OCS);
2184         }
2185         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2186         case OR_Success:
2187           ND = Best->FoundDecl;
2188           Corrected.setCorrectionDecl(ND);
2189           break;
2190         default:
2191           // FIXME: Arbitrarily pick the first declaration for the note.
2192           Corrected.setCorrectionDecl(ND);
2193           break;
2194         }
2195       }
2196       R.addDecl(ND);
2197       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2198         CXXRecordDecl *Record = nullptr;
2199         if (Corrected.getCorrectionSpecifier()) {
2200           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2201           Record = Ty->getAsCXXRecordDecl();
2202         }
2203         if (!Record)
2204           Record = cast<CXXRecordDecl>(
2205               ND->getDeclContext()->getRedeclContext());
2206         R.setNamingClass(Record);
2207       }
2208
2209       auto *UnderlyingND = ND->getUnderlyingDecl();
2210       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2211                                isa<FunctionTemplateDecl>(UnderlyingND);
2212       // FIXME: If we ended up with a typo for a type name or
2213       // Objective-C class name, we're in trouble because the parser
2214       // is in the wrong place to recover. Suggest the typo
2215       // correction, but don't make it a fix-it since we're not going
2216       // to recover well anyway.
2217       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2218                                   getAsTypeTemplateDecl(UnderlyingND) ||
2219                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2220     } else {
2221       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2222       // because we aren't able to recover.
2223       AcceptableWithoutRecovery = true;
2224     }
2225
2226     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2227       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2228                             ? diag::note_implicit_param_decl
2229                             : diag::note_previous_decl;
2230       if (SS.isEmpty())
2231         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2232                      PDiag(NoteID), AcceptableWithRecovery);
2233       else
2234         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2235                                   << Name << computeDeclContext(SS, false)
2236                                   << DroppedSpecifier << SS.getRange(),
2237                      PDiag(NoteID), AcceptableWithRecovery);
2238
2239       // Tell the callee whether to try to recover.
2240       return !AcceptableWithRecovery;
2241     }
2242   }
2243   R.clear();
2244
2245   // Emit a special diagnostic for failed member lookups.
2246   // FIXME: computing the declaration context might fail here (?)
2247   if (!SS.isEmpty()) {
2248     Diag(R.getNameLoc(), diag::err_no_member)
2249       << Name << computeDeclContext(SS, false)
2250       << SS.getRange();
2251     return true;
2252   }
2253
2254   // Give up, we can't recover.
2255   Diag(R.getNameLoc(), diagnostic) << Name;
2256   return true;
2257 }
2258
2259 /// In Microsoft mode, if we are inside a template class whose parent class has
2260 /// dependent base classes, and we can't resolve an unqualified identifier, then
2261 /// assume the identifier is a member of a dependent base class.  We can only
2262 /// recover successfully in static methods, instance methods, and other contexts
2263 /// where 'this' is available.  This doesn't precisely match MSVC's
2264 /// instantiation model, but it's close enough.
2265 static Expr *
2266 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2267                                DeclarationNameInfo &NameInfo,
2268                                SourceLocation TemplateKWLoc,
2269                                const TemplateArgumentListInfo *TemplateArgs) {
2270   // Only try to recover from lookup into dependent bases in static methods or
2271   // contexts where 'this' is available.
2272   QualType ThisType = S.getCurrentThisType();
2273   const CXXRecordDecl *RD = nullptr;
2274   if (!ThisType.isNull())
2275     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2276   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2277     RD = MD->getParent();
2278   if (!RD || !RD->hasAnyDependentBases())
2279     return nullptr;
2280
2281   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2282   // is available, suggest inserting 'this->' as a fixit.
2283   SourceLocation Loc = NameInfo.getLoc();
2284   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2285   DB << NameInfo.getName() << RD;
2286
2287   if (!ThisType.isNull()) {
2288     DB << FixItHint::CreateInsertion(Loc, "this->");
2289     return CXXDependentScopeMemberExpr::Create(
2290         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2291         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2292         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2293   }
2294
2295   // Synthesize a fake NNS that points to the derived class.  This will
2296   // perform name lookup during template instantiation.
2297   CXXScopeSpec SS;
2298   auto *NNS =
2299       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2300   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2301   return DependentScopeDeclRefExpr::Create(
2302       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2303       TemplateArgs);
2304 }
2305
2306 ExprResult
2307 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2308                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2309                         bool HasTrailingLParen, bool IsAddressOfOperand,
2310                         CorrectionCandidateCallback *CCC,
2311                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2312   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2313          "cannot be direct & operand and have a trailing lparen");
2314   if (SS.isInvalid())
2315     return ExprError();
2316
2317   TemplateArgumentListInfo TemplateArgsBuffer;
2318
2319   // Decompose the UnqualifiedId into the following data.
2320   DeclarationNameInfo NameInfo;
2321   const TemplateArgumentListInfo *TemplateArgs;
2322   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2323
2324   DeclarationName Name = NameInfo.getName();
2325   IdentifierInfo *II = Name.getAsIdentifierInfo();
2326   SourceLocation NameLoc = NameInfo.getLoc();
2327
2328   if (II && II->isEditorPlaceholder()) {
2329     // FIXME: When typed placeholders are supported we can create a typed
2330     // placeholder expression node.
2331     return ExprError();
2332   }
2333
2334   // C++ [temp.dep.expr]p3:
2335   //   An id-expression is type-dependent if it contains:
2336   //     -- an identifier that was declared with a dependent type,
2337   //        (note: handled after lookup)
2338   //     -- a template-id that is dependent,
2339   //        (note: handled in BuildTemplateIdExpr)
2340   //     -- a conversion-function-id that specifies a dependent type,
2341   //     -- a nested-name-specifier that contains a class-name that
2342   //        names a dependent type.
2343   // Determine whether this is a member of an unknown specialization;
2344   // we need to handle these differently.
2345   bool DependentID = false;
2346   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2347       Name.getCXXNameType()->isDependentType()) {
2348     DependentID = true;
2349   } else if (SS.isSet()) {
2350     if (DeclContext *DC = computeDeclContext(SS, false)) {
2351       if (RequireCompleteDeclContext(SS, DC))
2352         return ExprError();
2353     } else {
2354       DependentID = true;
2355     }
2356   }
2357
2358   if (DependentID)
2359     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2360                                       IsAddressOfOperand, TemplateArgs);
2361
2362   // Perform the required lookup.
2363   LookupResult R(*this, NameInfo,
2364                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2365                      ? LookupObjCImplicitSelfParam
2366                      : LookupOrdinaryName);
2367   if (TemplateKWLoc.isValid() || TemplateArgs) {
2368     // Lookup the template name again to correctly establish the context in
2369     // which it was found. This is really unfortunate as we already did the
2370     // lookup to determine that it was a template name in the first place. If
2371     // this becomes a performance hit, we can work harder to preserve those
2372     // results until we get here but it's likely not worth it.
2373     bool MemberOfUnknownSpecialization;
2374     AssumedTemplateKind AssumedTemplate;
2375     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2376                            MemberOfUnknownSpecialization, TemplateKWLoc,
2377                            &AssumedTemplate))
2378       return ExprError();
2379
2380     if (MemberOfUnknownSpecialization ||
2381         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2382       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2383                                         IsAddressOfOperand, TemplateArgs);
2384   } else {
2385     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2386     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2387
2388     // If the result might be in a dependent base class, this is a dependent
2389     // id-expression.
2390     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2391       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2392                                         IsAddressOfOperand, TemplateArgs);
2393
2394     // If this reference is in an Objective-C method, then we need to do
2395     // some special Objective-C lookup, too.
2396     if (IvarLookupFollowUp) {
2397       ExprResult E(LookupInObjCMethod(R, S, II, true));
2398       if (E.isInvalid())
2399         return ExprError();
2400
2401       if (Expr *Ex = E.getAs<Expr>())
2402         return Ex;
2403     }
2404   }
2405
2406   if (R.isAmbiguous())
2407     return ExprError();
2408
2409   // This could be an implicitly declared function reference (legal in C90,
2410   // extension in C99, forbidden in C++).
2411   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2412     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2413     if (D) R.addDecl(D);
2414   }
2415
2416   // Determine whether this name might be a candidate for
2417   // argument-dependent lookup.
2418   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2419
2420   if (R.empty() && !ADL) {
2421     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2422       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2423                                                    TemplateKWLoc, TemplateArgs))
2424         return E;
2425     }
2426
2427     // Don't diagnose an empty lookup for inline assembly.
2428     if (IsInlineAsmIdentifier)
2429       return ExprError();
2430
2431     // If this name wasn't predeclared and if this is not a function
2432     // call, diagnose the problem.
2433     TypoExpr *TE = nullptr;
2434     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2435                                                        : nullptr);
2436     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2437     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2438            "Typo correction callback misconfigured");
2439     if (CCC) {
2440       // Make sure the callback knows what the typo being diagnosed is.
2441       CCC->setTypoName(II);
2442       if (SS.isValid())
2443         CCC->setTypoNNS(SS.getScopeRep());
2444     }
2445     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2446     // a template name, but we happen to have always already looked up the name
2447     // before we get here if it must be a template name.
2448     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2449                             None, &TE)) {
2450       if (TE && KeywordReplacement) {
2451         auto &State = getTypoExprState(TE);
2452         auto BestTC = State.Consumer->getNextCorrection();
2453         if (BestTC.isKeyword()) {
2454           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2455           if (State.DiagHandler)
2456             State.DiagHandler(BestTC);
2457           KeywordReplacement->startToken();
2458           KeywordReplacement->setKind(II->getTokenID());
2459           KeywordReplacement->setIdentifierInfo(II);
2460           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2461           // Clean up the state associated with the TypoExpr, since it has
2462           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2463           clearDelayedTypo(TE);
2464           // Signal that a correction to a keyword was performed by returning a
2465           // valid-but-null ExprResult.
2466           return (Expr*)nullptr;
2467         }
2468         State.Consumer->resetCorrectionStream();
2469       }
2470       return TE ? TE : ExprError();
2471     }
2472
2473     assert(!R.empty() &&
2474            "DiagnoseEmptyLookup returned false but added no results");
2475
2476     // If we found an Objective-C instance variable, let
2477     // LookupInObjCMethod build the appropriate expression to
2478     // reference the ivar.
2479     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2480       R.clear();
2481       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2482       // In a hopelessly buggy code, Objective-C instance variable
2483       // lookup fails and no expression will be built to reference it.
2484       if (!E.isInvalid() && !E.get())
2485         return ExprError();
2486       return E;
2487     }
2488   }
2489
2490   // This is guaranteed from this point on.
2491   assert(!R.empty() || ADL);
2492
2493   // Check whether this might be a C++ implicit instance member access.
2494   // C++ [class.mfct.non-static]p3:
2495   //   When an id-expression that is not part of a class member access
2496   //   syntax and not used to form a pointer to member is used in the
2497   //   body of a non-static member function of class X, if name lookup
2498   //   resolves the name in the id-expression to a non-static non-type
2499   //   member of some class C, the id-expression is transformed into a
2500   //   class member access expression using (*this) as the
2501   //   postfix-expression to the left of the . operator.
2502   //
2503   // But we don't actually need to do this for '&' operands if R
2504   // resolved to a function or overloaded function set, because the
2505   // expression is ill-formed if it actually works out to be a
2506   // non-static member function:
2507   //
2508   // C++ [expr.ref]p4:
2509   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2510   //   [t]he expression can be used only as the left-hand operand of a
2511   //   member function call.
2512   //
2513   // There are other safeguards against such uses, but it's important
2514   // to get this right here so that we don't end up making a
2515   // spuriously dependent expression if we're inside a dependent
2516   // instance method.
2517   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2518     bool MightBeImplicitMember;
2519     if (!IsAddressOfOperand)
2520       MightBeImplicitMember = true;
2521     else if (!SS.isEmpty())
2522       MightBeImplicitMember = false;
2523     else if (R.isOverloadedResult())
2524       MightBeImplicitMember = false;
2525     else if (R.isUnresolvableResult())
2526       MightBeImplicitMember = true;
2527     else
2528       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2529                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2530                               isa<MSPropertyDecl>(R.getFoundDecl());
2531
2532     if (MightBeImplicitMember)
2533       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2534                                              R, TemplateArgs, S);
2535   }
2536
2537   if (TemplateArgs || TemplateKWLoc.isValid()) {
2538
2539     // In C++1y, if this is a variable template id, then check it
2540     // in BuildTemplateIdExpr().
2541     // The single lookup result must be a variable template declaration.
2542     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2543         Id.TemplateId->Kind == TNK_Var_template) {
2544       assert(R.getAsSingle<VarTemplateDecl>() &&
2545              "There should only be one declaration found.");
2546     }
2547
2548     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2549   }
2550
2551   return BuildDeclarationNameExpr(SS, R, ADL);
2552 }
2553
2554 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2555 /// declaration name, generally during template instantiation.
2556 /// There's a large number of things which don't need to be done along
2557 /// this path.
2558 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2559     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2560     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2561   DeclContext *DC = computeDeclContext(SS, false);
2562   if (!DC)
2563     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2564                                      NameInfo, /*TemplateArgs=*/nullptr);
2565
2566   if (RequireCompleteDeclContext(SS, DC))
2567     return ExprError();
2568
2569   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2570   LookupQualifiedName(R, DC);
2571
2572   if (R.isAmbiguous())
2573     return ExprError();
2574
2575   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2576     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2577                                      NameInfo, /*TemplateArgs=*/nullptr);
2578
2579   if (R.empty()) {
2580     Diag(NameInfo.getLoc(), diag::err_no_member)
2581       << NameInfo.getName() << DC << SS.getRange();
2582     return ExprError();
2583   }
2584
2585   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2586     // Diagnose a missing typename if this resolved unambiguously to a type in
2587     // a dependent context.  If we can recover with a type, downgrade this to
2588     // a warning in Microsoft compatibility mode.
2589     unsigned DiagID = diag::err_typename_missing;
2590     if (RecoveryTSI && getLangOpts().MSVCCompat)
2591       DiagID = diag::ext_typename_missing;
2592     SourceLocation Loc = SS.getBeginLoc();
2593     auto D = Diag(Loc, DiagID);
2594     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2595       << SourceRange(Loc, NameInfo.getEndLoc());
2596
2597     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2598     // context.
2599     if (!RecoveryTSI)
2600       return ExprError();
2601
2602     // Only issue the fixit if we're prepared to recover.
2603     D << FixItHint::CreateInsertion(Loc, "typename ");
2604
2605     // Recover by pretending this was an elaborated type.
2606     QualType Ty = Context.getTypeDeclType(TD);
2607     TypeLocBuilder TLB;
2608     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2609
2610     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2611     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2612     QTL.setElaboratedKeywordLoc(SourceLocation());
2613     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2614
2615     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2616
2617     return ExprEmpty();
2618   }
2619
2620   // Defend against this resolving to an implicit member access. We usually
2621   // won't get here if this might be a legitimate a class member (we end up in
2622   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2623   // a pointer-to-member or in an unevaluated context in C++11.
2624   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2625     return BuildPossibleImplicitMemberExpr(SS,
2626                                            /*TemplateKWLoc=*/SourceLocation(),
2627                                            R, /*TemplateArgs=*/nullptr, S);
2628
2629   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2630 }
2631
2632 /// The parser has read a name in, and Sema has detected that we're currently
2633 /// inside an ObjC method. Perform some additional checks and determine if we
2634 /// should form a reference to an ivar.
2635 ///
2636 /// Ideally, most of this would be done by lookup, but there's
2637 /// actually quite a lot of extra work involved.
2638 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2639                                         IdentifierInfo *II) {
2640   SourceLocation Loc = Lookup.getNameLoc();
2641   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2642
2643   // Check for error condition which is already reported.
2644   if (!CurMethod)
2645     return DeclResult(true);
2646
2647   // There are two cases to handle here.  1) scoped lookup could have failed,
2648   // in which case we should look for an ivar.  2) scoped lookup could have
2649   // found a decl, but that decl is outside the current instance method (i.e.
2650   // a global variable).  In these two cases, we do a lookup for an ivar with
2651   // this name, if the lookup sucedes, we replace it our current decl.
2652
2653   // If we're in a class method, we don't normally want to look for
2654   // ivars.  But if we don't find anything else, and there's an
2655   // ivar, that's an error.
2656   bool IsClassMethod = CurMethod->isClassMethod();
2657
2658   bool LookForIvars;
2659   if (Lookup.empty())
2660     LookForIvars = true;
2661   else if (IsClassMethod)
2662     LookForIvars = false;
2663   else
2664     LookForIvars = (Lookup.isSingleResult() &&
2665                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2666   ObjCInterfaceDecl *IFace = nullptr;
2667   if (LookForIvars) {
2668     IFace = CurMethod->getClassInterface();
2669     ObjCInterfaceDecl *ClassDeclared;
2670     ObjCIvarDecl *IV = nullptr;
2671     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2672       // Diagnose using an ivar in a class method.
2673       if (IsClassMethod) {
2674         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2675         return DeclResult(true);
2676       }
2677
2678       // Diagnose the use of an ivar outside of the declaring class.
2679       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2680           !declaresSameEntity(ClassDeclared, IFace) &&
2681           !getLangOpts().DebuggerSupport)
2682         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2683
2684       // Success.
2685       return IV;
2686     }
2687   } else if (CurMethod->isInstanceMethod()) {
2688     // We should warn if a local variable hides an ivar.
2689     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2690       ObjCInterfaceDecl *ClassDeclared;
2691       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2692         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2693             declaresSameEntity(IFace, ClassDeclared))
2694           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2695       }
2696     }
2697   } else if (Lookup.isSingleResult() &&
2698              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2699     // If accessing a stand-alone ivar in a class method, this is an error.
2700     if (const ObjCIvarDecl *IV =
2701             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2702       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2703       return DeclResult(true);
2704     }
2705   }
2706
2707   // Didn't encounter an error, didn't find an ivar.
2708   return DeclResult(false);
2709 }
2710
2711 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2712                                   ObjCIvarDecl *IV) {
2713   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2714   assert(CurMethod && CurMethod->isInstanceMethod() &&
2715          "should not reference ivar from this context");
2716
2717   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2718   assert(IFace && "should not reference ivar from this context");
2719
2720   // If we're referencing an invalid decl, just return this as a silent
2721   // error node.  The error diagnostic was already emitted on the decl.
2722   if (IV->isInvalidDecl())
2723     return ExprError();
2724
2725   // Check if referencing a field with __attribute__((deprecated)).
2726   if (DiagnoseUseOfDecl(IV, Loc))
2727     return ExprError();
2728
2729   // FIXME: This should use a new expr for a direct reference, don't
2730   // turn this into Self->ivar, just return a BareIVarExpr or something.
2731   IdentifierInfo &II = Context.Idents.get("self");
2732   UnqualifiedId SelfName;
2733   SelfName.setIdentifier(&II, SourceLocation());
2734   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2735   CXXScopeSpec SelfScopeSpec;
2736   SourceLocation TemplateKWLoc;
2737   ExprResult SelfExpr =
2738       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2739                         /*HasTrailingLParen=*/false,
2740                         /*IsAddressOfOperand=*/false);
2741   if (SelfExpr.isInvalid())
2742     return ExprError();
2743
2744   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2745   if (SelfExpr.isInvalid())
2746     return ExprError();
2747
2748   MarkAnyDeclReferenced(Loc, IV, true);
2749
2750   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2751   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2752       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2753     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2754
2755   ObjCIvarRefExpr *Result = new (Context)
2756       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2757                       IV->getLocation(), SelfExpr.get(), true, true);
2758
2759   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2760     if (!isUnevaluatedContext() &&
2761         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2762       getCurFunction()->recordUseOfWeak(Result);
2763   }
2764   if (getLangOpts().ObjCAutoRefCount)
2765     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2766       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2767
2768   return Result;
2769 }
2770
2771 /// The parser has read a name in, and Sema has detected that we're currently
2772 /// inside an ObjC method. Perform some additional checks and determine if we
2773 /// should form a reference to an ivar. If so, build an expression referencing
2774 /// that ivar.
2775 ExprResult
2776 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2777                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2778   // FIXME: Integrate this lookup step into LookupParsedName.
2779   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2780   if (Ivar.isInvalid())
2781     return ExprError();
2782   if (Ivar.isUsable())
2783     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2784                             cast<ObjCIvarDecl>(Ivar.get()));
2785
2786   if (Lookup.empty() && II && AllowBuiltinCreation)
2787     LookupBuiltin(Lookup);
2788
2789   // Sentinel value saying that we didn't do anything special.
2790   return ExprResult(false);
2791 }
2792
2793 /// Cast a base object to a member's actual type.
2794 ///
2795 /// Logically this happens in three phases:
2796 ///
2797 /// * First we cast from the base type to the naming class.
2798 ///   The naming class is the class into which we were looking
2799 ///   when we found the member;  it's the qualifier type if a
2800 ///   qualifier was provided, and otherwise it's the base type.
2801 ///
2802 /// * Next we cast from the naming class to the declaring class.
2803 ///   If the member we found was brought into a class's scope by
2804 ///   a using declaration, this is that class;  otherwise it's
2805 ///   the class declaring the member.
2806 ///
2807 /// * Finally we cast from the declaring class to the "true"
2808 ///   declaring class of the member.  This conversion does not
2809 ///   obey access control.
2810 ExprResult
2811 Sema::PerformObjectMemberConversion(Expr *From,
2812                                     NestedNameSpecifier *Qualifier,
2813                                     NamedDecl *FoundDecl,
2814                                     NamedDecl *Member) {
2815   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2816   if (!RD)
2817     return From;
2818
2819   QualType DestRecordType;
2820   QualType DestType;
2821   QualType FromRecordType;
2822   QualType FromType = From->getType();
2823   bool PointerConversions = false;
2824   if (isa<FieldDecl>(Member)) {
2825     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2826     auto FromPtrType = FromType->getAs<PointerType>();
2827     DestRecordType = Context.getAddrSpaceQualType(
2828         DestRecordType, FromPtrType
2829                             ? FromType->getPointeeType().getAddressSpace()
2830                             : FromType.getAddressSpace());
2831
2832     if (FromPtrType) {
2833       DestType = Context.getPointerType(DestRecordType);
2834       FromRecordType = FromPtrType->getPointeeType();
2835       PointerConversions = true;
2836     } else {
2837       DestType = DestRecordType;
2838       FromRecordType = FromType;
2839     }
2840   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2841     if (Method->isStatic())
2842       return From;
2843
2844     DestType = Method->getThisType();
2845     DestRecordType = DestType->getPointeeType();
2846
2847     if (FromType->getAs<PointerType>()) {
2848       FromRecordType = FromType->getPointeeType();
2849       PointerConversions = true;
2850     } else {
2851       FromRecordType = FromType;
2852       DestType = DestRecordType;
2853     }
2854
2855     LangAS FromAS = FromRecordType.getAddressSpace();
2856     LangAS DestAS = DestRecordType.getAddressSpace();
2857     if (FromAS != DestAS) {
2858       QualType FromRecordTypeWithoutAS =
2859           Context.removeAddrSpaceQualType(FromRecordType);
2860       QualType FromTypeWithDestAS =
2861           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2862       if (PointerConversions)
2863         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2864       From = ImpCastExprToType(From, FromTypeWithDestAS,
2865                                CK_AddressSpaceConversion, From->getValueKind())
2866                  .get();
2867     }
2868   } else {
2869     // No conversion necessary.
2870     return From;
2871   }
2872
2873   if (DestType->isDependentType() || FromType->isDependentType())
2874     return From;
2875
2876   // If the unqualified types are the same, no conversion is necessary.
2877   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2878     return From;
2879
2880   SourceRange FromRange = From->getSourceRange();
2881   SourceLocation FromLoc = FromRange.getBegin();
2882
2883   ExprValueKind VK = From->getValueKind();
2884
2885   // C++ [class.member.lookup]p8:
2886   //   [...] Ambiguities can often be resolved by qualifying a name with its
2887   //   class name.
2888   //
2889   // If the member was a qualified name and the qualified referred to a
2890   // specific base subobject type, we'll cast to that intermediate type
2891   // first and then to the object in which the member is declared. That allows
2892   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2893   //
2894   //   class Base { public: int x; };
2895   //   class Derived1 : public Base { };
2896   //   class Derived2 : public Base { };
2897   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2898   //
2899   //   void VeryDerived::f() {
2900   //     x = 17; // error: ambiguous base subobjects
2901   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2902   //   }
2903   if (Qualifier && Qualifier->getAsType()) {
2904     QualType QType = QualType(Qualifier->getAsType(), 0);
2905     assert(QType->isRecordType() && "lookup done with non-record type");
2906
2907     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2908
2909     // In C++98, the qualifier type doesn't actually have to be a base
2910     // type of the object type, in which case we just ignore it.
2911     // Otherwise build the appropriate casts.
2912     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2913       CXXCastPath BasePath;
2914       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2915                                        FromLoc, FromRange, &BasePath))
2916         return ExprError();
2917
2918       if (PointerConversions)
2919         QType = Context.getPointerType(QType);
2920       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2921                                VK, &BasePath).get();
2922
2923       FromType = QType;
2924       FromRecordType = QRecordType;
2925
2926       // If the qualifier type was the same as the destination type,
2927       // we're done.
2928       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2929         return From;
2930     }
2931   }
2932
2933   bool IgnoreAccess = false;
2934
2935   // If we actually found the member through a using declaration, cast
2936   // down to the using declaration's type.
2937   //
2938   // Pointer equality is fine here because only one declaration of a
2939   // class ever has member declarations.
2940   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2941     assert(isa<UsingShadowDecl>(FoundDecl));
2942     QualType URecordType = Context.getTypeDeclType(
2943                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2944
2945     // We only need to do this if the naming-class to declaring-class
2946     // conversion is non-trivial.
2947     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2948       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2949       CXXCastPath BasePath;
2950       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2951                                        FromLoc, FromRange, &BasePath))
2952         return ExprError();
2953
2954       QualType UType = URecordType;
2955       if (PointerConversions)
2956         UType = Context.getPointerType(UType);
2957       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2958                                VK, &BasePath).get();
2959       FromType = UType;
2960       FromRecordType = URecordType;
2961     }
2962
2963     // We don't do access control for the conversion from the
2964     // declaring class to the true declaring class.
2965     IgnoreAccess = true;
2966   }
2967
2968   CXXCastPath BasePath;
2969   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2970                                    FromLoc, FromRange, &BasePath,
2971                                    IgnoreAccess))
2972     return ExprError();
2973
2974   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2975                            VK, &BasePath);
2976 }
2977
2978 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2979                                       const LookupResult &R,
2980                                       bool HasTrailingLParen) {
2981   // Only when used directly as the postfix-expression of a call.
2982   if (!HasTrailingLParen)
2983     return false;
2984
2985   // Never if a scope specifier was provided.
2986   if (SS.isSet())
2987     return false;
2988
2989   // Only in C++ or ObjC++.
2990   if (!getLangOpts().CPlusPlus)
2991     return false;
2992
2993   // Turn off ADL when we find certain kinds of declarations during
2994   // normal lookup:
2995   for (NamedDecl *D : R) {
2996     // C++0x [basic.lookup.argdep]p3:
2997     //     -- a declaration of a class member
2998     // Since using decls preserve this property, we check this on the
2999     // original decl.
3000     if (D->isCXXClassMember())
3001       return false;
3002
3003     // C++0x [basic.lookup.argdep]p3:
3004     //     -- a block-scope function declaration that is not a
3005     //        using-declaration
3006     // NOTE: we also trigger this for function templates (in fact, we
3007     // don't check the decl type at all, since all other decl types
3008     // turn off ADL anyway).
3009     if (isa<UsingShadowDecl>(D))
3010       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3011     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3012       return false;
3013
3014     // C++0x [basic.lookup.argdep]p3:
3015     //     -- a declaration that is neither a function or a function
3016     //        template
3017     // And also for builtin functions.
3018     if (isa<FunctionDecl>(D)) {
3019       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3020
3021       // But also builtin functions.
3022       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3023         return false;
3024     } else if (!isa<FunctionTemplateDecl>(D))
3025       return false;
3026   }
3027
3028   return true;
3029 }
3030
3031
3032 /// Diagnoses obvious problems with the use of the given declaration
3033 /// as an expression.  This is only actually called for lookups that
3034 /// were not overloaded, and it doesn't promise that the declaration
3035 /// will in fact be used.
3036 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3037   if (D->isInvalidDecl())
3038     return true;
3039
3040   if (isa<TypedefNameDecl>(D)) {
3041     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3042     return true;
3043   }
3044
3045   if (isa<ObjCInterfaceDecl>(D)) {
3046     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3047     return true;
3048   }
3049
3050   if (isa<NamespaceDecl>(D)) {
3051     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3052     return true;
3053   }
3054
3055   return false;
3056 }
3057
3058 // Certain multiversion types should be treated as overloaded even when there is
3059 // only one result.
3060 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3061   assert(R.isSingleResult() && "Expected only a single result");
3062   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3063   return FD &&
3064          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3065 }
3066
3067 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3068                                           LookupResult &R, bool NeedsADL,
3069                                           bool AcceptInvalidDecl) {
3070   // If this is a single, fully-resolved result and we don't need ADL,
3071   // just build an ordinary singleton decl ref.
3072   if (!NeedsADL && R.isSingleResult() &&
3073       !R.getAsSingle<FunctionTemplateDecl>() &&
3074       !ShouldLookupResultBeMultiVersionOverload(R))
3075     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3076                                     R.getRepresentativeDecl(), nullptr,
3077                                     AcceptInvalidDecl);
3078
3079   // We only need to check the declaration if there's exactly one
3080   // result, because in the overloaded case the results can only be
3081   // functions and function templates.
3082   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3083       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3084     return ExprError();
3085
3086   // Otherwise, just build an unresolved lookup expression.  Suppress
3087   // any lookup-related diagnostics; we'll hash these out later, when
3088   // we've picked a target.
3089   R.suppressDiagnostics();
3090
3091   UnresolvedLookupExpr *ULE
3092     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3093                                    SS.getWithLocInContext(Context),
3094                                    R.getLookupNameInfo(),
3095                                    NeedsADL, R.isOverloadedResult(),
3096                                    R.begin(), R.end());
3097
3098   return ULE;
3099 }
3100
3101 static void
3102 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3103                                    ValueDecl *var, DeclContext *DC);
3104
3105 /// Complete semantic analysis for a reference to the given declaration.
3106 ExprResult Sema::BuildDeclarationNameExpr(
3107     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3108     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3109     bool AcceptInvalidDecl) {
3110   assert(D && "Cannot refer to a NULL declaration");
3111   assert(!isa<FunctionTemplateDecl>(D) &&
3112          "Cannot refer unambiguously to a function template");
3113
3114   SourceLocation Loc = NameInfo.getLoc();
3115   if (CheckDeclInExpr(*this, Loc, D))
3116     return ExprError();
3117
3118   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3119     // Specifically diagnose references to class templates that are missing
3120     // a template argument list.
3121     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3122     return ExprError();
3123   }
3124
3125   // Make sure that we're referring to a value.
3126   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3127   if (!VD) {
3128     Diag(Loc, diag::err_ref_non_value)
3129       << D << SS.getRange();
3130     Diag(D->getLocation(), diag::note_declared_at);
3131     return ExprError();
3132   }
3133
3134   // Check whether this declaration can be used. Note that we suppress
3135   // this check when we're going to perform argument-dependent lookup
3136   // on this function name, because this might not be the function
3137   // that overload resolution actually selects.
3138   if (DiagnoseUseOfDecl(VD, Loc))
3139     return ExprError();
3140
3141   // Only create DeclRefExpr's for valid Decl's.
3142   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3143     return ExprError();
3144
3145   // Handle members of anonymous structs and unions.  If we got here,
3146   // and the reference is to a class member indirect field, then this
3147   // must be the subject of a pointer-to-member expression.
3148   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3149     if (!indirectField->isCXXClassMember())
3150       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3151                                                       indirectField);
3152
3153   {
3154     QualType type = VD->getType();
3155     if (type.isNull())
3156       return ExprError();
3157     ExprValueKind valueKind = VK_RValue;
3158
3159     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3160     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3161     // is expanded by some outer '...' in the context of the use.
3162     type = type.getNonPackExpansionType();
3163
3164     switch (D->getKind()) {
3165     // Ignore all the non-ValueDecl kinds.
3166 #define ABSTRACT_DECL(kind)
3167 #define VALUE(type, base)
3168 #define DECL(type, base) \
3169     case Decl::type:
3170 #include "clang/AST/DeclNodes.inc"
3171       llvm_unreachable("invalid value decl kind");
3172
3173     // These shouldn't make it here.
3174     case Decl::ObjCAtDefsField:
3175       llvm_unreachable("forming non-member reference to ivar?");
3176
3177     // Enum constants are always r-values and never references.
3178     // Unresolved using declarations are dependent.
3179     case Decl::EnumConstant:
3180     case Decl::UnresolvedUsingValue:
3181     case Decl::OMPDeclareReduction:
3182     case Decl::OMPDeclareMapper:
3183       valueKind = VK_RValue;
3184       break;
3185
3186     // Fields and indirect fields that got here must be for
3187     // pointer-to-member expressions; we just call them l-values for
3188     // internal consistency, because this subexpression doesn't really
3189     // exist in the high-level semantics.
3190     case Decl::Field:
3191     case Decl::IndirectField:
3192     case Decl::ObjCIvar:
3193       assert(getLangOpts().CPlusPlus &&
3194              "building reference to field in C?");
3195
3196       // These can't have reference type in well-formed programs, but
3197       // for internal consistency we do this anyway.
3198       type = type.getNonReferenceType();
3199       valueKind = VK_LValue;
3200       break;
3201
3202     // Non-type template parameters are either l-values or r-values
3203     // depending on the type.
3204     case Decl::NonTypeTemplateParm: {
3205       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3206         type = reftype->getPointeeType();
3207         valueKind = VK_LValue; // even if the parameter is an r-value reference
3208         break;
3209       }
3210
3211       // For non-references, we need to strip qualifiers just in case
3212       // the template parameter was declared as 'const int' or whatever.
3213       valueKind = VK_RValue;
3214       type = type.getUnqualifiedType();
3215       break;
3216     }
3217
3218     case Decl::Var:
3219     case Decl::VarTemplateSpecialization:
3220     case Decl::VarTemplatePartialSpecialization:
3221     case Decl::Decomposition:
3222     case Decl::OMPCapturedExpr:
3223       // In C, "extern void blah;" is valid and is an r-value.
3224       if (!getLangOpts().CPlusPlus &&
3225           !type.hasQualifiers() &&
3226           type->isVoidType()) {
3227         valueKind = VK_RValue;
3228         break;
3229       }
3230       LLVM_FALLTHROUGH;
3231
3232     case Decl::ImplicitParam:
3233     case Decl::ParmVar: {
3234       // These are always l-values.
3235       valueKind = VK_LValue;
3236       type = type.getNonReferenceType();
3237
3238       // FIXME: Does the addition of const really only apply in
3239       // potentially-evaluated contexts? Since the variable isn't actually
3240       // captured in an unevaluated context, it seems that the answer is no.
3241       if (!isUnevaluatedContext()) {
3242         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3243         if (!CapturedType.isNull())
3244           type = CapturedType;
3245       }
3246
3247       break;
3248     }
3249
3250     case Decl::Binding: {
3251       // These are always lvalues.
3252       valueKind = VK_LValue;
3253       type = type.getNonReferenceType();
3254       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3255       // decides how that's supposed to work.
3256       auto *BD = cast<BindingDecl>(VD);
3257       if (BD->getDeclContext() != CurContext) {
3258         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3259         if (DD && DD->hasLocalStorage())
3260           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3261       }
3262       break;
3263     }
3264
3265     case Decl::Function: {
3266       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3267         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3268           type = Context.BuiltinFnTy;
3269           valueKind = VK_RValue;
3270           break;
3271         }
3272       }
3273
3274       const FunctionType *fty = type->castAs<FunctionType>();
3275
3276       // If we're referring to a function with an __unknown_anytype
3277       // result type, make the entire expression __unknown_anytype.
3278       if (fty->getReturnType() == Context.UnknownAnyTy) {
3279         type = Context.UnknownAnyTy;
3280         valueKind = VK_RValue;
3281         break;
3282       }
3283
3284       // Functions are l-values in C++.
3285       if (getLangOpts().CPlusPlus) {
3286         valueKind = VK_LValue;
3287         break;
3288       }
3289
3290       // C99 DR 316 says that, if a function type comes from a
3291       // function definition (without a prototype), that type is only
3292       // used for checking compatibility. Therefore, when referencing
3293       // the function, we pretend that we don't have the full function
3294       // type.
3295       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3296           isa<FunctionProtoType>(fty))
3297         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3298                                               fty->getExtInfo());
3299
3300       // Functions are r-values in C.
3301       valueKind = VK_RValue;
3302       break;
3303     }
3304
3305     case Decl::CXXDeductionGuide:
3306       llvm_unreachable("building reference to deduction guide");
3307
3308     case Decl::MSProperty:
3309     case Decl::MSGuid:
3310       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3311       // or duplicated between host and device?
3312       valueKind = VK_LValue;
3313       break;
3314
3315     case Decl::CXXMethod:
3316       // If we're referring to a method with an __unknown_anytype
3317       // result type, make the entire expression __unknown_anytype.
3318       // This should only be possible with a type written directly.
3319       if (const FunctionProtoType *proto
3320             = dyn_cast<FunctionProtoType>(VD->getType()))
3321         if (proto->getReturnType() == Context.UnknownAnyTy) {
3322           type = Context.UnknownAnyTy;
3323           valueKind = VK_RValue;
3324           break;
3325         }
3326
3327       // C++ methods are l-values if static, r-values if non-static.
3328       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3329         valueKind = VK_LValue;
3330         break;
3331       }
3332       LLVM_FALLTHROUGH;
3333
3334     case Decl::CXXConversion:
3335     case Decl::CXXDestructor:
3336     case Decl::CXXConstructor:
3337       valueKind = VK_RValue;
3338       break;
3339     }
3340
3341     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3342                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3343                             TemplateArgs);
3344   }
3345 }
3346
3347 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3348                                     SmallString<32> &Target) {
3349   Target.resize(CharByteWidth * (Source.size() + 1));
3350   char *ResultPtr = &Target[0];
3351   const llvm::UTF8 *ErrorPtr;
3352   bool success =
3353       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3354   (void)success;
3355   assert(success);
3356   Target.resize(ResultPtr - &Target[0]);
3357 }
3358
3359 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3360                                      PredefinedExpr::IdentKind IK) {
3361   // Pick the current block, lambda, captured statement or function.
3362   Decl *currentDecl = nullptr;
3363   if (const BlockScopeInfo *BSI = getCurBlock())
3364     currentDecl = BSI->TheDecl;
3365   else if (const LambdaScopeInfo *LSI = getCurLambda())
3366     currentDecl = LSI->CallOperator;
3367   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3368     currentDecl = CSI->TheCapturedDecl;
3369   else
3370     currentDecl = getCurFunctionOrMethodDecl();
3371
3372   if (!currentDecl) {
3373     Diag(Loc, diag::ext_predef_outside_function);
3374     currentDecl = Context.getTranslationUnitDecl();
3375   }
3376
3377   QualType ResTy;
3378   StringLiteral *SL = nullptr;
3379   if (cast<DeclContext>(currentDecl)->isDependentContext())
3380     ResTy = Context.DependentTy;
3381   else {
3382     // Pre-defined identifiers are of type char[x], where x is the length of
3383     // the string.
3384     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3385     unsigned Length = Str.length();
3386
3387     llvm::APInt LengthI(32, Length + 1);
3388     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3389       ResTy =
3390           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3391       SmallString<32> RawChars;
3392       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3393                               Str, RawChars);
3394       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3395                                            ArrayType::Normal,
3396                                            /*IndexTypeQuals*/ 0);
3397       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3398                                  /*Pascal*/ false, ResTy, Loc);
3399     } else {
3400       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3401       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3402                                            ArrayType::Normal,
3403                                            /*IndexTypeQuals*/ 0);
3404       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3405                                  /*Pascal*/ false, ResTy, Loc);
3406     }
3407   }
3408
3409   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3410 }
3411
3412 static std::pair<QualType, StringLiteral *>
3413 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3414                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3415   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3416
3417   if (OpType->isDependentType()) {
3418       Result.first = Context.DependentTy;
3419       return Result;
3420   }
3421
3422   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3423   llvm::APInt Length(32, Str.length() + 1);
3424   Result.first =
3425       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3426   Result.first = Context.getConstantArrayType(
3427       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3428   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3429                                         /*Pascal*/ false, Result.first, OpLoc);
3430   return Result;
3431 }
3432
3433 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3434                                        TypeSourceInfo *Operand) {
3435   QualType ResultTy;
3436   StringLiteral *SL;
3437   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3438       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3439
3440   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3441                                 PredefinedExpr::UniqueStableNameType, SL,
3442                                 Operand);
3443 }
3444
3445 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3446                                        Expr *E) {
3447   QualType ResultTy;
3448   StringLiteral *SL;
3449   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3450       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3451
3452   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3453                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3454 }
3455
3456 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3457                                            SourceLocation L, SourceLocation R,
3458                                            ParsedType Ty) {
3459   TypeSourceInfo *TInfo = nullptr;
3460   QualType T = GetTypeFromParser(Ty, &TInfo);
3461
3462   if (T.isNull())
3463     return ExprError();
3464   if (!TInfo)
3465     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3466
3467   return BuildUniqueStableName(OpLoc, TInfo);
3468 }
3469
3470 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3471                                            SourceLocation L, SourceLocation R,
3472                                            Expr *E) {
3473   return BuildUniqueStableName(OpLoc, E);
3474 }
3475
3476 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3477   PredefinedExpr::IdentKind IK;
3478
3479   switch (Kind) {
3480   default: llvm_unreachable("Unknown simple primary expr!");
3481   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3482   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3483   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3484   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3485   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3486   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3487   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3488   }
3489
3490   return BuildPredefinedExpr(Loc, IK);
3491 }
3492
3493 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3494   SmallString<16> CharBuffer;
3495   bool Invalid = false;
3496   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3497   if (Invalid)
3498     return ExprError();
3499
3500   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3501                             PP, Tok.getKind());
3502   if (Literal.hadError())
3503     return ExprError();
3504
3505   QualType Ty;
3506   if (Literal.isWide())
3507     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3508   else if (Literal.isUTF8() && getLangOpts().Char8)
3509     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3510   else if (Literal.isUTF16())
3511     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3512   else if (Literal.isUTF32())
3513     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3514   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3515     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3516   else
3517     Ty = Context.CharTy;  // 'x' -> char in C++
3518
3519   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3520   if (Literal.isWide())
3521     Kind = CharacterLiteral::Wide;
3522   else if (Literal.isUTF16())
3523     Kind = CharacterLiteral::UTF16;
3524   else if (Literal.isUTF32())
3525     Kind = CharacterLiteral::UTF32;
3526   else if (Literal.isUTF8())
3527     Kind = CharacterLiteral::UTF8;
3528
3529   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3530                                              Tok.getLocation());
3531
3532   if (Literal.getUDSuffix().empty())
3533     return Lit;
3534
3535   // We're building a user-defined literal.
3536   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3537   SourceLocation UDSuffixLoc =
3538     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3539
3540   // Make sure we're allowed user-defined literals here.
3541   if (!UDLScope)
3542     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3543
3544   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3545   //   operator "" X (ch)
3546   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3547                                         Lit, Tok.getLocation());
3548 }
3549
3550 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3551   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3552   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3553                                 Context.IntTy, Loc);
3554 }
3555
3556 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3557                                   QualType Ty, SourceLocation Loc) {
3558   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3559
3560   using llvm::APFloat;
3561   APFloat Val(Format);
3562
3563   APFloat::opStatus result = Literal.GetFloatValue(Val);
3564
3565   // Overflow is always an error, but underflow is only an error if
3566   // we underflowed to zero (APFloat reports denormals as underflow).
3567   if ((result & APFloat::opOverflow) ||
3568       ((result & APFloat::opUnderflow) && Val.isZero())) {
3569     unsigned diagnostic;
3570     SmallString<20> buffer;
3571     if (result & APFloat::opOverflow) {
3572       diagnostic = diag::warn_float_overflow;
3573       APFloat::getLargest(Format).toString(buffer);
3574     } else {
3575       diagnostic = diag::warn_float_underflow;
3576       APFloat::getSmallest(Format).toString(buffer);
3577     }
3578
3579     S.Diag(Loc, diagnostic)
3580       << Ty
3581       << StringRef(buffer.data(), buffer.size());
3582   }
3583
3584   bool isExact = (result == APFloat::opOK);
3585   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3586 }
3587
3588 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3589   assert(E && "Invalid expression");
3590
3591   if (E->isValueDependent())
3592     return false;
3593
3594   QualType QT = E->getType();
3595   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3596     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3597     return true;
3598   }
3599
3600   llvm::APSInt ValueAPS;
3601   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3602
3603   if (R.isInvalid())
3604     return true;
3605
3606   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3607   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3608     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3609         << ValueAPS.toString(10) << ValueIsPositive;
3610     return true;
3611   }
3612
3613   return false;
3614 }
3615
3616 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3617   // Fast path for a single digit (which is quite common).  A single digit
3618   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3619   if (Tok.getLength() == 1) {
3620     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3621     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3622   }
3623
3624   SmallString<128> SpellingBuffer;
3625   // NumericLiteralParser wants to overread by one character.  Add padding to
3626   // the buffer in case the token is copied to the buffer.  If getSpelling()
3627   // returns a StringRef to the memory buffer, it should have a null char at
3628   // the EOF, so it is also safe.
3629   SpellingBuffer.resize(Tok.getLength() + 1);
3630
3631   // Get the spelling of the token, which eliminates trigraphs, etc.
3632   bool Invalid = false;
3633   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3634   if (Invalid)
3635     return ExprError();
3636
3637   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3638                                PP.getSourceManager(), PP.getLangOpts(),
3639                                PP.getTargetInfo(), PP.getDiagnostics());
3640   if (Literal.hadError)
3641     return ExprError();
3642
3643   if (Literal.hasUDSuffix()) {
3644     // We're building a user-defined literal.
3645     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3646     SourceLocation UDSuffixLoc =
3647       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3648
3649     // Make sure we're allowed user-defined literals here.
3650     if (!UDLScope)
3651       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3652
3653     QualType CookedTy;
3654     if (Literal.isFloatingLiteral()) {
3655       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3656       // long double, the literal is treated as a call of the form
3657       //   operator "" X (f L)
3658       CookedTy = Context.LongDoubleTy;
3659     } else {
3660       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3661       // unsigned long long, the literal is treated as a call of the form
3662       //   operator "" X (n ULL)
3663       CookedTy = Context.UnsignedLongLongTy;
3664     }
3665
3666     DeclarationName OpName =
3667       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3668     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3669     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3670
3671     SourceLocation TokLoc = Tok.getLocation();
3672
3673     // Perform literal operator lookup to determine if we're building a raw
3674     // literal or a cooked one.
3675     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3676     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3677                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3678                                   /*AllowStringTemplate*/ false,
3679                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3680     case LOLR_ErrorNoDiagnostic:
3681       // Lookup failure for imaginary constants isn't fatal, there's still the
3682       // GNU extension producing _Complex types.
3683       break;
3684     case LOLR_Error:
3685       return ExprError();
3686     case LOLR_Cooked: {
3687       Expr *Lit;
3688       if (Literal.isFloatingLiteral()) {
3689         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3690       } else {
3691         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3692         if (Literal.GetIntegerValue(ResultVal))
3693           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3694               << /* Unsigned */ 1;
3695         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3696                                      Tok.getLocation());
3697       }
3698       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3699     }
3700
3701     case LOLR_Raw: {
3702       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3703       // literal is treated as a call of the form
3704       //   operator "" X ("n")
3705       unsigned Length = Literal.getUDSuffixOffset();
3706       QualType StrTy = Context.getConstantArrayType(
3707           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3708           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3709       Expr *Lit = StringLiteral::Create(
3710           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3711           /*Pascal*/false, StrTy, &TokLoc, 1);
3712       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3713     }
3714
3715     case LOLR_Template: {
3716       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3717       // template), L is treated as a call fo the form
3718       //   operator "" X <'c1', 'c2', ... 'ck'>()
3719       // where n is the source character sequence c1 c2 ... ck.
3720       TemplateArgumentListInfo ExplicitArgs;
3721       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3722       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3723       llvm::APSInt Value(CharBits, CharIsUnsigned);
3724       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3725         Value = TokSpelling[I];
3726         TemplateArgument Arg(Context, Value, Context.CharTy);
3727         TemplateArgumentLocInfo ArgInfo;
3728         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3729       }
3730       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3731                                       &ExplicitArgs);
3732     }
3733     case LOLR_StringTemplate:
3734       llvm_unreachable("unexpected literal operator lookup result");
3735     }
3736   }
3737
3738   Expr *Res;
3739
3740   if (Literal.isFixedPointLiteral()) {
3741     QualType Ty;
3742
3743     if (Literal.isAccum) {
3744       if (Literal.isHalf) {
3745         Ty = Context.ShortAccumTy;
3746       } else if (Literal.isLong) {
3747         Ty = Context.LongAccumTy;
3748       } else {
3749         Ty = Context.AccumTy;
3750       }
3751     } else if (Literal.isFract) {
3752       if (Literal.isHalf) {
3753         Ty = Context.ShortFractTy;
3754       } else if (Literal.isLong) {
3755         Ty = Context.LongFractTy;
3756       } else {
3757         Ty = Context.FractTy;
3758       }
3759     }
3760
3761     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3762
3763     bool isSigned = !Literal.isUnsigned;
3764     unsigned scale = Context.getFixedPointScale(Ty);
3765     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3766
3767     llvm::APInt Val(bit_width, 0, isSigned);
3768     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3769     bool ValIsZero = Val.isNullValue() && !Overflowed;
3770
3771     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3772     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3773       // Clause 6.4.4 - The value of a constant shall be in the range of
3774       // representable values for its type, with exception for constants of a
3775       // fract type with a value of exactly 1; such a constant shall denote
3776       // the maximal value for the type.
3777       --Val;
3778     else if (Val.ugt(MaxVal) || Overflowed)
3779       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3780
3781     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3782                                               Tok.getLocation(), scale);
3783   } else if (Literal.isFloatingLiteral()) {
3784     QualType Ty;
3785     if (Literal.isHalf){
3786       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3787         Ty = Context.HalfTy;
3788       else {
3789         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3790         return ExprError();
3791       }
3792     } else if (Literal.isFloat)
3793       Ty = Context.FloatTy;
3794     else if (Literal.isLong)
3795       Ty = Context.LongDoubleTy;
3796     else if (Literal.isFloat16)
3797       Ty = Context.Float16Ty;
3798     else if (Literal.isFloat128)
3799       Ty = Context.Float128Ty;
3800     else
3801       Ty = Context.DoubleTy;
3802
3803     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3804
3805     if (Ty == Context.DoubleTy) {
3806       if (getLangOpts().SinglePrecisionConstants) {
3807         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3808         if (BTy->getKind() != BuiltinType::Float) {
3809           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3810         }
3811       } else if (getLangOpts().OpenCL &&
3812                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3813         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3814         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3815         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3816       }
3817     }
3818   } else if (!Literal.isIntegerLiteral()) {
3819     return ExprError();
3820   } else {
3821     QualType Ty;
3822
3823     // 'long long' is a C99 or C++11 feature.
3824     if (!getLangOpts().C99 && Literal.isLongLong) {
3825       if (getLangOpts().CPlusPlus)
3826         Diag(Tok.getLocation(),
3827              getLangOpts().CPlusPlus11 ?
3828              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3829       else
3830         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3831     }
3832
3833     // Get the value in the widest-possible width.
3834     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3835     llvm::APInt ResultVal(MaxWidth, 0);
3836
3837     if (Literal.GetIntegerValue(ResultVal)) {
3838       // If this value didn't fit into uintmax_t, error and force to ull.
3839       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3840           << /* Unsigned */ 1;
3841       Ty = Context.UnsignedLongLongTy;
3842       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3843              "long long is not intmax_t?");
3844     } else {
3845       // If this value fits into a ULL, try to figure out what else it fits into
3846       // according to the rules of C99 6.4.4.1p5.
3847
3848       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3849       // be an unsigned int.
3850       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3851
3852       // Check from smallest to largest, picking the smallest type we can.
3853       unsigned Width = 0;
3854
3855       // Microsoft specific integer suffixes are explicitly sized.
3856       if (Literal.MicrosoftInteger) {
3857         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3858           Width = 8;
3859           Ty = Context.CharTy;
3860         } else {
3861           Width = Literal.MicrosoftInteger;
3862           Ty = Context.getIntTypeForBitwidth(Width,
3863                                              /*Signed=*/!Literal.isUnsigned);
3864         }
3865       }
3866
3867       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3868         // Are int/unsigned possibilities?
3869         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3870
3871         // Does it fit in a unsigned int?
3872         if (ResultVal.isIntN(IntSize)) {
3873           // Does it fit in a signed int?
3874           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3875             Ty = Context.IntTy;
3876           else if (AllowUnsigned)
3877             Ty = Context.UnsignedIntTy;
3878           Width = IntSize;
3879         }
3880       }
3881
3882       // Are long/unsigned long possibilities?
3883       if (Ty.isNull() && !Literal.isLongLong) {
3884         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3885
3886         // Does it fit in a unsigned long?
3887         if (ResultVal.isIntN(LongSize)) {
3888           // Does it fit in a signed long?
3889           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3890             Ty = Context.LongTy;
3891           else if (AllowUnsigned)
3892             Ty = Context.UnsignedLongTy;
3893           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3894           // is compatible.
3895           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3896             const unsigned LongLongSize =
3897                 Context.getTargetInfo().getLongLongWidth();
3898             Diag(Tok.getLocation(),
3899                  getLangOpts().CPlusPlus
3900                      ? Literal.isLong
3901                            ? diag::warn_old_implicitly_unsigned_long_cxx
3902                            : /*C++98 UB*/ diag::
3903                                  ext_old_implicitly_unsigned_long_cxx
3904                      : diag::warn_old_implicitly_unsigned_long)
3905                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3906                                             : /*will be ill-formed*/ 1);
3907             Ty = Context.UnsignedLongTy;
3908           }
3909           Width = LongSize;
3910         }
3911       }
3912
3913       // Check long long if needed.
3914       if (Ty.isNull()) {
3915         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3916
3917         // Does it fit in a unsigned long long?
3918         if (ResultVal.isIntN(LongLongSize)) {
3919           // Does it fit in a signed long long?
3920           // To be compatible with MSVC, hex integer literals ending with the
3921           // LL or i64 suffix are always signed in Microsoft mode.
3922           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3923               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3924             Ty = Context.LongLongTy;
3925           else if (AllowUnsigned)
3926             Ty = Context.UnsignedLongLongTy;
3927           Width = LongLongSize;
3928         }
3929       }
3930
3931       // If we still couldn't decide a type, we probably have something that
3932       // does not fit in a signed long long, but has no U suffix.
3933       if (Ty.isNull()) {
3934         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3935         Ty = Context.UnsignedLongLongTy;
3936         Width = Context.getTargetInfo().getLongLongWidth();
3937       }
3938
3939       if (ResultVal.getBitWidth() != Width)
3940         ResultVal = ResultVal.trunc(Width);
3941     }
3942     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3943   }
3944
3945   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3946   if (Literal.isImaginary) {
3947     Res = new (Context) ImaginaryLiteral(Res,
3948                                         Context.getComplexType(Res->getType()));
3949
3950     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3951   }
3952   return Res;
3953 }
3954
3955 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3956   assert(E && "ActOnParenExpr() missing expr");
3957   return new (Context) ParenExpr(L, R, E);
3958 }
3959
3960 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3961                                          SourceLocation Loc,
3962                                          SourceRange ArgRange) {
3963   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3964   // scalar or vector data type argument..."
3965   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3966   // type (C99 6.2.5p18) or void.
3967   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3968     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3969       << T << ArgRange;
3970     return true;
3971   }
3972
3973   assert((T->isVoidType() || !T->isIncompleteType()) &&
3974          "Scalar types should always be complete");
3975   return false;
3976 }
3977
3978 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3979                                            SourceLocation Loc,
3980                                            SourceRange ArgRange,
3981                                            UnaryExprOrTypeTrait TraitKind) {
3982   // Invalid types must be hard errors for SFINAE in C++.
3983   if (S.LangOpts.CPlusPlus)
3984     return true;
3985
3986   // C99 6.5.3.4p1:
3987   if (T->isFunctionType() &&
3988       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3989        TraitKind == UETT_PreferredAlignOf)) {
3990     // sizeof(function)/alignof(function) is allowed as an extension.
3991     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3992         << getTraitSpelling(TraitKind) << ArgRange;
3993     return false;
3994   }
3995
3996   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3997   // this is an error (OpenCL v1.1 s6.3.k)
3998   if (T->isVoidType()) {
3999     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4000                                         : diag::ext_sizeof_alignof_void_type;
4001     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4002     return false;
4003   }
4004
4005   return true;
4006 }
4007
4008 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4009                                              SourceLocation Loc,
4010                                              SourceRange ArgRange,
4011                                              UnaryExprOrTypeTrait TraitKind) {
4012   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4013   // runtime doesn't allow it.
4014   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4015     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4016       << T << (TraitKind == UETT_SizeOf)
4017       << ArgRange;
4018     return true;
4019   }
4020
4021   return false;
4022 }
4023
4024 /// Check whether E is a pointer from a decayed array type (the decayed
4025 /// pointer type is equal to T) and emit a warning if it is.
4026 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4027                                      Expr *E) {
4028   // Don't warn if the operation changed the type.
4029   if (T != E->getType())
4030     return;
4031
4032   // Now look for array decays.
4033   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4034   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4035     return;
4036
4037   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4038                                              << ICE->getType()
4039                                              << ICE->getSubExpr()->getType();
4040 }
4041
4042 /// Check the constraints on expression operands to unary type expression
4043 /// and type traits.
4044 ///
4045 /// Completes any types necessary and validates the constraints on the operand
4046 /// expression. The logic mostly mirrors the type-based overload, but may modify
4047 /// the expression as it completes the type for that expression through template
4048 /// instantiation, etc.
4049 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4050                                             UnaryExprOrTypeTrait ExprKind) {
4051   QualType ExprTy = E->getType();
4052   assert(!ExprTy->isReferenceType());
4053
4054   bool IsUnevaluatedOperand =
4055       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4056        ExprKind == UETT_PreferredAlignOf);
4057   if (IsUnevaluatedOperand) {
4058     ExprResult Result = CheckUnevaluatedOperand(E);
4059     if (Result.isInvalid())
4060       return true;
4061     E = Result.get();
4062   }
4063
4064   if (ExprKind == UETT_VecStep)
4065     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4066                                         E->getSourceRange());
4067
4068   // Explicitly list some types as extensions.
4069   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4070                                       E->getSourceRange(), ExprKind))
4071     return false;
4072
4073   // 'alignof' applied to an expression only requires the base element type of
4074   // the expression to be complete. 'sizeof' requires the expression's type to
4075   // be complete (and will attempt to complete it if it's an array of unknown
4076   // bound).
4077   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4078     if (RequireCompleteSizedType(
4079             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4080             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4081             getTraitSpelling(ExprKind), E->getSourceRange()))
4082       return true;
4083   } else {
4084     if (RequireCompleteSizedExprType(
4085             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4086             getTraitSpelling(ExprKind), E->getSourceRange()))
4087       return true;
4088   }
4089
4090   // Completing the expression's type may have changed it.
4091   ExprTy = E->getType();
4092   assert(!ExprTy->isReferenceType());
4093
4094   if (ExprTy->isFunctionType()) {
4095     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4096         << getTraitSpelling(ExprKind) << E->getSourceRange();
4097     return true;
4098   }
4099
4100   // The operand for sizeof and alignof is in an unevaluated expression context,
4101   // so side effects could result in unintended consequences.
4102   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4103       E->HasSideEffects(Context, false))
4104     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4105
4106   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4107                                        E->getSourceRange(), ExprKind))
4108     return true;
4109
4110   if (ExprKind == UETT_SizeOf) {
4111     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4112       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4113         QualType OType = PVD->getOriginalType();
4114         QualType Type = PVD->getType();
4115         if (Type->isPointerType() && OType->isArrayType()) {
4116           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4117             << Type << OType;
4118           Diag(PVD->getLocation(), diag::note_declared_at);
4119         }
4120       }
4121     }
4122
4123     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4124     // decays into a pointer and returns an unintended result. This is most
4125     // likely a typo for "sizeof(array) op x".
4126     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4127       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4128                                BO->getLHS());
4129       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4130                                BO->getRHS());
4131     }
4132   }
4133
4134   return false;
4135 }
4136
4137 /// Check the constraints on operands to unary expression and type
4138 /// traits.
4139 ///
4140 /// This will complete any types necessary, and validate the various constraints
4141 /// on those operands.
4142 ///
4143 /// The UsualUnaryConversions() function is *not* called by this routine.
4144 /// C99 6.3.2.1p[2-4] all state:
4145 ///   Except when it is the operand of the sizeof operator ...
4146 ///
4147 /// C++ [expr.sizeof]p4
4148 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4149 ///   standard conversions are not applied to the operand of sizeof.
4150 ///
4151 /// This policy is followed for all of the unary trait expressions.
4152 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4153                                             SourceLocation OpLoc,
4154                                             SourceRange ExprRange,
4155                                             UnaryExprOrTypeTrait ExprKind) {
4156   if (ExprType->isDependentType())
4157     return false;
4158
4159   // C++ [expr.sizeof]p2:
4160   //     When applied to a reference or a reference type, the result
4161   //     is the size of the referenced type.
4162   // C++11 [expr.alignof]p3:
4163   //     When alignof is applied to a reference type, the result
4164   //     shall be the alignment of the referenced type.
4165   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4166     ExprType = Ref->getPointeeType();
4167
4168   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4169   //   When alignof or _Alignof is applied to an array type, the result
4170   //   is the alignment of the element type.
4171   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4172       ExprKind == UETT_OpenMPRequiredSimdAlign)
4173     ExprType = Context.getBaseElementType(ExprType);
4174
4175   if (ExprKind == UETT_VecStep)
4176     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4177
4178   // Explicitly list some types as extensions.
4179   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4180                                       ExprKind))
4181     return false;
4182
4183   if (RequireCompleteSizedType(
4184           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4185           getTraitSpelling(ExprKind), ExprRange))
4186     return true;
4187
4188   if (ExprType->isFunctionType()) {
4189     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4190         << getTraitSpelling(ExprKind) << ExprRange;
4191     return true;
4192   }
4193
4194   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4195                                        ExprKind))
4196     return true;
4197
4198   return false;
4199 }
4200
4201 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4202   // Cannot know anything else if the expression is dependent.
4203   if (E->isTypeDependent())
4204     return false;
4205
4206   if (E->getObjectKind() == OK_BitField) {
4207     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4208        << 1 << E->getSourceRange();
4209     return true;
4210   }
4211
4212   ValueDecl *D = nullptr;
4213   Expr *Inner = E->IgnoreParens();
4214   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4215     D = DRE->getDecl();
4216   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4217     D = ME->getMemberDecl();
4218   }
4219
4220   // If it's a field, require the containing struct to have a
4221   // complete definition so that we can compute the layout.
4222   //
4223   // This can happen in C++11 onwards, either by naming the member
4224   // in a way that is not transformed into a member access expression
4225   // (in an unevaluated operand, for instance), or by naming the member
4226   // in a trailing-return-type.
4227   //
4228   // For the record, since __alignof__ on expressions is a GCC
4229   // extension, GCC seems to permit this but always gives the
4230   // nonsensical answer 0.
4231   //
4232   // We don't really need the layout here --- we could instead just
4233   // directly check for all the appropriate alignment-lowing
4234   // attributes --- but that would require duplicating a lot of
4235   // logic that just isn't worth duplicating for such a marginal
4236   // use-case.
4237   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4238     // Fast path this check, since we at least know the record has a
4239     // definition if we can find a member of it.
4240     if (!FD->getParent()->isCompleteDefinition()) {
4241       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4242         << E->getSourceRange();
4243       return true;
4244     }
4245
4246     // Otherwise, if it's a field, and the field doesn't have
4247     // reference type, then it must have a complete type (or be a
4248     // flexible array member, which we explicitly want to
4249     // white-list anyway), which makes the following checks trivial.
4250     if (!FD->getType()->isReferenceType())
4251       return false;
4252   }
4253
4254   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4255 }
4256
4257 bool Sema::CheckVecStepExpr(Expr *E) {
4258   E = E->IgnoreParens();
4259
4260   // Cannot know anything else if the expression is dependent.
4261   if (E->isTypeDependent())
4262     return false;
4263
4264   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4265 }
4266
4267 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4268                                         CapturingScopeInfo *CSI) {
4269   assert(T->isVariablyModifiedType());
4270   assert(CSI != nullptr);
4271
4272   // We're going to walk down into the type and look for VLA expressions.
4273   do {
4274     const Type *Ty = T.getTypePtr();
4275     switch (Ty->getTypeClass()) {
4276 #define TYPE(Class, Base)
4277 #define ABSTRACT_TYPE(Class, Base)
4278 #define NON_CANONICAL_TYPE(Class, Base)
4279 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4280 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4281 #include "clang/AST/TypeNodes.inc"
4282       T = QualType();
4283       break;
4284     // These types are never variably-modified.
4285     case Type::Builtin:
4286     case Type::Complex:
4287     case Type::Vector:
4288     case Type::ExtVector:
4289     case Type::ConstantMatrix:
4290     case Type::Record:
4291     case Type::Enum:
4292     case Type::Elaborated:
4293     case Type::TemplateSpecialization:
4294     case Type::ObjCObject:
4295     case Type::ObjCInterface:
4296     case Type::ObjCObjectPointer:
4297     case Type::ObjCTypeParam:
4298     case Type::Pipe:
4299     case Type::ExtInt:
4300       llvm_unreachable("type class is never variably-modified!");
4301     case Type::Adjusted:
4302       T = cast<AdjustedType>(Ty)->getOriginalType();
4303       break;
4304     case Type::Decayed:
4305       T = cast<DecayedType>(Ty)->getPointeeType();
4306       break;
4307     case Type::Pointer:
4308       T = cast<PointerType>(Ty)->getPointeeType();
4309       break;
4310     case Type::BlockPointer:
4311       T = cast<BlockPointerType>(Ty)->getPointeeType();
4312       break;
4313     case Type::LValueReference:
4314     case Type::RValueReference:
4315       T = cast<ReferenceType>(Ty)->getPointeeType();
4316       break;
4317     case Type::MemberPointer:
4318       T = cast<MemberPointerType>(Ty)->getPointeeType();
4319       break;
4320     case Type::ConstantArray:
4321     case Type::IncompleteArray:
4322       // Losing element qualification here is fine.
4323       T = cast<ArrayType>(Ty)->getElementType();
4324       break;
4325     case Type::VariableArray: {
4326       // Losing element qualification here is fine.
4327       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4328
4329       // Unknown size indication requires no size computation.
4330       // Otherwise, evaluate and record it.
4331       auto Size = VAT->getSizeExpr();
4332       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4333           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4334         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4335
4336       T = VAT->getElementType();
4337       break;
4338     }
4339     case Type::FunctionProto:
4340     case Type::FunctionNoProto:
4341       T = cast<FunctionType>(Ty)->getReturnType();
4342       break;
4343     case Type::Paren:
4344     case Type::TypeOf:
4345     case Type::UnaryTransform:
4346     case Type::Attributed:
4347     case Type::SubstTemplateTypeParm:
4348     case Type::PackExpansion:
4349     case Type::MacroQualified:
4350       // Keep walking after single level desugaring.
4351       T = T.getSingleStepDesugaredType(Context);
4352       break;
4353     case Type::Typedef:
4354       T = cast<TypedefType>(Ty)->desugar();
4355       break;
4356     case Type::Decltype:
4357       T = cast<DecltypeType>(Ty)->desugar();
4358       break;
4359     case Type::Auto:
4360     case Type::DeducedTemplateSpecialization:
4361       T = cast<DeducedType>(Ty)->getDeducedType();
4362       break;
4363     case Type::TypeOfExpr:
4364       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4365       break;
4366     case Type::Atomic:
4367       T = cast<AtomicType>(Ty)->getValueType();
4368       break;
4369     }
4370   } while (!T.isNull() && T->isVariablyModifiedType());
4371 }
4372
4373 /// Build a sizeof or alignof expression given a type operand.
4374 ExprResult
4375 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4376                                      SourceLocation OpLoc,
4377                                      UnaryExprOrTypeTrait ExprKind,
4378                                      SourceRange R) {
4379   if (!TInfo)
4380     return ExprError();
4381
4382   QualType T = TInfo->getType();
4383
4384   if (!T->isDependentType() &&
4385       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4386     return ExprError();
4387
4388   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4389     if (auto *TT = T->getAs<TypedefType>()) {
4390       for (auto I = FunctionScopes.rbegin(),
4391                 E = std::prev(FunctionScopes.rend());
4392            I != E; ++I) {
4393         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4394         if (CSI == nullptr)
4395           break;
4396         DeclContext *DC = nullptr;
4397         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4398           DC = LSI->CallOperator;
4399         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4400           DC = CRSI->TheCapturedDecl;
4401         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4402           DC = BSI->TheDecl;
4403         if (DC) {
4404           if (DC->containsDecl(TT->getDecl()))
4405             break;
4406           captureVariablyModifiedType(Context, T, CSI);
4407         }
4408       }
4409     }
4410   }
4411
4412   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4413   return new (Context) UnaryExprOrTypeTraitExpr(
4414       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4415 }
4416
4417 /// Build a sizeof or alignof expression given an expression
4418 /// operand.
4419 ExprResult
4420 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4421                                      UnaryExprOrTypeTrait ExprKind) {
4422   ExprResult PE = CheckPlaceholderExpr(E);
4423   if (PE.isInvalid())
4424     return ExprError();
4425
4426   E = PE.get();
4427
4428   // Verify that the operand is valid.
4429   bool isInvalid = false;
4430   if (E->isTypeDependent()) {
4431     // Delay type-checking for type-dependent expressions.
4432   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4433     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4434   } else if (ExprKind == UETT_VecStep) {
4435     isInvalid = CheckVecStepExpr(E);
4436   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4437       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4438       isInvalid = true;
4439   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4440     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4441     isInvalid = true;
4442   } else {
4443     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4444   }
4445
4446   if (isInvalid)
4447     return ExprError();
4448
4449   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4450     PE = TransformToPotentiallyEvaluated(E);
4451     if (PE.isInvalid()) return ExprError();
4452     E = PE.get();
4453   }
4454
4455   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4456   return new (Context) UnaryExprOrTypeTraitExpr(
4457       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4458 }
4459
4460 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4461 /// expr and the same for @c alignof and @c __alignof
4462 /// Note that the ArgRange is invalid if isType is false.
4463 ExprResult
4464 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4465                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4466                                     void *TyOrEx, SourceRange ArgRange) {
4467   // If error parsing type, ignore.
4468   if (!TyOrEx) return ExprError();
4469
4470   if (IsType) {
4471     TypeSourceInfo *TInfo;
4472     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4473     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4474   }
4475
4476   Expr *ArgEx = (Expr *)TyOrEx;
4477   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4478   return Result;
4479 }
4480
4481 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4482                                      bool IsReal) {
4483   if (V.get()->isTypeDependent())
4484     return S.Context.DependentTy;
4485
4486   // _Real and _Imag are only l-values for normal l-values.
4487   if (V.get()->getObjectKind() != OK_Ordinary) {
4488     V = S.DefaultLvalueConversion(V.get());
4489     if (V.isInvalid())
4490       return QualType();
4491   }
4492
4493   // These operators return the element type of a complex type.
4494   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4495     return CT->getElementType();
4496
4497   // Otherwise they pass through real integer and floating point types here.
4498   if (V.get()->getType()->isArithmeticType())
4499     return V.get()->getType();
4500
4501   // Test for placeholders.
4502   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4503   if (PR.isInvalid()) return QualType();
4504   if (PR.get() != V.get()) {
4505     V = PR;
4506     return CheckRealImagOperand(S, V, Loc, IsReal);
4507   }
4508
4509   // Reject anything else.
4510   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4511     << (IsReal ? "__real" : "__imag");
4512   return QualType();
4513 }
4514
4515
4516
4517 ExprResult
4518 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4519                           tok::TokenKind Kind, Expr *Input) {
4520   UnaryOperatorKind Opc;
4521   switch (Kind) {
4522   default: llvm_unreachable("Unknown unary op!");
4523   case tok::plusplus:   Opc = UO_PostInc; break;
4524   case tok::minusminus: Opc = UO_PostDec; break;
4525   }
4526
4527   // Since this might is a postfix expression, get rid of ParenListExprs.
4528   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4529   if (Result.isInvalid()) return ExprError();
4530   Input = Result.get();
4531
4532   return BuildUnaryOp(S, OpLoc, Opc, Input);
4533 }
4534
4535 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4536 ///
4537 /// \return true on error
4538 static bool checkArithmeticOnObjCPointer(Sema &S,
4539                                          SourceLocation opLoc,
4540                                          Expr *op) {
4541   assert(op->getType()->isObjCObjectPointerType());
4542   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4543       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4544     return false;
4545
4546   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4547     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4548     << op->getSourceRange();
4549   return true;
4550 }
4551
4552 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4553   auto *BaseNoParens = Base->IgnoreParens();
4554   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4555     return MSProp->getPropertyDecl()->getType()->isArrayType();
4556   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4557 }
4558
4559 ExprResult
4560 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4561                               Expr *idx, SourceLocation rbLoc) {
4562   if (base && !base->getType().isNull() &&
4563       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4564     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4565                                     SourceLocation(), /*Length*/ nullptr,
4566                                     /*Stride=*/nullptr, rbLoc);
4567
4568   // Since this might be a postfix expression, get rid of ParenListExprs.
4569   if (isa<ParenListExpr>(base)) {
4570     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4571     if (result.isInvalid()) return ExprError();
4572     base = result.get();
4573   }
4574
4575   // Check if base and idx form a MatrixSubscriptExpr.
4576   //
4577   // Helper to check for comma expressions, which are not allowed as indices for
4578   // matrix subscript expressions.
4579   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4580     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4581       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4582           << SourceRange(base->getBeginLoc(), rbLoc);
4583       return true;
4584     }
4585     return false;
4586   };
4587   // The matrix subscript operator ([][])is considered a single operator.
4588   // Separating the index expressions by parenthesis is not allowed.
4589   if (base->getType()->isSpecificPlaceholderType(
4590           BuiltinType::IncompleteMatrixIdx) &&
4591       !isa<MatrixSubscriptExpr>(base)) {
4592     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4593         << SourceRange(base->getBeginLoc(), rbLoc);
4594     return ExprError();
4595   }
4596   // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4597   // a new MatrixSubscriptExpr.
4598   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4599   if (matSubscriptE) {
4600     if (CheckAndReportCommaError(idx))
4601       return ExprError();
4602
4603     assert(matSubscriptE->isIncomplete() &&
4604            "base has to be an incomplete matrix subscript");
4605     return CreateBuiltinMatrixSubscriptExpr(
4606         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4607   }
4608   Expr *matrixBase = base;
4609   bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4610   if (!IsMSPropertySubscript) {
4611     ExprResult result = CheckPlaceholderExpr(base);
4612     if (!result.isInvalid())
4613       matrixBase = result.get();
4614   }
4615   if (matrixBase->getType()->isMatrixType()) {
4616     if (CheckAndReportCommaError(idx))
4617       return ExprError();
4618
4619     return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4620   }
4621
4622   // A comma-expression as the index is deprecated in C++2a onwards.
4623   if (getLangOpts().CPlusPlus20 &&
4624       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4625        (isa<CXXOperatorCallExpr>(idx) &&
4626         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4627     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4628       << SourceRange(base->getBeginLoc(), rbLoc);
4629   }
4630
4631   // Handle any non-overload placeholder types in the base and index
4632   // expressions.  We can't handle overloads here because the other
4633   // operand might be an overloadable type, in which case the overload
4634   // resolution for the operator overload should get the first crack
4635   // at the overload.
4636   if (base->getType()->isNonOverloadPlaceholderType()) {
4637     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4638     if (!IsMSPropertySubscript) {
4639       ExprResult result = CheckPlaceholderExpr(base);
4640       if (result.isInvalid())
4641         return ExprError();
4642       base = result.get();
4643     }
4644   }
4645   if (idx->getType()->isNonOverloadPlaceholderType()) {
4646     ExprResult result = CheckPlaceholderExpr(idx);
4647     if (result.isInvalid()) return ExprError();
4648     idx = result.get();
4649   }
4650
4651   // Build an unanalyzed expression if either operand is type-dependent.
4652   if (getLangOpts().CPlusPlus &&
4653       (base->isTypeDependent() || idx->isTypeDependent())) {
4654     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4655                                             VK_LValue, OK_Ordinary, rbLoc);
4656   }
4657
4658   // MSDN, property (C++)
4659   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4660   // This attribute can also be used in the declaration of an empty array in a
4661   // class or structure definition. For example:
4662   // __declspec(property(get=GetX, put=PutX)) int x[];
4663   // The above statement indicates that x[] can be used with one or more array
4664   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4665   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4666   if (IsMSPropertySubscript) {
4667     // Build MS property subscript expression if base is MS property reference
4668     // or MS property subscript.
4669     return new (Context) MSPropertySubscriptExpr(
4670         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4671   }
4672
4673   // Use C++ overloaded-operator rules if either operand has record
4674   // type.  The spec says to do this if either type is *overloadable*,
4675   // but enum types can't declare subscript operators or conversion
4676   // operators, so there's nothing interesting for overload resolution
4677   // to do if there aren't any record types involved.
4678   //
4679   // ObjC pointers have their own subscripting logic that is not tied
4680   // to overload resolution and so should not take this path.
4681   if (getLangOpts().CPlusPlus &&
4682       (base->getType()->isRecordType() ||
4683        (!base->getType()->isObjCObjectPointerType() &&
4684         idx->getType()->isRecordType()))) {
4685     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4686   }
4687
4688   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4689
4690   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4691     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4692
4693   return Res;
4694 }
4695
4696 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4697   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4698   InitializationKind Kind =
4699       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4700   InitializationSequence InitSeq(*this, Entity, Kind, E);
4701   return InitSeq.Perform(*this, Entity, Kind, E);
4702 }
4703
4704 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4705                                                   Expr *ColumnIdx,
4706                                                   SourceLocation RBLoc) {
4707   ExprResult BaseR = CheckPlaceholderExpr(Base);
4708   if (BaseR.isInvalid())
4709     return BaseR;
4710   Base = BaseR.get();
4711
4712   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4713   if (RowR.isInvalid())
4714     return RowR;
4715   RowIdx = RowR.get();
4716
4717   if (!ColumnIdx)
4718     return new (Context) MatrixSubscriptExpr(
4719         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4720
4721   // Build an unanalyzed expression if any of the operands is type-dependent.
4722   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4723       ColumnIdx->isTypeDependent())
4724     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4725                                              Context.DependentTy, RBLoc);
4726
4727   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4728   if (ColumnR.isInvalid())
4729     return ColumnR;
4730   ColumnIdx = ColumnR.get();
4731
4732   // Check that IndexExpr is an integer expression. If it is a constant
4733   // expression, check that it is less than Dim (= the number of elements in the
4734   // corresponding dimension).
4735   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4736                           bool IsColumnIdx) -> Expr * {
4737     if (!IndexExpr->getType()->isIntegerType() &&
4738         !IndexExpr->isTypeDependent()) {
4739       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4740           << IsColumnIdx;
4741       return nullptr;
4742     }
4743
4744     llvm::APSInt Idx;
4745     if (IndexExpr->isIntegerConstantExpr(Idx, Context) &&
4746         (Idx < 0 || Idx >= Dim)) {
4747       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4748           << IsColumnIdx << Dim;
4749       return nullptr;
4750     }
4751
4752     ExprResult ConvExpr =
4753         tryConvertExprToType(IndexExpr, Context.getSizeType());
4754     assert(!ConvExpr.isInvalid() &&
4755            "should be able to convert any integer type to size type");
4756     return ConvExpr.get();
4757   };
4758
4759   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4760   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4761   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4762   if (!RowIdx || !ColumnIdx)
4763     return ExprError();
4764
4765   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4766                                            MTy->getElementType(), RBLoc);
4767 }
4768
4769 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4770   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4771   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4772
4773   // For expressions like `&(*s).b`, the base is recorded and what should be
4774   // checked.
4775   const MemberExpr *Member = nullptr;
4776   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4777     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4778
4779   LastRecord.PossibleDerefs.erase(StrippedExpr);
4780 }
4781
4782 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4783   QualType ResultTy = E->getType();
4784   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4785
4786   // Bail if the element is an array since it is not memory access.
4787   if (isa<ArrayType>(ResultTy))
4788     return;
4789
4790   if (ResultTy->hasAttr(attr::NoDeref)) {
4791     LastRecord.PossibleDerefs.insert(E);
4792     return;
4793   }
4794
4795   // Check if the base type is a pointer to a member access of a struct
4796   // marked with noderef.
4797   const Expr *Base = E->getBase();
4798   QualType BaseTy = Base->getType();
4799   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4800     // Not a pointer access
4801     return;
4802
4803   const MemberExpr *Member = nullptr;
4804   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4805          Member->isArrow())
4806     Base = Member->getBase();
4807
4808   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4809     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4810       LastRecord.PossibleDerefs.insert(E);
4811   }
4812 }
4813
4814 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4815                                           Expr *LowerBound,
4816                                           SourceLocation ColonLocFirst,
4817                                           SourceLocation ColonLocSecond,
4818                                           Expr *Length, Expr *Stride,
4819                                           SourceLocation RBLoc) {
4820   if (Base->getType()->isPlaceholderType() &&
4821       !Base->getType()->isSpecificPlaceholderType(
4822           BuiltinType::OMPArraySection)) {
4823     ExprResult Result = CheckPlaceholderExpr(Base);
4824     if (Result.isInvalid())
4825       return ExprError();
4826     Base = Result.get();
4827   }
4828   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4829     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4830     if (Result.isInvalid())
4831       return ExprError();
4832     Result = DefaultLvalueConversion(Result.get());
4833     if (Result.isInvalid())
4834       return ExprError();
4835     LowerBound = Result.get();
4836   }
4837   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4838     ExprResult Result = CheckPlaceholderExpr(Length);
4839     if (Result.isInvalid())
4840       return ExprError();
4841     Result = DefaultLvalueConversion(Result.get());
4842     if (Result.isInvalid())
4843       return ExprError();
4844     Length = Result.get();
4845   }
4846   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4847     ExprResult Result = CheckPlaceholderExpr(Stride);
4848     if (Result.isInvalid())
4849       return ExprError();
4850     Result = DefaultLvalueConversion(Result.get());
4851     if (Result.isInvalid())
4852       return ExprError();
4853     Stride = Result.get();
4854   }
4855
4856   // Build an unanalyzed expression if either operand is type-dependent.
4857   if (Base->isTypeDependent() ||
4858       (LowerBound &&
4859        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4860       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4861       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4862     return new (Context) OMPArraySectionExpr(
4863         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4864         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4865   }
4866
4867   // Perform default conversions.
4868   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4869   QualType ResultTy;
4870   if (OriginalTy->isAnyPointerType()) {
4871     ResultTy = OriginalTy->getPointeeType();
4872   } else if (OriginalTy->isArrayType()) {
4873     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4874   } else {
4875     return ExprError(
4876         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4877         << Base->getSourceRange());
4878   }
4879   // C99 6.5.2.1p1
4880   if (LowerBound) {
4881     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4882                                                       LowerBound);
4883     if (Res.isInvalid())
4884       return ExprError(Diag(LowerBound->getExprLoc(),
4885                             diag::err_omp_typecheck_section_not_integer)
4886                        << 0 << LowerBound->getSourceRange());
4887     LowerBound = Res.get();
4888
4889     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4890         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4891       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4892           << 0 << LowerBound->getSourceRange();
4893   }
4894   if (Length) {
4895     auto Res =
4896         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4897     if (Res.isInvalid())
4898       return ExprError(Diag(Length->getExprLoc(),
4899                             diag::err_omp_typecheck_section_not_integer)
4900                        << 1 << Length->getSourceRange());
4901     Length = Res.get();
4902
4903     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4904         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4905       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4906           << 1 << Length->getSourceRange();
4907   }
4908   if (Stride) {
4909     ExprResult Res =
4910         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4911     if (Res.isInvalid())
4912       return ExprError(Diag(Stride->getExprLoc(),
4913                             diag::err_omp_typecheck_section_not_integer)
4914                        << 1 << Stride->getSourceRange());
4915     Stride = Res.get();
4916
4917     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4918         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4919       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4920           << 1 << Stride->getSourceRange();
4921   }
4922
4923   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4924   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4925   // type. Note that functions are not objects, and that (in C99 parlance)
4926   // incomplete types are not object types.
4927   if (ResultTy->isFunctionType()) {
4928     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4929         << ResultTy << Base->getSourceRange();
4930     return ExprError();
4931   }
4932
4933   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4934                           diag::err_omp_section_incomplete_type, Base))
4935     return ExprError();
4936
4937   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4938     Expr::EvalResult Result;
4939     if (LowerBound->EvaluateAsInt(Result, Context)) {
4940       // OpenMP 5.0, [2.1.5 Array Sections]
4941       // The array section must be a subset of the original array.
4942       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4943       if (LowerBoundValue.isNegative()) {
4944         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4945             << LowerBound->getSourceRange();
4946         return ExprError();
4947       }
4948     }
4949   }
4950
4951   if (Length) {
4952     Expr::EvalResult Result;
4953     if (Length->EvaluateAsInt(Result, Context)) {
4954       // OpenMP 5.0, [2.1.5 Array Sections]
4955       // The length must evaluate to non-negative integers.
4956       llvm::APSInt LengthValue = Result.Val.getInt();
4957       if (LengthValue.isNegative()) {
4958         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4959             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4960             << Length->getSourceRange();
4961         return ExprError();
4962       }
4963     }
4964   } else if (ColonLocFirst.isValid() &&
4965              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4966                                       !OriginalTy->isVariableArrayType()))) {
4967     // OpenMP 5.0, [2.1.5 Array Sections]
4968     // When the size of the array dimension is not known, the length must be
4969     // specified explicitly.
4970     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4971         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4972     return ExprError();
4973   }
4974
4975   if (Stride) {
4976     Expr::EvalResult Result;
4977     if (Stride->EvaluateAsInt(Result, Context)) {
4978       // OpenMP 5.0, [2.1.5 Array Sections]
4979       // The stride must evaluate to a positive integer.
4980       llvm::APSInt StrideValue = Result.Val.getInt();
4981       if (!StrideValue.isStrictlyPositive()) {
4982         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4983             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4984             << Stride->getSourceRange();
4985         return ExprError();
4986       }
4987     }
4988   }
4989
4990   if (!Base->getType()->isSpecificPlaceholderType(
4991           BuiltinType::OMPArraySection)) {
4992     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4993     if (Result.isInvalid())
4994       return ExprError();
4995     Base = Result.get();
4996   }
4997   return new (Context) OMPArraySectionExpr(
4998       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4999       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5000 }
5001
5002 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5003                                           SourceLocation RParenLoc,
5004                                           ArrayRef<Expr *> Dims,
5005                                           ArrayRef<SourceRange> Brackets) {
5006   if (Base->getType()->isPlaceholderType()) {
5007     ExprResult Result = CheckPlaceholderExpr(Base);
5008     if (Result.isInvalid())
5009       return ExprError();
5010     Result = DefaultLvalueConversion(Result.get());
5011     if (Result.isInvalid())
5012       return ExprError();
5013     Base = Result.get();
5014   }
5015   QualType BaseTy = Base->getType();
5016   // Delay analysis of the types/expressions if instantiation/specialization is
5017   // required.
5018   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5019     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5020                                        LParenLoc, RParenLoc, Dims, Brackets);
5021   if (!BaseTy->isPointerType() ||
5022       (!Base->isTypeDependent() &&
5023        BaseTy->getPointeeType()->isIncompleteType()))
5024     return ExprError(Diag(Base->getExprLoc(),
5025                           diag::err_omp_non_pointer_type_array_shaping_base)
5026                      << Base->getSourceRange());
5027
5028   SmallVector<Expr *, 4> NewDims;
5029   bool ErrorFound = false;
5030   for (Expr *Dim : Dims) {
5031     if (Dim->getType()->isPlaceholderType()) {
5032       ExprResult Result = CheckPlaceholderExpr(Dim);
5033       if (Result.isInvalid()) {
5034         ErrorFound = true;
5035         continue;
5036       }
5037       Result = DefaultLvalueConversion(Result.get());
5038       if (Result.isInvalid()) {
5039         ErrorFound = true;
5040         continue;
5041       }
5042       Dim = Result.get();
5043     }
5044     if (!Dim->isTypeDependent()) {
5045       ExprResult Result =
5046           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5047       if (Result.isInvalid()) {
5048         ErrorFound = true;
5049         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5050             << Dim->getSourceRange();
5051         continue;
5052       }
5053       Dim = Result.get();
5054       Expr::EvalResult EvResult;
5055       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5056         // OpenMP 5.0, [2.1.4 Array Shaping]
5057         // Each si is an integral type expression that must evaluate to a
5058         // positive integer.
5059         llvm::APSInt Value = EvResult.Val.getInt();
5060         if (!Value.isStrictlyPositive()) {
5061           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5062               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5063               << Dim->getSourceRange();
5064           ErrorFound = true;
5065           continue;
5066         }
5067       }
5068     }
5069     NewDims.push_back(Dim);
5070   }
5071   if (ErrorFound)
5072     return ExprError();
5073   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5074                                      LParenLoc, RParenLoc, NewDims, Brackets);
5075 }
5076
5077 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5078                                       SourceLocation LLoc, SourceLocation RLoc,
5079                                       ArrayRef<OMPIteratorData> Data) {
5080   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5081   bool IsCorrect = true;
5082   for (const OMPIteratorData &D : Data) {
5083     TypeSourceInfo *TInfo = nullptr;
5084     SourceLocation StartLoc;
5085     QualType DeclTy;
5086     if (!D.Type.getAsOpaquePtr()) {
5087       // OpenMP 5.0, 2.1.6 Iterators
5088       // In an iterator-specifier, if the iterator-type is not specified then
5089       // the type of that iterator is of int type.
5090       DeclTy = Context.IntTy;
5091       StartLoc = D.DeclIdentLoc;
5092     } else {
5093       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5094       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5095     }
5096
5097     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5098                              DeclTy->containsUnexpandedParameterPack() ||
5099                              DeclTy->isInstantiationDependentType();
5100     if (!IsDeclTyDependent) {
5101       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5102         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5103         // The iterator-type must be an integral or pointer type.
5104         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5105             << DeclTy;
5106         IsCorrect = false;
5107         continue;
5108       }
5109       if (DeclTy.isConstant(Context)) {
5110         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5111         // The iterator-type must not be const qualified.
5112         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5113             << DeclTy;
5114         IsCorrect = false;
5115         continue;
5116       }
5117     }
5118
5119     // Iterator declaration.
5120     assert(D.DeclIdent && "Identifier expected.");
5121     // Always try to create iterator declarator to avoid extra error messages
5122     // about unknown declarations use.
5123     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5124                                D.DeclIdent, DeclTy, TInfo, SC_None);
5125     VD->setImplicit();
5126     if (S) {
5127       // Check for conflicting previous declaration.
5128       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5129       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5130                             ForVisibleRedeclaration);
5131       Previous.suppressDiagnostics();
5132       LookupName(Previous, S);
5133
5134       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5135                            /*AllowInlineNamespace=*/false);
5136       if (!Previous.empty()) {
5137         NamedDecl *Old = Previous.getRepresentativeDecl();
5138         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5139         Diag(Old->getLocation(), diag::note_previous_definition);
5140       } else {
5141         PushOnScopeChains(VD, S);
5142       }
5143     } else {
5144       CurContext->addDecl(VD);
5145     }
5146     Expr *Begin = D.Range.Begin;
5147     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5148       ExprResult BeginRes =
5149           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5150       Begin = BeginRes.get();
5151     }
5152     Expr *End = D.Range.End;
5153     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5154       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5155       End = EndRes.get();
5156     }
5157     Expr *Step = D.Range.Step;
5158     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5159       if (!Step->getType()->isIntegralType(Context)) {
5160         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5161             << Step << Step->getSourceRange();
5162         IsCorrect = false;
5163         continue;
5164       }
5165       llvm::APSInt Result;
5166       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
5167       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5168       // If the step expression of a range-specification equals zero, the
5169       // behavior is unspecified.
5170       if (IsConstant && Result.isNullValue()) {
5171         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5172             << Step << Step->getSourceRange();
5173         IsCorrect = false;
5174         continue;
5175       }
5176     }
5177     if (!Begin || !End || !IsCorrect) {
5178       IsCorrect = false;
5179       continue;
5180     }
5181     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5182     IDElem.IteratorDecl = VD;
5183     IDElem.AssignmentLoc = D.AssignLoc;
5184     IDElem.Range.Begin = Begin;
5185     IDElem.Range.End = End;
5186     IDElem.Range.Step = Step;
5187     IDElem.ColonLoc = D.ColonLoc;
5188     IDElem.SecondColonLoc = D.SecColonLoc;
5189   }
5190   if (!IsCorrect) {
5191     // Invalidate all created iterator declarations if error is found.
5192     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5193       if (Decl *ID = D.IteratorDecl)
5194         ID->setInvalidDecl();
5195     }
5196     return ExprError();
5197   }
5198   SmallVector<OMPIteratorHelperData, 4> Helpers;
5199   if (!CurContext->isDependentContext()) {
5200     // Build number of ityeration for each iteration range.
5201     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5202     // ((Begini-Stepi-1-Endi) / -Stepi);
5203     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5204       // (Endi - Begini)
5205       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5206                                           D.Range.Begin);
5207       if(!Res.isUsable()) {
5208         IsCorrect = false;
5209         continue;
5210       }
5211       ExprResult St, St1;
5212       if (D.Range.Step) {
5213         St = D.Range.Step;
5214         // (Endi - Begini) + Stepi
5215         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5216         if (!Res.isUsable()) {
5217           IsCorrect = false;
5218           continue;
5219         }
5220         // (Endi - Begini) + Stepi - 1
5221         Res =
5222             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5223                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5224         if (!Res.isUsable()) {
5225           IsCorrect = false;
5226           continue;
5227         }
5228         // ((Endi - Begini) + Stepi - 1) / Stepi
5229         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5230         if (!Res.isUsable()) {
5231           IsCorrect = false;
5232           continue;
5233         }
5234         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5235         // (Begini - Endi)
5236         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5237                                              D.Range.Begin, D.Range.End);
5238         if (!Res1.isUsable()) {
5239           IsCorrect = false;
5240           continue;
5241         }
5242         // (Begini - Endi) - Stepi
5243         Res1 =
5244             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5245         if (!Res1.isUsable()) {
5246           IsCorrect = false;
5247           continue;
5248         }
5249         // (Begini - Endi) - Stepi - 1
5250         Res1 =
5251             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5252                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5253         if (!Res1.isUsable()) {
5254           IsCorrect = false;
5255           continue;
5256         }
5257         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5258         Res1 =
5259             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5260         if (!Res1.isUsable()) {
5261           IsCorrect = false;
5262           continue;
5263         }
5264         // Stepi > 0.
5265         ExprResult CmpRes =
5266             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5267                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5268         if (!CmpRes.isUsable()) {
5269           IsCorrect = false;
5270           continue;
5271         }
5272         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5273                                  Res.get(), Res1.get());
5274         if (!Res.isUsable()) {
5275           IsCorrect = false;
5276           continue;
5277         }
5278       }
5279       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5280       if (!Res.isUsable()) {
5281         IsCorrect = false;
5282         continue;
5283       }
5284
5285       // Build counter update.
5286       // Build counter.
5287       auto *CounterVD =
5288           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5289                           D.IteratorDecl->getBeginLoc(), nullptr,
5290                           Res.get()->getType(), nullptr, SC_None);
5291       CounterVD->setImplicit();
5292       ExprResult RefRes =
5293           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5294                            D.IteratorDecl->getBeginLoc());
5295       // Build counter update.
5296       // I = Begini + counter * Stepi;
5297       ExprResult UpdateRes;
5298       if (D.Range.Step) {
5299         UpdateRes = CreateBuiltinBinOp(
5300             D.AssignmentLoc, BO_Mul,
5301             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5302       } else {
5303         UpdateRes = DefaultLvalueConversion(RefRes.get());
5304       }
5305       if (!UpdateRes.isUsable()) {
5306         IsCorrect = false;
5307         continue;
5308       }
5309       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5310                                      UpdateRes.get());
5311       if (!UpdateRes.isUsable()) {
5312         IsCorrect = false;
5313         continue;
5314       }
5315       ExprResult VDRes =
5316           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5317                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5318                            D.IteratorDecl->getBeginLoc());
5319       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5320                                      UpdateRes.get());
5321       if (!UpdateRes.isUsable()) {
5322         IsCorrect = false;
5323         continue;
5324       }
5325       UpdateRes =
5326           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5327       if (!UpdateRes.isUsable()) {
5328         IsCorrect = false;
5329         continue;
5330       }
5331       ExprResult CounterUpdateRes =
5332           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5333       if (!CounterUpdateRes.isUsable()) {
5334         IsCorrect = false;
5335         continue;
5336       }
5337       CounterUpdateRes =
5338           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5339       if (!CounterUpdateRes.isUsable()) {
5340         IsCorrect = false;
5341         continue;
5342       }
5343       OMPIteratorHelperData &HD = Helpers.emplace_back();
5344       HD.CounterVD = CounterVD;
5345       HD.Upper = Res.get();
5346       HD.Update = UpdateRes.get();
5347       HD.CounterUpdate = CounterUpdateRes.get();
5348     }
5349   } else {
5350     Helpers.assign(ID.size(), {});
5351   }
5352   if (!IsCorrect) {
5353     // Invalidate all created iterator declarations if error is found.
5354     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5355       if (Decl *ID = D.IteratorDecl)
5356         ID->setInvalidDecl();
5357     }
5358     return ExprError();
5359   }
5360   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5361                                  LLoc, RLoc, ID, Helpers);
5362 }
5363
5364 ExprResult
5365 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5366                                       Expr *Idx, SourceLocation RLoc) {
5367   Expr *LHSExp = Base;
5368   Expr *RHSExp = Idx;
5369
5370   ExprValueKind VK = VK_LValue;
5371   ExprObjectKind OK = OK_Ordinary;
5372
5373   // Per C++ core issue 1213, the result is an xvalue if either operand is
5374   // a non-lvalue array, and an lvalue otherwise.
5375   if (getLangOpts().CPlusPlus11) {
5376     for (auto *Op : {LHSExp, RHSExp}) {
5377       Op = Op->IgnoreImplicit();
5378       if (Op->getType()->isArrayType() && !Op->isLValue())
5379         VK = VK_XValue;
5380     }
5381   }
5382
5383   // Perform default conversions.
5384   if (!LHSExp->getType()->getAs<VectorType>()) {
5385     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5386     if (Result.isInvalid())
5387       return ExprError();
5388     LHSExp = Result.get();
5389   }
5390   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5391   if (Result.isInvalid())
5392     return ExprError();
5393   RHSExp = Result.get();
5394
5395   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5396
5397   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5398   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5399   // in the subscript position. As a result, we need to derive the array base
5400   // and index from the expression types.
5401   Expr *BaseExpr, *IndexExpr;
5402   QualType ResultType;
5403   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5404     BaseExpr = LHSExp;
5405     IndexExpr = RHSExp;
5406     ResultType = Context.DependentTy;
5407   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5408     BaseExpr = LHSExp;
5409     IndexExpr = RHSExp;
5410     ResultType = PTy->getPointeeType();
5411   } else if (const ObjCObjectPointerType *PTy =
5412                LHSTy->getAs<ObjCObjectPointerType>()) {
5413     BaseExpr = LHSExp;
5414     IndexExpr = RHSExp;
5415
5416     // Use custom logic if this should be the pseudo-object subscript
5417     // expression.
5418     if (!LangOpts.isSubscriptPointerArithmetic())
5419       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5420                                           nullptr);
5421
5422     ResultType = PTy->getPointeeType();
5423   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5424      // Handle the uncommon case of "123[Ptr]".
5425     BaseExpr = RHSExp;
5426     IndexExpr = LHSExp;
5427     ResultType = PTy->getPointeeType();
5428   } else if (const ObjCObjectPointerType *PTy =
5429                RHSTy->getAs<ObjCObjectPointerType>()) {
5430      // Handle the uncommon case of "123[Ptr]".
5431     BaseExpr = RHSExp;
5432     IndexExpr = LHSExp;
5433     ResultType = PTy->getPointeeType();
5434     if (!LangOpts.isSubscriptPointerArithmetic()) {
5435       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5436         << ResultType << BaseExpr->getSourceRange();
5437       return ExprError();
5438     }
5439   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5440     BaseExpr = LHSExp;    // vectors: V[123]
5441     IndexExpr = RHSExp;
5442     // We apply C++ DR1213 to vector subscripting too.
5443     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5444       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5445       if (Materialized.isInvalid())
5446         return ExprError();
5447       LHSExp = Materialized.get();
5448     }
5449     VK = LHSExp->getValueKind();
5450     if (VK != VK_RValue)
5451       OK = OK_VectorComponent;
5452
5453     ResultType = VTy->getElementType();
5454     QualType BaseType = BaseExpr->getType();
5455     Qualifiers BaseQuals = BaseType.getQualifiers();
5456     Qualifiers MemberQuals = ResultType.getQualifiers();
5457     Qualifiers Combined = BaseQuals + MemberQuals;
5458     if (Combined != MemberQuals)
5459       ResultType = Context.getQualifiedType(ResultType, Combined);
5460   } else if (LHSTy->isArrayType()) {
5461     // If we see an array that wasn't promoted by
5462     // DefaultFunctionArrayLvalueConversion, it must be an array that
5463     // wasn't promoted because of the C90 rule that doesn't
5464     // allow promoting non-lvalue arrays.  Warn, then
5465     // force the promotion here.
5466     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5467         << LHSExp->getSourceRange();
5468     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5469                                CK_ArrayToPointerDecay).get();
5470     LHSTy = LHSExp->getType();
5471
5472     BaseExpr = LHSExp;
5473     IndexExpr = RHSExp;
5474     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5475   } else if (RHSTy->isArrayType()) {
5476     // Same as previous, except for 123[f().a] case
5477     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5478         << RHSExp->getSourceRange();
5479     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5480                                CK_ArrayToPointerDecay).get();
5481     RHSTy = RHSExp->getType();
5482
5483     BaseExpr = RHSExp;
5484     IndexExpr = LHSExp;
5485     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5486   } else {
5487     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5488        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5489   }
5490   // C99 6.5.2.1p1
5491   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5492     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5493                      << IndexExpr->getSourceRange());
5494
5495   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5496        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5497          && !IndexExpr->isTypeDependent())
5498     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5499
5500   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5501   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5502   // type. Note that Functions are not objects, and that (in C99 parlance)
5503   // incomplete types are not object types.
5504   if (ResultType->isFunctionType()) {
5505     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5506         << ResultType << BaseExpr->getSourceRange();
5507     return ExprError();
5508   }
5509
5510   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5511     // GNU extension: subscripting on pointer to void
5512     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5513       << BaseExpr->getSourceRange();
5514
5515     // C forbids expressions of unqualified void type from being l-values.
5516     // See IsCForbiddenLValueType.
5517     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5518   } else if (!ResultType->isDependentType() &&
5519              RequireCompleteSizedType(
5520                  LLoc, ResultType,
5521                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5522     return ExprError();
5523
5524   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5525          !ResultType.isCForbiddenLValueType());
5526
5527   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5528       FunctionScopes.size() > 1) {
5529     if (auto *TT =
5530             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5531       for (auto I = FunctionScopes.rbegin(),
5532                 E = std::prev(FunctionScopes.rend());
5533            I != E; ++I) {
5534         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5535         if (CSI == nullptr)
5536           break;
5537         DeclContext *DC = nullptr;
5538         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5539           DC = LSI->CallOperator;
5540         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5541           DC = CRSI->TheCapturedDecl;
5542         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5543           DC = BSI->TheDecl;
5544         if (DC) {
5545           if (DC->containsDecl(TT->getDecl()))
5546             break;
5547           captureVariablyModifiedType(
5548               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5549         }
5550       }
5551     }
5552   }
5553
5554   return new (Context)
5555       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5556 }
5557
5558 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5559                                   ParmVarDecl *Param) {
5560   if (Param->hasUnparsedDefaultArg()) {
5561     // If we've already cleared out the location for the default argument,
5562     // that means we're parsing it right now.
5563     if (!UnparsedDefaultArgLocs.count(Param)) {
5564       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5565       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5566       Param->setInvalidDecl();
5567       return true;
5568     }
5569
5570     Diag(CallLoc,
5571          diag::err_use_of_default_argument_to_function_declared_later) <<
5572       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5573     Diag(UnparsedDefaultArgLocs[Param],
5574          diag::note_default_argument_declared_here);
5575     return true;
5576   }
5577
5578   if (Param->hasUninstantiatedDefaultArg() &&
5579       InstantiateDefaultArgument(CallLoc, FD, Param))
5580     return true;
5581
5582   assert(Param->hasInit() && "default argument but no initializer?");
5583
5584   // If the default expression creates temporaries, we need to
5585   // push them to the current stack of expression temporaries so they'll
5586   // be properly destroyed.
5587   // FIXME: We should really be rebuilding the default argument with new
5588   // bound temporaries; see the comment in PR5810.
5589   // We don't need to do that with block decls, though, because
5590   // blocks in default argument expression can never capture anything.
5591   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5592     // Set the "needs cleanups" bit regardless of whether there are
5593     // any explicit objects.
5594     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5595
5596     // Append all the objects to the cleanup list.  Right now, this
5597     // should always be a no-op, because blocks in default argument
5598     // expressions should never be able to capture anything.
5599     assert(!Init->getNumObjects() &&
5600            "default argument expression has capturing blocks?");
5601   }
5602
5603   // We already type-checked the argument, so we know it works.
5604   // Just mark all of the declarations in this potentially-evaluated expression
5605   // as being "referenced".
5606   EnterExpressionEvaluationContext EvalContext(
5607       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5608   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5609                                    /*SkipLocalVariables=*/true);
5610   return false;
5611 }
5612
5613 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5614                                         FunctionDecl *FD, ParmVarDecl *Param) {
5615   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5616   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5617     return ExprError();
5618   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5619 }
5620
5621 Sema::VariadicCallType
5622 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5623                           Expr *Fn) {
5624   if (Proto && Proto->isVariadic()) {
5625     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5626       return VariadicConstructor;
5627     else if (Fn && Fn->getType()->isBlockPointerType())
5628       return VariadicBlock;
5629     else if (FDecl) {
5630       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5631         if (Method->isInstance())
5632           return VariadicMethod;
5633     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5634       return VariadicMethod;
5635     return VariadicFunction;
5636   }
5637   return VariadicDoesNotApply;
5638 }
5639
5640 namespace {
5641 class FunctionCallCCC final : public FunctionCallFilterCCC {
5642 public:
5643   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5644                   unsigned NumArgs, MemberExpr *ME)
5645       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5646         FunctionName(FuncName) {}
5647
5648   bool ValidateCandidate(const TypoCorrection &candidate) override {
5649     if (!candidate.getCorrectionSpecifier() ||
5650         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5651       return false;
5652     }
5653
5654     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5655   }
5656
5657   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5658     return std::make_unique<FunctionCallCCC>(*this);
5659   }
5660
5661 private:
5662   const IdentifierInfo *const FunctionName;
5663 };
5664 }
5665
5666 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5667                                                FunctionDecl *FDecl,
5668                                                ArrayRef<Expr *> Args) {
5669   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5670   DeclarationName FuncName = FDecl->getDeclName();
5671   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5672
5673   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5674   if (TypoCorrection Corrected = S.CorrectTypo(
5675           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5676           S.getScopeForContext(S.CurContext), nullptr, CCC,
5677           Sema::CTK_ErrorRecovery)) {
5678     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5679       if (Corrected.isOverloaded()) {
5680         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5681         OverloadCandidateSet::iterator Best;
5682         for (NamedDecl *CD : Corrected) {
5683           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5684             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5685                                    OCS);
5686         }
5687         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5688         case OR_Success:
5689           ND = Best->FoundDecl;
5690           Corrected.setCorrectionDecl(ND);
5691           break;
5692         default:
5693           break;
5694         }
5695       }
5696       ND = ND->getUnderlyingDecl();
5697       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5698         return Corrected;
5699     }
5700   }
5701   return TypoCorrection();
5702 }
5703
5704 /// ConvertArgumentsForCall - Converts the arguments specified in
5705 /// Args/NumArgs to the parameter types of the function FDecl with
5706 /// function prototype Proto. Call is the call expression itself, and
5707 /// Fn is the function expression. For a C++ member function, this
5708 /// routine does not attempt to convert the object argument. Returns
5709 /// true if the call is ill-formed.
5710 bool
5711 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5712                               FunctionDecl *FDecl,
5713                               const FunctionProtoType *Proto,
5714                               ArrayRef<Expr *> Args,
5715                               SourceLocation RParenLoc,
5716                               bool IsExecConfig) {
5717   // Bail out early if calling a builtin with custom typechecking.
5718   if (FDecl)
5719     if (unsigned ID = FDecl->getBuiltinID())
5720       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5721         return false;
5722
5723   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5724   // assignment, to the types of the corresponding parameter, ...
5725   unsigned NumParams = Proto->getNumParams();
5726   bool Invalid = false;
5727   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5728   unsigned FnKind = Fn->getType()->isBlockPointerType()
5729                        ? 1 /* block */
5730                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5731                                        : 0 /* function */);
5732
5733   // If too few arguments are available (and we don't have default
5734   // arguments for the remaining parameters), don't make the call.
5735   if (Args.size() < NumParams) {
5736     if (Args.size() < MinArgs) {
5737       TypoCorrection TC;
5738       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5739         unsigned diag_id =
5740             MinArgs == NumParams && !Proto->isVariadic()
5741                 ? diag::err_typecheck_call_too_few_args_suggest
5742                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5743         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5744                                         << static_cast<unsigned>(Args.size())
5745                                         << TC.getCorrectionRange());
5746       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5747         Diag(RParenLoc,
5748              MinArgs == NumParams && !Proto->isVariadic()
5749                  ? diag::err_typecheck_call_too_few_args_one
5750                  : diag::err_typecheck_call_too_few_args_at_least_one)
5751             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5752       else
5753         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5754                             ? diag::err_typecheck_call_too_few_args
5755                             : diag::err_typecheck_call_too_few_args_at_least)
5756             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5757             << Fn->getSourceRange();
5758
5759       // Emit the location of the prototype.
5760       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5761         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5762
5763       return true;
5764     }
5765     // We reserve space for the default arguments when we create
5766     // the call expression, before calling ConvertArgumentsForCall.
5767     assert((Call->getNumArgs() == NumParams) &&
5768            "We should have reserved space for the default arguments before!");
5769   }
5770
5771   // If too many are passed and not variadic, error on the extras and drop
5772   // them.
5773   if (Args.size() > NumParams) {
5774     if (!Proto->isVariadic()) {
5775       TypoCorrection TC;
5776       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5777         unsigned diag_id =
5778             MinArgs == NumParams && !Proto->isVariadic()
5779                 ? diag::err_typecheck_call_too_many_args_suggest
5780                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5781         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5782                                         << static_cast<unsigned>(Args.size())
5783                                         << TC.getCorrectionRange());
5784       } else if (NumParams == 1 && FDecl &&
5785                  FDecl->getParamDecl(0)->getDeclName())
5786         Diag(Args[NumParams]->getBeginLoc(),
5787              MinArgs == NumParams
5788                  ? diag::err_typecheck_call_too_many_args_one
5789                  : diag::err_typecheck_call_too_many_args_at_most_one)
5790             << FnKind << FDecl->getParamDecl(0)
5791             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5792             << SourceRange(Args[NumParams]->getBeginLoc(),
5793                            Args.back()->getEndLoc());
5794       else
5795         Diag(Args[NumParams]->getBeginLoc(),
5796              MinArgs == NumParams
5797                  ? diag::err_typecheck_call_too_many_args
5798                  : diag::err_typecheck_call_too_many_args_at_most)
5799             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5800             << Fn->getSourceRange()
5801             << SourceRange(Args[NumParams]->getBeginLoc(),
5802                            Args.back()->getEndLoc());
5803
5804       // Emit the location of the prototype.
5805       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5806         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5807
5808       // This deletes the extra arguments.
5809       Call->shrinkNumArgs(NumParams);
5810       return true;
5811     }
5812   }
5813   SmallVector<Expr *, 8> AllArgs;
5814   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5815
5816   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5817                                    AllArgs, CallType);
5818   if (Invalid)
5819     return true;
5820   unsigned TotalNumArgs = AllArgs.size();
5821   for (unsigned i = 0; i < TotalNumArgs; ++i)
5822     Call->setArg(i, AllArgs[i]);
5823
5824   return false;
5825 }
5826
5827 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5828                                   const FunctionProtoType *Proto,
5829                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5830                                   SmallVectorImpl<Expr *> &AllArgs,
5831                                   VariadicCallType CallType, bool AllowExplicit,
5832                                   bool IsListInitialization) {
5833   unsigned NumParams = Proto->getNumParams();
5834   bool Invalid = false;
5835   size_t ArgIx = 0;
5836   // Continue to check argument types (even if we have too few/many args).
5837   for (unsigned i = FirstParam; i < NumParams; i++) {
5838     QualType ProtoArgType = Proto->getParamType(i);
5839
5840     Expr *Arg;
5841     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5842     if (ArgIx < Args.size()) {
5843       Arg = Args[ArgIx++];
5844
5845       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5846                               diag::err_call_incomplete_argument, Arg))
5847         return true;
5848
5849       // Strip the unbridged-cast placeholder expression off, if applicable.
5850       bool CFAudited = false;
5851       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5852           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5853           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5854         Arg = stripARCUnbridgedCast(Arg);
5855       else if (getLangOpts().ObjCAutoRefCount &&
5856                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5857                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5858         CFAudited = true;
5859
5860       if (Proto->getExtParameterInfo(i).isNoEscape())
5861         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5862           BE->getBlockDecl()->setDoesNotEscape();
5863
5864       InitializedEntity Entity =
5865           Param ? InitializedEntity::InitializeParameter(Context, Param,
5866                                                          ProtoArgType)
5867                 : InitializedEntity::InitializeParameter(
5868                       Context, ProtoArgType, Proto->isParamConsumed(i));
5869
5870       // Remember that parameter belongs to a CF audited API.
5871       if (CFAudited)
5872         Entity.setParameterCFAudited();
5873
5874       ExprResult ArgE = PerformCopyInitialization(
5875           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5876       if (ArgE.isInvalid())
5877         return true;
5878
5879       Arg = ArgE.getAs<Expr>();
5880     } else {
5881       assert(Param && "can't use default arguments without a known callee");
5882
5883       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5884       if (ArgExpr.isInvalid())
5885         return true;
5886
5887       Arg = ArgExpr.getAs<Expr>();
5888     }
5889
5890     // Check for array bounds violations for each argument to the call. This
5891     // check only triggers warnings when the argument isn't a more complex Expr
5892     // with its own checking, such as a BinaryOperator.
5893     CheckArrayAccess(Arg);
5894
5895     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5896     CheckStaticArrayArgument(CallLoc, Param, Arg);
5897
5898     AllArgs.push_back(Arg);
5899   }
5900
5901   // If this is a variadic call, handle args passed through "...".
5902   if (CallType != VariadicDoesNotApply) {
5903     // Assume that extern "C" functions with variadic arguments that
5904     // return __unknown_anytype aren't *really* variadic.
5905     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5906         FDecl->isExternC()) {
5907       for (Expr *A : Args.slice(ArgIx)) {
5908         QualType paramType; // ignored
5909         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5910         Invalid |= arg.isInvalid();
5911         AllArgs.push_back(arg.get());
5912       }
5913
5914     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5915     } else {
5916       for (Expr *A : Args.slice(ArgIx)) {
5917         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5918         Invalid |= Arg.isInvalid();
5919         AllArgs.push_back(Arg.get());
5920       }
5921     }
5922
5923     // Check for array bounds violations.
5924     for (Expr *A : Args.slice(ArgIx))
5925       CheckArrayAccess(A);
5926   }
5927   return Invalid;
5928 }
5929
5930 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5931   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5932   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5933     TL = DTL.getOriginalLoc();
5934   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5935     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5936       << ATL.getLocalSourceRange();
5937 }
5938
5939 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5940 /// array parameter, check that it is non-null, and that if it is formed by
5941 /// array-to-pointer decay, the underlying array is sufficiently large.
5942 ///
5943 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5944 /// array type derivation, then for each call to the function, the value of the
5945 /// corresponding actual argument shall provide access to the first element of
5946 /// an array with at least as many elements as specified by the size expression.
5947 void
5948 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5949                                ParmVarDecl *Param,
5950                                const Expr *ArgExpr) {
5951   // Static array parameters are not supported in C++.
5952   if (!Param || getLangOpts().CPlusPlus)
5953     return;
5954
5955   QualType OrigTy = Param->getOriginalType();
5956
5957   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5958   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5959     return;
5960
5961   if (ArgExpr->isNullPointerConstant(Context,
5962                                      Expr::NPC_NeverValueDependent)) {
5963     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5964     DiagnoseCalleeStaticArrayParam(*this, Param);
5965     return;
5966   }
5967
5968   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5969   if (!CAT)
5970     return;
5971
5972   const ConstantArrayType *ArgCAT =
5973     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5974   if (!ArgCAT)
5975     return;
5976
5977   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5978                                              ArgCAT->getElementType())) {
5979     if (ArgCAT->getSize().ult(CAT->getSize())) {
5980       Diag(CallLoc, diag::warn_static_array_too_small)
5981           << ArgExpr->getSourceRange()
5982           << (unsigned)ArgCAT->getSize().getZExtValue()
5983           << (unsigned)CAT->getSize().getZExtValue() << 0;
5984       DiagnoseCalleeStaticArrayParam(*this, Param);
5985     }
5986     return;
5987   }
5988
5989   Optional<CharUnits> ArgSize =
5990       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5991   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5992   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5993     Diag(CallLoc, diag::warn_static_array_too_small)
5994         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5995         << (unsigned)ParmSize->getQuantity() << 1;
5996     DiagnoseCalleeStaticArrayParam(*this, Param);
5997   }
5998 }
5999
6000 /// Given a function expression of unknown-any type, try to rebuild it
6001 /// to have a function type.
6002 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6003
6004 /// Is the given type a placeholder that we need to lower out
6005 /// immediately during argument processing?
6006 static bool isPlaceholderToRemoveAsArg(QualType type) {
6007   // Placeholders are never sugared.
6008   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6009   if (!placeholder) return false;
6010
6011   switch (placeholder->getKind()) {
6012   // Ignore all the non-placeholder types.
6013 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6014   case BuiltinType::Id:
6015 #include "clang/Basic/OpenCLImageTypes.def"
6016 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6017   case BuiltinType::Id:
6018 #include "clang/Basic/OpenCLExtensionTypes.def"
6019   // In practice we'll never use this, since all SVE types are sugared
6020   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6021 #define SVE_TYPE(Name, Id, SingletonId) \
6022   case BuiltinType::Id:
6023 #include "clang/Basic/AArch64SVEACLETypes.def"
6024 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6025 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6026 #include "clang/AST/BuiltinTypes.def"
6027     return false;
6028
6029   // We cannot lower out overload sets; they might validly be resolved
6030   // by the call machinery.
6031   case BuiltinType::Overload:
6032     return false;
6033
6034   // Unbridged casts in ARC can be handled in some call positions and
6035   // should be left in place.
6036   case BuiltinType::ARCUnbridgedCast:
6037     return false;
6038
6039   // Pseudo-objects should be converted as soon as possible.
6040   case BuiltinType::PseudoObject:
6041     return true;
6042
6043   // The debugger mode could theoretically but currently does not try
6044   // to resolve unknown-typed arguments based on known parameter types.
6045   case BuiltinType::UnknownAny:
6046     return true;
6047
6048   // These are always invalid as call arguments and should be reported.
6049   case BuiltinType::BoundMember:
6050   case BuiltinType::BuiltinFn:
6051   case BuiltinType::IncompleteMatrixIdx:
6052   case BuiltinType::OMPArraySection:
6053   case BuiltinType::OMPArrayShaping:
6054   case BuiltinType::OMPIterator:
6055     return true;
6056
6057   }
6058   llvm_unreachable("bad builtin type kind");
6059 }
6060
6061 /// Check an argument list for placeholders that we won't try to
6062 /// handle later.
6063 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6064   // Apply this processing to all the arguments at once instead of
6065   // dying at the first failure.
6066   bool hasInvalid = false;
6067   for (size_t i = 0, e = args.size(); i != e; i++) {
6068     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6069       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6070       if (result.isInvalid()) hasInvalid = true;
6071       else args[i] = result.get();
6072     } else if (hasInvalid) {
6073       (void)S.CorrectDelayedTyposInExpr(args[i]);
6074     }
6075   }
6076   return hasInvalid;
6077 }
6078
6079 /// If a builtin function has a pointer argument with no explicit address
6080 /// space, then it should be able to accept a pointer to any address
6081 /// space as input.  In order to do this, we need to replace the
6082 /// standard builtin declaration with one that uses the same address space
6083 /// as the call.
6084 ///
6085 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6086 ///                  it does not contain any pointer arguments without
6087 ///                  an address space qualifer.  Otherwise the rewritten
6088 ///                  FunctionDecl is returned.
6089 /// TODO: Handle pointer return types.
6090 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6091                                                 FunctionDecl *FDecl,
6092                                                 MultiExprArg ArgExprs) {
6093
6094   QualType DeclType = FDecl->getType();
6095   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6096
6097   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6098       ArgExprs.size() < FT->getNumParams())
6099     return nullptr;
6100
6101   bool NeedsNewDecl = false;
6102   unsigned i = 0;
6103   SmallVector<QualType, 8> OverloadParams;
6104
6105   for (QualType ParamType : FT->param_types()) {
6106
6107     // Convert array arguments to pointer to simplify type lookup.
6108     ExprResult ArgRes =
6109         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6110     if (ArgRes.isInvalid())
6111       return nullptr;
6112     Expr *Arg = ArgRes.get();
6113     QualType ArgType = Arg->getType();
6114     if (!ParamType->isPointerType() ||
6115         ParamType.hasAddressSpace() ||
6116         !ArgType->isPointerType() ||
6117         !ArgType->getPointeeType().hasAddressSpace()) {
6118       OverloadParams.push_back(ParamType);
6119       continue;
6120     }
6121
6122     QualType PointeeType = ParamType->getPointeeType();
6123     if (PointeeType.hasAddressSpace())
6124       continue;
6125
6126     NeedsNewDecl = true;
6127     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6128
6129     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6130     OverloadParams.push_back(Context.getPointerType(PointeeType));
6131   }
6132
6133   if (!NeedsNewDecl)
6134     return nullptr;
6135
6136   FunctionProtoType::ExtProtoInfo EPI;
6137   EPI.Variadic = FT->isVariadic();
6138   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6139                                                 OverloadParams, EPI);
6140   DeclContext *Parent = FDecl->getParent();
6141   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6142                                                     FDecl->getLocation(),
6143                                                     FDecl->getLocation(),
6144                                                     FDecl->getIdentifier(),
6145                                                     OverloadTy,
6146                                                     /*TInfo=*/nullptr,
6147                                                     SC_Extern, false,
6148                                                     /*hasPrototype=*/true);
6149   SmallVector<ParmVarDecl*, 16> Params;
6150   FT = cast<FunctionProtoType>(OverloadTy);
6151   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6152     QualType ParamType = FT->getParamType(i);
6153     ParmVarDecl *Parm =
6154         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6155                                 SourceLocation(), nullptr, ParamType,
6156                                 /*TInfo=*/nullptr, SC_None, nullptr);
6157     Parm->setScopeInfo(0, i);
6158     Params.push_back(Parm);
6159   }
6160   OverloadDecl->setParams(Params);
6161   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6162   return OverloadDecl;
6163 }
6164
6165 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6166                                     FunctionDecl *Callee,
6167                                     MultiExprArg ArgExprs) {
6168   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6169   // similar attributes) really don't like it when functions are called with an
6170   // invalid number of args.
6171   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6172                          /*PartialOverloading=*/false) &&
6173       !Callee->isVariadic())
6174     return;
6175   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6176     return;
6177
6178   if (const EnableIfAttr *Attr =
6179           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6180     S.Diag(Fn->getBeginLoc(),
6181            isa<CXXMethodDecl>(Callee)
6182                ? diag::err_ovl_no_viable_member_function_in_call
6183                : diag::err_ovl_no_viable_function_in_call)
6184         << Callee << Callee->getSourceRange();
6185     S.Diag(Callee->getLocation(),
6186            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6187         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6188     return;
6189   }
6190 }
6191
6192 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6193     const UnresolvedMemberExpr *const UME, Sema &S) {
6194
6195   const auto GetFunctionLevelDCIfCXXClass =
6196       [](Sema &S) -> const CXXRecordDecl * {
6197     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6198     if (!DC || !DC->getParent())
6199       return nullptr;
6200
6201     // If the call to some member function was made from within a member
6202     // function body 'M' return return 'M's parent.
6203     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6204       return MD->getParent()->getCanonicalDecl();
6205     // else the call was made from within a default member initializer of a
6206     // class, so return the class.
6207     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6208       return RD->getCanonicalDecl();
6209     return nullptr;
6210   };
6211   // If our DeclContext is neither a member function nor a class (in the
6212   // case of a lambda in a default member initializer), we can't have an
6213   // enclosing 'this'.
6214
6215   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6216   if (!CurParentClass)
6217     return false;
6218
6219   // The naming class for implicit member functions call is the class in which
6220   // name lookup starts.
6221   const CXXRecordDecl *const NamingClass =
6222       UME->getNamingClass()->getCanonicalDecl();
6223   assert(NamingClass && "Must have naming class even for implicit access");
6224
6225   // If the unresolved member functions were found in a 'naming class' that is
6226   // related (either the same or derived from) to the class that contains the
6227   // member function that itself contained the implicit member access.
6228
6229   return CurParentClass == NamingClass ||
6230          CurParentClass->isDerivedFrom(NamingClass);
6231 }
6232
6233 static void
6234 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6235     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6236
6237   if (!UME)
6238     return;
6239
6240   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6241   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6242   // already been captured, or if this is an implicit member function call (if
6243   // it isn't, an attempt to capture 'this' should already have been made).
6244   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6245       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6246     return;
6247
6248   // Check if the naming class in which the unresolved members were found is
6249   // related (same as or is a base of) to the enclosing class.
6250
6251   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6252     return;
6253
6254
6255   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6256   // If the enclosing function is not dependent, then this lambda is
6257   // capture ready, so if we can capture this, do so.
6258   if (!EnclosingFunctionCtx->isDependentContext()) {
6259     // If the current lambda and all enclosing lambdas can capture 'this' -
6260     // then go ahead and capture 'this' (since our unresolved overload set
6261     // contains at least one non-static member function).
6262     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6263       S.CheckCXXThisCapture(CallLoc);
6264   } else if (S.CurContext->isDependentContext()) {
6265     // ... since this is an implicit member reference, that might potentially
6266     // involve a 'this' capture, mark 'this' for potential capture in
6267     // enclosing lambdas.
6268     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6269       CurLSI->addPotentialThisCapture(CallLoc);
6270   }
6271 }
6272
6273 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6274                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6275                                Expr *ExecConfig) {
6276   ExprResult Call =
6277       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6278   if (Call.isInvalid())
6279     return Call;
6280
6281   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6282   // language modes.
6283   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6284     if (ULE->hasExplicitTemplateArgs() &&
6285         ULE->decls_begin() == ULE->decls_end()) {
6286       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6287                                  ? diag::warn_cxx17_compat_adl_only_template_id
6288                                  : diag::ext_adl_only_template_id)
6289           << ULE->getName();
6290     }
6291   }
6292
6293   if (LangOpts.OpenMP)
6294     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6295                            ExecConfig);
6296
6297   return Call;
6298 }
6299
6300 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6301 /// This provides the location of the left/right parens and a list of comma
6302 /// locations.
6303 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6304                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6305                                Expr *ExecConfig, bool IsExecConfig) {
6306   // Since this might be a postfix expression, get rid of ParenListExprs.
6307   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6308   if (Result.isInvalid()) return ExprError();
6309   Fn = Result.get();
6310
6311   if (checkArgsForPlaceholders(*this, ArgExprs))
6312     return ExprError();
6313
6314   if (getLangOpts().CPlusPlus) {
6315     // If this is a pseudo-destructor expression, build the call immediately.
6316     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6317       if (!ArgExprs.empty()) {
6318         // Pseudo-destructor calls should not have any arguments.
6319         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6320             << FixItHint::CreateRemoval(
6321                    SourceRange(ArgExprs.front()->getBeginLoc(),
6322                                ArgExprs.back()->getEndLoc()));
6323       }
6324
6325       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6326                               VK_RValue, RParenLoc);
6327     }
6328     if (Fn->getType() == Context.PseudoObjectTy) {
6329       ExprResult result = CheckPlaceholderExpr(Fn);
6330       if (result.isInvalid()) return ExprError();
6331       Fn = result.get();
6332     }
6333
6334     // Determine whether this is a dependent call inside a C++ template,
6335     // in which case we won't do any semantic analysis now.
6336     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6337       if (ExecConfig) {
6338         return CUDAKernelCallExpr::Create(
6339             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6340             Context.DependentTy, VK_RValue, RParenLoc);
6341       } else {
6342
6343         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6344             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6345             Fn->getBeginLoc());
6346
6347         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6348                                 VK_RValue, RParenLoc);
6349       }
6350     }
6351
6352     // Determine whether this is a call to an object (C++ [over.call.object]).
6353     if (Fn->getType()->isRecordType())
6354       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6355                                           RParenLoc);
6356
6357     if (Fn->getType() == Context.UnknownAnyTy) {
6358       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6359       if (result.isInvalid()) return ExprError();
6360       Fn = result.get();
6361     }
6362
6363     if (Fn->getType() == Context.BoundMemberTy) {
6364       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6365                                        RParenLoc);
6366     }
6367   }
6368
6369   // Check for overloaded calls.  This can happen even in C due to extensions.
6370   if (Fn->getType() == Context.OverloadTy) {
6371     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6372
6373     // We aren't supposed to apply this logic if there's an '&' involved.
6374     if (!find.HasFormOfMemberPointer) {
6375       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6376         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6377                                 VK_RValue, RParenLoc);
6378       OverloadExpr *ovl = find.Expression;
6379       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6380         return BuildOverloadedCallExpr(
6381             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6382             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6383       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6384                                        RParenLoc);
6385     }
6386   }
6387
6388   // If we're directly calling a function, get the appropriate declaration.
6389   if (Fn->getType() == Context.UnknownAnyTy) {
6390     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6391     if (result.isInvalid()) return ExprError();
6392     Fn = result.get();
6393   }
6394
6395   Expr *NakedFn = Fn->IgnoreParens();
6396
6397   bool CallingNDeclIndirectly = false;
6398   NamedDecl *NDecl = nullptr;
6399   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6400     if (UnOp->getOpcode() == UO_AddrOf) {
6401       CallingNDeclIndirectly = true;
6402       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6403     }
6404   }
6405
6406   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6407     NDecl = DRE->getDecl();
6408
6409     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6410     if (FDecl && FDecl->getBuiltinID()) {
6411       // Rewrite the function decl for this builtin by replacing parameters
6412       // with no explicit address space with the address space of the arguments
6413       // in ArgExprs.
6414       if ((FDecl =
6415                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6416         NDecl = FDecl;
6417         Fn = DeclRefExpr::Create(
6418             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6419             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6420             nullptr, DRE->isNonOdrUse());
6421       }
6422     }
6423   } else if (isa<MemberExpr>(NakedFn))
6424     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6425
6426   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6427     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6428                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6429       return ExprError();
6430
6431     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6432       return ExprError();
6433
6434     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6435   }
6436
6437   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6438                                ExecConfig, IsExecConfig);
6439 }
6440
6441 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6442 ///
6443 /// __builtin_astype( value, dst type )
6444 ///
6445 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6446                                  SourceLocation BuiltinLoc,
6447                                  SourceLocation RParenLoc) {
6448   ExprValueKind VK = VK_RValue;
6449   ExprObjectKind OK = OK_Ordinary;
6450   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6451   QualType SrcTy = E->getType();
6452   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6453     return ExprError(Diag(BuiltinLoc,
6454                           diag::err_invalid_astype_of_different_size)
6455                      << DstTy
6456                      << SrcTy
6457                      << E->getSourceRange());
6458   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6459 }
6460
6461 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6462 /// provided arguments.
6463 ///
6464 /// __builtin_convertvector( value, dst type )
6465 ///
6466 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6467                                         SourceLocation BuiltinLoc,
6468                                         SourceLocation RParenLoc) {
6469   TypeSourceInfo *TInfo;
6470   GetTypeFromParser(ParsedDestTy, &TInfo);
6471   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6472 }
6473
6474 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6475 /// i.e. an expression not of \p OverloadTy.  The expression should
6476 /// unary-convert to an expression of function-pointer or
6477 /// block-pointer type.
6478 ///
6479 /// \param NDecl the declaration being called, if available
6480 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6481                                        SourceLocation LParenLoc,
6482                                        ArrayRef<Expr *> Args,
6483                                        SourceLocation RParenLoc, Expr *Config,
6484                                        bool IsExecConfig, ADLCallKind UsesADL) {
6485   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6486   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6487
6488   // Functions with 'interrupt' attribute cannot be called directly.
6489   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6490     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6491     return ExprError();
6492   }
6493
6494   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6495   // so there's some risk when calling out to non-interrupt handler functions
6496   // that the callee might not preserve them. This is easy to diagnose here,
6497   // but can be very challenging to debug.
6498   if (auto *Caller = getCurFunctionDecl())
6499     if (Caller->hasAttr<ARMInterruptAttr>()) {
6500       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6501       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6502         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6503     }
6504
6505   // Promote the function operand.
6506   // We special-case function promotion here because we only allow promoting
6507   // builtin functions to function pointers in the callee of a call.
6508   ExprResult Result;
6509   QualType ResultTy;
6510   if (BuiltinID &&
6511       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6512     // Extract the return type from the (builtin) function pointer type.
6513     // FIXME Several builtins still have setType in
6514     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6515     // Builtins.def to ensure they are correct before removing setType calls.
6516     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6517     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6518     ResultTy = FDecl->getCallResultType();
6519   } else {
6520     Result = CallExprUnaryConversions(Fn);
6521     ResultTy = Context.BoolTy;
6522   }
6523   if (Result.isInvalid())
6524     return ExprError();
6525   Fn = Result.get();
6526
6527   // Check for a valid function type, but only if it is not a builtin which
6528   // requires custom type checking. These will be handled by
6529   // CheckBuiltinFunctionCall below just after creation of the call expression.
6530   const FunctionType *FuncT = nullptr;
6531   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6532   retry:
6533     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6534       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6535       // have type pointer to function".
6536       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6537       if (!FuncT)
6538         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6539                          << Fn->getType() << Fn->getSourceRange());
6540     } else if (const BlockPointerType *BPT =
6541                    Fn->getType()->getAs<BlockPointerType>()) {
6542       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6543     } else {
6544       // Handle calls to expressions of unknown-any type.
6545       if (Fn->getType() == Context.UnknownAnyTy) {
6546         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6547         if (rewrite.isInvalid())
6548           return ExprError();
6549         Fn = rewrite.get();
6550         goto retry;
6551       }
6552
6553       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6554                        << Fn->getType() << Fn->getSourceRange());
6555     }
6556   }
6557
6558   // Get the number of parameters in the function prototype, if any.
6559   // We will allocate space for max(Args.size(), NumParams) arguments
6560   // in the call expression.
6561   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6562   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6563
6564   CallExpr *TheCall;
6565   if (Config) {
6566     assert(UsesADL == ADLCallKind::NotADL &&
6567            "CUDAKernelCallExpr should not use ADL");
6568     TheCall =
6569         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6570                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6571   } else {
6572     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6573                                RParenLoc, NumParams, UsesADL);
6574   }
6575
6576   if (!getLangOpts().CPlusPlus) {
6577     // Forget about the nulled arguments since typo correction
6578     // do not handle them well.
6579     TheCall->shrinkNumArgs(Args.size());
6580     // C cannot always handle TypoExpr nodes in builtin calls and direct
6581     // function calls as their argument checking don't necessarily handle
6582     // dependent types properly, so make sure any TypoExprs have been
6583     // dealt with.
6584     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6585     if (!Result.isUsable()) return ExprError();
6586     CallExpr *TheOldCall = TheCall;
6587     TheCall = dyn_cast<CallExpr>(Result.get());
6588     bool CorrectedTypos = TheCall != TheOldCall;
6589     if (!TheCall) return Result;
6590     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6591
6592     // A new call expression node was created if some typos were corrected.
6593     // However it may not have been constructed with enough storage. In this
6594     // case, rebuild the node with enough storage. The waste of space is
6595     // immaterial since this only happens when some typos were corrected.
6596     if (CorrectedTypos && Args.size() < NumParams) {
6597       if (Config)
6598         TheCall = CUDAKernelCallExpr::Create(
6599             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6600             RParenLoc, NumParams);
6601       else
6602         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6603                                    RParenLoc, NumParams, UsesADL);
6604     }
6605     // We can now handle the nulled arguments for the default arguments.
6606     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6607   }
6608
6609   // Bail out early if calling a builtin with custom type checking.
6610   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6611     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6612
6613   if (getLangOpts().CUDA) {
6614     if (Config) {
6615       // CUDA: Kernel calls must be to global functions
6616       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6617         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6618             << FDecl << Fn->getSourceRange());
6619
6620       // CUDA: Kernel function must have 'void' return type
6621       if (!FuncT->getReturnType()->isVoidType() &&
6622           !FuncT->getReturnType()->getAs<AutoType>() &&
6623           !FuncT->getReturnType()->isInstantiationDependentType())
6624         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6625             << Fn->getType() << Fn->getSourceRange());
6626     } else {
6627       // CUDA: Calls to global functions must be configured
6628       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6629         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6630             << FDecl << Fn->getSourceRange());
6631     }
6632   }
6633
6634   // Check for a valid return type
6635   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6636                           FDecl))
6637     return ExprError();
6638
6639   // We know the result type of the call, set it.
6640   TheCall->setType(FuncT->getCallResultType(Context));
6641   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6642
6643   if (Proto) {
6644     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6645                                 IsExecConfig))
6646       return ExprError();
6647   } else {
6648     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6649
6650     if (FDecl) {
6651       // Check if we have too few/too many template arguments, based
6652       // on our knowledge of the function definition.
6653       const FunctionDecl *Def = nullptr;
6654       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6655         Proto = Def->getType()->getAs<FunctionProtoType>();
6656        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6657           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6658           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6659       }
6660
6661       // If the function we're calling isn't a function prototype, but we have
6662       // a function prototype from a prior declaratiom, use that prototype.
6663       if (!FDecl->hasPrototype())
6664         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6665     }
6666
6667     // Promote the arguments (C99 6.5.2.2p6).
6668     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6669       Expr *Arg = Args[i];
6670
6671       if (Proto && i < Proto->getNumParams()) {
6672         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6673             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6674         ExprResult ArgE =
6675             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6676         if (ArgE.isInvalid())
6677           return true;
6678
6679         Arg = ArgE.getAs<Expr>();
6680
6681       } else {
6682         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6683
6684         if (ArgE.isInvalid())
6685           return true;
6686
6687         Arg = ArgE.getAs<Expr>();
6688       }
6689
6690       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6691                               diag::err_call_incomplete_argument, Arg))
6692         return ExprError();
6693
6694       TheCall->setArg(i, Arg);
6695     }
6696   }
6697
6698   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6699     if (!Method->isStatic())
6700       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6701         << Fn->getSourceRange());
6702
6703   // Check for sentinels
6704   if (NDecl)
6705     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6706
6707   // Warn for unions passing across security boundary (CMSE).
6708   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6709     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6710       if (const auto *RT =
6711               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6712         if (RT->getDecl()->isOrContainsUnion())
6713           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6714               << 0 << i;
6715       }
6716     }
6717   }
6718
6719   // Do special checking on direct calls to functions.
6720   if (FDecl) {
6721     if (CheckFunctionCall(FDecl, TheCall, Proto))
6722       return ExprError();
6723
6724     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6725
6726     if (BuiltinID)
6727       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6728   } else if (NDecl) {
6729     if (CheckPointerCall(NDecl, TheCall, Proto))
6730       return ExprError();
6731   } else {
6732     if (CheckOtherCall(TheCall, Proto))
6733       return ExprError();
6734   }
6735
6736   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6737 }
6738
6739 ExprResult
6740 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6741                            SourceLocation RParenLoc, Expr *InitExpr) {
6742   assert(Ty && "ActOnCompoundLiteral(): missing type");
6743   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6744
6745   TypeSourceInfo *TInfo;
6746   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6747   if (!TInfo)
6748     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6749
6750   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6751 }
6752
6753 ExprResult
6754 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6755                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6756   QualType literalType = TInfo->getType();
6757
6758   if (literalType->isArrayType()) {
6759     if (RequireCompleteSizedType(
6760             LParenLoc, Context.getBaseElementType(literalType),
6761             diag::err_array_incomplete_or_sizeless_type,
6762             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6763       return ExprError();
6764     if (literalType->isVariableArrayType())
6765       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6766         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6767   } else if (!literalType->isDependentType() &&
6768              RequireCompleteType(LParenLoc, literalType,
6769                diag::err_typecheck_decl_incomplete_type,
6770                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6771     return ExprError();
6772
6773   InitializedEntity Entity
6774     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6775   InitializationKind Kind
6776     = InitializationKind::CreateCStyleCast(LParenLoc,
6777                                            SourceRange(LParenLoc, RParenLoc),
6778                                            /*InitList=*/true);
6779   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6780   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6781                                       &literalType);
6782   if (Result.isInvalid())
6783     return ExprError();
6784   LiteralExpr = Result.get();
6785
6786   bool isFileScope = !CurContext->isFunctionOrMethod();
6787
6788   // In C, compound literals are l-values for some reason.
6789   // For GCC compatibility, in C++, file-scope array compound literals with
6790   // constant initializers are also l-values, and compound literals are
6791   // otherwise prvalues.
6792   //
6793   // (GCC also treats C++ list-initialized file-scope array prvalues with
6794   // constant initializers as l-values, but that's non-conforming, so we don't
6795   // follow it there.)
6796   //
6797   // FIXME: It would be better to handle the lvalue cases as materializing and
6798   // lifetime-extending a temporary object, but our materialized temporaries
6799   // representation only supports lifetime extension from a variable, not "out
6800   // of thin air".
6801   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6802   // is bound to the result of applying array-to-pointer decay to the compound
6803   // literal.
6804   // FIXME: GCC supports compound literals of reference type, which should
6805   // obviously have a value kind derived from the kind of reference involved.
6806   ExprValueKind VK =
6807       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6808           ? VK_RValue
6809           : VK_LValue;
6810
6811   if (isFileScope)
6812     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6813       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6814         Expr *Init = ILE->getInit(i);
6815         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6816       }
6817
6818   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6819                                               VK, LiteralExpr, isFileScope);
6820   if (isFileScope) {
6821     if (!LiteralExpr->isTypeDependent() &&
6822         !LiteralExpr->isValueDependent() &&
6823         !literalType->isDependentType()) // C99 6.5.2.5p3
6824       if (CheckForConstantInitializer(LiteralExpr, literalType))
6825         return ExprError();
6826   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6827              literalType.getAddressSpace() != LangAS::Default) {
6828     // Embedded-C extensions to C99 6.5.2.5:
6829     //   "If the compound literal occurs inside the body of a function, the
6830     //   type name shall not be qualified by an address-space qualifier."
6831     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6832       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6833     return ExprError();
6834   }
6835
6836   if (!isFileScope && !getLangOpts().CPlusPlus) {
6837     // Compound literals that have automatic storage duration are destroyed at
6838     // the end of the scope in C; in C++, they're just temporaries.
6839
6840     // Emit diagnostics if it is or contains a C union type that is non-trivial
6841     // to destruct.
6842     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6843       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6844                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6845
6846     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6847     if (literalType.isDestructedType()) {
6848       Cleanup.setExprNeedsCleanups(true);
6849       ExprCleanupObjects.push_back(E);
6850       getCurFunction()->setHasBranchProtectedScope();
6851     }
6852   }
6853
6854   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6855       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6856     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6857                                        E->getInitializer()->getExprLoc());
6858
6859   return MaybeBindToTemporary(E);
6860 }
6861
6862 ExprResult
6863 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6864                     SourceLocation RBraceLoc) {
6865   // Only produce each kind of designated initialization diagnostic once.
6866   SourceLocation FirstDesignator;
6867   bool DiagnosedArrayDesignator = false;
6868   bool DiagnosedNestedDesignator = false;
6869   bool DiagnosedMixedDesignator = false;
6870
6871   // Check that any designated initializers are syntactically valid in the
6872   // current language mode.
6873   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6874     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6875       if (FirstDesignator.isInvalid())
6876         FirstDesignator = DIE->getBeginLoc();
6877
6878       if (!getLangOpts().CPlusPlus)
6879         break;
6880
6881       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6882         DiagnosedNestedDesignator = true;
6883         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6884           << DIE->getDesignatorsSourceRange();
6885       }
6886
6887       for (auto &Desig : DIE->designators()) {
6888         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6889           DiagnosedArrayDesignator = true;
6890           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6891             << Desig.getSourceRange();
6892         }
6893       }
6894
6895       if (!DiagnosedMixedDesignator &&
6896           !isa<DesignatedInitExpr>(InitArgList[0])) {
6897         DiagnosedMixedDesignator = true;
6898         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6899           << DIE->getSourceRange();
6900         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6901           << InitArgList[0]->getSourceRange();
6902       }
6903     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6904                isa<DesignatedInitExpr>(InitArgList[0])) {
6905       DiagnosedMixedDesignator = true;
6906       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6907       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6908         << DIE->getSourceRange();
6909       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6910         << InitArgList[I]->getSourceRange();
6911     }
6912   }
6913
6914   if (FirstDesignator.isValid()) {
6915     // Only diagnose designated initiaization as a C++20 extension if we didn't
6916     // already diagnose use of (non-C++20) C99 designator syntax.
6917     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6918         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6919       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6920                                 ? diag::warn_cxx17_compat_designated_init
6921                                 : diag::ext_cxx_designated_init);
6922     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6923       Diag(FirstDesignator, diag::ext_designated_init);
6924     }
6925   }
6926
6927   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6928 }
6929
6930 ExprResult
6931 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6932                     SourceLocation RBraceLoc) {
6933   // Semantic analysis for initializers is done by ActOnDeclarator() and
6934   // CheckInitializer() - it requires knowledge of the object being initialized.
6935
6936   // Immediately handle non-overload placeholders.  Overloads can be
6937   // resolved contextually, but everything else here can't.
6938   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6939     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6940       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6941
6942       // Ignore failures; dropping the entire initializer list because
6943       // of one failure would be terrible for indexing/etc.
6944       if (result.isInvalid()) continue;
6945
6946       InitArgList[I] = result.get();
6947     }
6948   }
6949
6950   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6951                                                RBraceLoc);
6952   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6953   return E;
6954 }
6955
6956 /// Do an explicit extend of the given block pointer if we're in ARC.
6957 void Sema::maybeExtendBlockObject(ExprResult &E) {
6958   assert(E.get()->getType()->isBlockPointerType());
6959   assert(E.get()->isRValue());
6960
6961   // Only do this in an r-value context.
6962   if (!getLangOpts().ObjCAutoRefCount) return;
6963
6964   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6965                                CK_ARCExtendBlockObject, E.get(),
6966                                /*base path*/ nullptr, VK_RValue);
6967   Cleanup.setExprNeedsCleanups(true);
6968 }
6969
6970 /// Prepare a conversion of the given expression to an ObjC object
6971 /// pointer type.
6972 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6973   QualType type = E.get()->getType();
6974   if (type->isObjCObjectPointerType()) {
6975     return CK_BitCast;
6976   } else if (type->isBlockPointerType()) {
6977     maybeExtendBlockObject(E);
6978     return CK_BlockPointerToObjCPointerCast;
6979   } else {
6980     assert(type->isPointerType());
6981     return CK_CPointerToObjCPointerCast;
6982   }
6983 }
6984
6985 /// Prepares for a scalar cast, performing all the necessary stages
6986 /// except the final cast and returning the kind required.
6987 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6988   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6989   // Also, callers should have filtered out the invalid cases with
6990   // pointers.  Everything else should be possible.
6991
6992   QualType SrcTy = Src.get()->getType();
6993   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6994     return CK_NoOp;
6995
6996   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6997   case Type::STK_MemberPointer:
6998     llvm_unreachable("member pointer type in C");
6999
7000   case Type::STK_CPointer:
7001   case Type::STK_BlockPointer:
7002   case Type::STK_ObjCObjectPointer:
7003     switch (DestTy->getScalarTypeKind()) {
7004     case Type::STK_CPointer: {
7005       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7006       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7007       if (SrcAS != DestAS)
7008         return CK_AddressSpaceConversion;
7009       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7010         return CK_NoOp;
7011       return CK_BitCast;
7012     }
7013     case Type::STK_BlockPointer:
7014       return (SrcKind == Type::STK_BlockPointer
7015                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7016     case Type::STK_ObjCObjectPointer:
7017       if (SrcKind == Type::STK_ObjCObjectPointer)
7018         return CK_BitCast;
7019       if (SrcKind == Type::STK_CPointer)
7020         return CK_CPointerToObjCPointerCast;
7021       maybeExtendBlockObject(Src);
7022       return CK_BlockPointerToObjCPointerCast;
7023     case Type::STK_Bool:
7024       return CK_PointerToBoolean;
7025     case Type::STK_Integral:
7026       return CK_PointerToIntegral;
7027     case Type::STK_Floating:
7028     case Type::STK_FloatingComplex:
7029     case Type::STK_IntegralComplex:
7030     case Type::STK_MemberPointer:
7031     case Type::STK_FixedPoint:
7032       llvm_unreachable("illegal cast from pointer");
7033     }
7034     llvm_unreachable("Should have returned before this");
7035
7036   case Type::STK_FixedPoint:
7037     switch (DestTy->getScalarTypeKind()) {
7038     case Type::STK_FixedPoint:
7039       return CK_FixedPointCast;
7040     case Type::STK_Bool:
7041       return CK_FixedPointToBoolean;
7042     case Type::STK_Integral:
7043       return CK_FixedPointToIntegral;
7044     case Type::STK_Floating:
7045     case Type::STK_IntegralComplex:
7046     case Type::STK_FloatingComplex:
7047       Diag(Src.get()->getExprLoc(),
7048            diag::err_unimplemented_conversion_with_fixed_point_type)
7049           << DestTy;
7050       return CK_IntegralCast;
7051     case Type::STK_CPointer:
7052     case Type::STK_ObjCObjectPointer:
7053     case Type::STK_BlockPointer:
7054     case Type::STK_MemberPointer:
7055       llvm_unreachable("illegal cast to pointer type");
7056     }
7057     llvm_unreachable("Should have returned before this");
7058
7059   case Type::STK_Bool: // casting from bool is like casting from an integer
7060   case Type::STK_Integral:
7061     switch (DestTy->getScalarTypeKind()) {
7062     case Type::STK_CPointer:
7063     case Type::STK_ObjCObjectPointer:
7064     case Type::STK_BlockPointer:
7065       if (Src.get()->isNullPointerConstant(Context,
7066                                            Expr::NPC_ValueDependentIsNull))
7067         return CK_NullToPointer;
7068       return CK_IntegralToPointer;
7069     case Type::STK_Bool:
7070       return CK_IntegralToBoolean;
7071     case Type::STK_Integral:
7072       return CK_IntegralCast;
7073     case Type::STK_Floating:
7074       return CK_IntegralToFloating;
7075     case Type::STK_IntegralComplex:
7076       Src = ImpCastExprToType(Src.get(),
7077                       DestTy->castAs<ComplexType>()->getElementType(),
7078                       CK_IntegralCast);
7079       return CK_IntegralRealToComplex;
7080     case Type::STK_FloatingComplex:
7081       Src = ImpCastExprToType(Src.get(),
7082                       DestTy->castAs<ComplexType>()->getElementType(),
7083                       CK_IntegralToFloating);
7084       return CK_FloatingRealToComplex;
7085     case Type::STK_MemberPointer:
7086       llvm_unreachable("member pointer type in C");
7087     case Type::STK_FixedPoint:
7088       return CK_IntegralToFixedPoint;
7089     }
7090     llvm_unreachable("Should have returned before this");
7091
7092   case Type::STK_Floating:
7093     switch (DestTy->getScalarTypeKind()) {
7094     case Type::STK_Floating:
7095       return CK_FloatingCast;
7096     case Type::STK_Bool:
7097       return CK_FloatingToBoolean;
7098     case Type::STK_Integral:
7099       return CK_FloatingToIntegral;
7100     case Type::STK_FloatingComplex:
7101       Src = ImpCastExprToType(Src.get(),
7102                               DestTy->castAs<ComplexType>()->getElementType(),
7103                               CK_FloatingCast);
7104       return CK_FloatingRealToComplex;
7105     case Type::STK_IntegralComplex:
7106       Src = ImpCastExprToType(Src.get(),
7107                               DestTy->castAs<ComplexType>()->getElementType(),
7108                               CK_FloatingToIntegral);
7109       return CK_IntegralRealToComplex;
7110     case Type::STK_CPointer:
7111     case Type::STK_ObjCObjectPointer:
7112     case Type::STK_BlockPointer:
7113       llvm_unreachable("valid float->pointer cast?");
7114     case Type::STK_MemberPointer:
7115       llvm_unreachable("member pointer type in C");
7116     case Type::STK_FixedPoint:
7117       Diag(Src.get()->getExprLoc(),
7118            diag::err_unimplemented_conversion_with_fixed_point_type)
7119           << SrcTy;
7120       return CK_IntegralCast;
7121     }
7122     llvm_unreachable("Should have returned before this");
7123
7124   case Type::STK_FloatingComplex:
7125     switch (DestTy->getScalarTypeKind()) {
7126     case Type::STK_FloatingComplex:
7127       return CK_FloatingComplexCast;
7128     case Type::STK_IntegralComplex:
7129       return CK_FloatingComplexToIntegralComplex;
7130     case Type::STK_Floating: {
7131       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7132       if (Context.hasSameType(ET, DestTy))
7133         return CK_FloatingComplexToReal;
7134       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7135       return CK_FloatingCast;
7136     }
7137     case Type::STK_Bool:
7138       return CK_FloatingComplexToBoolean;
7139     case Type::STK_Integral:
7140       Src = ImpCastExprToType(Src.get(),
7141                               SrcTy->castAs<ComplexType>()->getElementType(),
7142                               CK_FloatingComplexToReal);
7143       return CK_FloatingToIntegral;
7144     case Type::STK_CPointer:
7145     case Type::STK_ObjCObjectPointer:
7146     case Type::STK_BlockPointer:
7147       llvm_unreachable("valid complex float->pointer cast?");
7148     case Type::STK_MemberPointer:
7149       llvm_unreachable("member pointer type in C");
7150     case Type::STK_FixedPoint:
7151       Diag(Src.get()->getExprLoc(),
7152            diag::err_unimplemented_conversion_with_fixed_point_type)
7153           << SrcTy;
7154       return CK_IntegralCast;
7155     }
7156     llvm_unreachable("Should have returned before this");
7157
7158   case Type::STK_IntegralComplex:
7159     switch (DestTy->getScalarTypeKind()) {
7160     case Type::STK_FloatingComplex:
7161       return CK_IntegralComplexToFloatingComplex;
7162     case Type::STK_IntegralComplex:
7163       return CK_IntegralComplexCast;
7164     case Type::STK_Integral: {
7165       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7166       if (Context.hasSameType(ET, DestTy))
7167         return CK_IntegralComplexToReal;
7168       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7169       return CK_IntegralCast;
7170     }
7171     case Type::STK_Bool:
7172       return CK_IntegralComplexToBoolean;
7173     case Type::STK_Floating:
7174       Src = ImpCastExprToType(Src.get(),
7175                               SrcTy->castAs<ComplexType>()->getElementType(),
7176                               CK_IntegralComplexToReal);
7177       return CK_IntegralToFloating;
7178     case Type::STK_CPointer:
7179     case Type::STK_ObjCObjectPointer:
7180     case Type::STK_BlockPointer:
7181       llvm_unreachable("valid complex int->pointer cast?");
7182     case Type::STK_MemberPointer:
7183       llvm_unreachable("member pointer type in C");
7184     case Type::STK_FixedPoint:
7185       Diag(Src.get()->getExprLoc(),
7186            diag::err_unimplemented_conversion_with_fixed_point_type)
7187           << SrcTy;
7188       return CK_IntegralCast;
7189     }
7190     llvm_unreachable("Should have returned before this");
7191   }
7192
7193   llvm_unreachable("Unhandled scalar cast");
7194 }
7195
7196 static bool breakDownVectorType(QualType type, uint64_t &len,
7197                                 QualType &eltType) {
7198   // Vectors are simple.
7199   if (const VectorType *vecType = type->getAs<VectorType>()) {
7200     len = vecType->getNumElements();
7201     eltType = vecType->getElementType();
7202     assert(eltType->isScalarType());
7203     return true;
7204   }
7205
7206   // We allow lax conversion to and from non-vector types, but only if
7207   // they're real types (i.e. non-complex, non-pointer scalar types).
7208   if (!type->isRealType()) return false;
7209
7210   len = 1;
7211   eltType = type;
7212   return true;
7213 }
7214
7215 /// Are the two types lax-compatible vector types?  That is, given
7216 /// that one of them is a vector, do they have equal storage sizes,
7217 /// where the storage size is the number of elements times the element
7218 /// size?
7219 ///
7220 /// This will also return false if either of the types is neither a
7221 /// vector nor a real type.
7222 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7223   assert(destTy->isVectorType() || srcTy->isVectorType());
7224
7225   // Disallow lax conversions between scalars and ExtVectors (these
7226   // conversions are allowed for other vector types because common headers
7227   // depend on them).  Most scalar OP ExtVector cases are handled by the
7228   // splat path anyway, which does what we want (convert, not bitcast).
7229   // What this rules out for ExtVectors is crazy things like char4*float.
7230   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7231   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7232
7233   uint64_t srcLen, destLen;
7234   QualType srcEltTy, destEltTy;
7235   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7236   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7237
7238   // ASTContext::getTypeSize will return the size rounded up to a
7239   // power of 2, so instead of using that, we need to use the raw
7240   // element size multiplied by the element count.
7241   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7242   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7243
7244   return (srcLen * srcEltSize == destLen * destEltSize);
7245 }
7246
7247 /// Is this a legal conversion between two types, one of which is
7248 /// known to be a vector type?
7249 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7250   assert(destTy->isVectorType() || srcTy->isVectorType());
7251
7252   switch (Context.getLangOpts().getLaxVectorConversions()) {
7253   case LangOptions::LaxVectorConversionKind::None:
7254     return false;
7255
7256   case LangOptions::LaxVectorConversionKind::Integer:
7257     if (!srcTy->isIntegralOrEnumerationType()) {
7258       auto *Vec = srcTy->getAs<VectorType>();
7259       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7260         return false;
7261     }
7262     if (!destTy->isIntegralOrEnumerationType()) {
7263       auto *Vec = destTy->getAs<VectorType>();
7264       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7265         return false;
7266     }
7267     // OK, integer (vector) -> integer (vector) bitcast.
7268     break;
7269
7270     case LangOptions::LaxVectorConversionKind::All:
7271     break;
7272   }
7273
7274   return areLaxCompatibleVectorTypes(srcTy, destTy);
7275 }
7276
7277 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7278                            CastKind &Kind) {
7279   assert(VectorTy->isVectorType() && "Not a vector type!");
7280
7281   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7282     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7283       return Diag(R.getBegin(),
7284                   Ty->isVectorType() ?
7285                   diag::err_invalid_conversion_between_vectors :
7286                   diag::err_invalid_conversion_between_vector_and_integer)
7287         << VectorTy << Ty << R;
7288   } else
7289     return Diag(R.getBegin(),
7290                 diag::err_invalid_conversion_between_vector_and_scalar)
7291       << VectorTy << Ty << R;
7292
7293   Kind = CK_BitCast;
7294   return false;
7295 }
7296
7297 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7298   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7299
7300   if (DestElemTy == SplattedExpr->getType())
7301     return SplattedExpr;
7302
7303   assert(DestElemTy->isFloatingType() ||
7304          DestElemTy->isIntegralOrEnumerationType());
7305
7306   CastKind CK;
7307   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7308     // OpenCL requires that we convert `true` boolean expressions to -1, but
7309     // only when splatting vectors.
7310     if (DestElemTy->isFloatingType()) {
7311       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7312       // in two steps: boolean to signed integral, then to floating.
7313       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7314                                                  CK_BooleanToSignedIntegral);
7315       SplattedExpr = CastExprRes.get();
7316       CK = CK_IntegralToFloating;
7317     } else {
7318       CK = CK_BooleanToSignedIntegral;
7319     }
7320   } else {
7321     ExprResult CastExprRes = SplattedExpr;
7322     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7323     if (CastExprRes.isInvalid())
7324       return ExprError();
7325     SplattedExpr = CastExprRes.get();
7326   }
7327   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7328 }
7329
7330 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7331                                     Expr *CastExpr, CastKind &Kind) {
7332   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7333
7334   QualType SrcTy = CastExpr->getType();
7335
7336   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7337   // an ExtVectorType.
7338   // In OpenCL, casts between vectors of different types are not allowed.
7339   // (See OpenCL 6.2).
7340   if (SrcTy->isVectorType()) {
7341     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7342         (getLangOpts().OpenCL &&
7343          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7344       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7345         << DestTy << SrcTy << R;
7346       return ExprError();
7347     }
7348     Kind = CK_BitCast;
7349     return CastExpr;
7350   }
7351
7352   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7353   // conversion will take place first from scalar to elt type, and then
7354   // splat from elt type to vector.
7355   if (SrcTy->isPointerType())
7356     return Diag(R.getBegin(),
7357                 diag::err_invalid_conversion_between_vector_and_scalar)
7358       << DestTy << SrcTy << R;
7359
7360   Kind = CK_VectorSplat;
7361   return prepareVectorSplat(DestTy, CastExpr);
7362 }
7363
7364 ExprResult
7365 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7366                     Declarator &D, ParsedType &Ty,
7367                     SourceLocation RParenLoc, Expr *CastExpr) {
7368   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7369          "ActOnCastExpr(): missing type or expr");
7370
7371   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7372   if (D.isInvalidType())
7373     return ExprError();
7374
7375   if (getLangOpts().CPlusPlus) {
7376     // Check that there are no default arguments (C++ only).
7377     CheckExtraCXXDefaultArguments(D);
7378   } else {
7379     // Make sure any TypoExprs have been dealt with.
7380     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7381     if (!Res.isUsable())
7382       return ExprError();
7383     CastExpr = Res.get();
7384   }
7385
7386   checkUnusedDeclAttributes(D);
7387
7388   QualType castType = castTInfo->getType();
7389   Ty = CreateParsedType(castType, castTInfo);
7390
7391   bool isVectorLiteral = false;
7392
7393   // Check for an altivec or OpenCL literal,
7394   // i.e. all the elements are integer constants.
7395   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7396   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7397   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7398        && castType->isVectorType() && (PE || PLE)) {
7399     if (PLE && PLE->getNumExprs() == 0) {
7400       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7401       return ExprError();
7402     }
7403     if (PE || PLE->getNumExprs() == 1) {
7404       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7405       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7406         isVectorLiteral = true;
7407     }
7408     else
7409       isVectorLiteral = true;
7410   }
7411
7412   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7413   // then handle it as such.
7414   if (isVectorLiteral)
7415     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7416
7417   // If the Expr being casted is a ParenListExpr, handle it specially.
7418   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7419   // sequence of BinOp comma operators.
7420   if (isa<ParenListExpr>(CastExpr)) {
7421     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7422     if (Result.isInvalid()) return ExprError();
7423     CastExpr = Result.get();
7424   }
7425
7426   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7427       !getSourceManager().isInSystemMacro(LParenLoc))
7428     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7429
7430   CheckTollFreeBridgeCast(castType, CastExpr);
7431
7432   CheckObjCBridgeRelatedCast(castType, CastExpr);
7433
7434   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7435
7436   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7437 }
7438
7439 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7440                                     SourceLocation RParenLoc, Expr *E,
7441                                     TypeSourceInfo *TInfo) {
7442   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7443          "Expected paren or paren list expression");
7444
7445   Expr **exprs;
7446   unsigned numExprs;
7447   Expr *subExpr;
7448   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7449   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7450     LiteralLParenLoc = PE->getLParenLoc();
7451     LiteralRParenLoc = PE->getRParenLoc();
7452     exprs = PE->getExprs();
7453     numExprs = PE->getNumExprs();
7454   } else { // isa<ParenExpr> by assertion at function entrance
7455     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7456     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7457     subExpr = cast<ParenExpr>(E)->getSubExpr();
7458     exprs = &subExpr;
7459     numExprs = 1;
7460   }
7461
7462   QualType Ty = TInfo->getType();
7463   assert(Ty->isVectorType() && "Expected vector type");
7464
7465   SmallVector<Expr *, 8> initExprs;
7466   const VectorType *VTy = Ty->castAs<VectorType>();
7467   unsigned numElems = VTy->getNumElements();
7468
7469   // '(...)' form of vector initialization in AltiVec: the number of
7470   // initializers must be one or must match the size of the vector.
7471   // If a single value is specified in the initializer then it will be
7472   // replicated to all the components of the vector
7473   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7474     // The number of initializers must be one or must match the size of the
7475     // vector. If a single value is specified in the initializer then it will
7476     // be replicated to all the components of the vector
7477     if (numExprs == 1) {
7478       QualType ElemTy = VTy->getElementType();
7479       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7480       if (Literal.isInvalid())
7481         return ExprError();
7482       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7483                                   PrepareScalarCast(Literal, ElemTy));
7484       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7485     }
7486     else if (numExprs < numElems) {
7487       Diag(E->getExprLoc(),
7488            diag::err_incorrect_number_of_vector_initializers);
7489       return ExprError();
7490     }
7491     else
7492       initExprs.append(exprs, exprs + numExprs);
7493   }
7494   else {
7495     // For OpenCL, when the number of initializers is a single value,
7496     // it will be replicated to all components of the vector.
7497     if (getLangOpts().OpenCL &&
7498         VTy->getVectorKind() == VectorType::GenericVector &&
7499         numExprs == 1) {
7500         QualType ElemTy = VTy->getElementType();
7501         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7502         if (Literal.isInvalid())
7503           return ExprError();
7504         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7505                                     PrepareScalarCast(Literal, ElemTy));
7506         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7507     }
7508
7509     initExprs.append(exprs, exprs + numExprs);
7510   }
7511   // FIXME: This means that pretty-printing the final AST will produce curly
7512   // braces instead of the original commas.
7513   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7514                                                    initExprs, LiteralRParenLoc);
7515   initE->setType(Ty);
7516   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7517 }
7518
7519 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7520 /// the ParenListExpr into a sequence of comma binary operators.
7521 ExprResult
7522 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7523   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7524   if (!E)
7525     return OrigExpr;
7526
7527   ExprResult Result(E->getExpr(0));
7528
7529   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7530     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7531                         E->getExpr(i));
7532
7533   if (Result.isInvalid()) return ExprError();
7534
7535   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7536 }
7537
7538 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7539                                     SourceLocation R,
7540                                     MultiExprArg Val) {
7541   return ParenListExpr::Create(Context, L, Val, R);
7542 }
7543
7544 /// Emit a specialized diagnostic when one expression is a null pointer
7545 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7546 /// emitted.
7547 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7548                                       SourceLocation QuestionLoc) {
7549   Expr *NullExpr = LHSExpr;
7550   Expr *NonPointerExpr = RHSExpr;
7551   Expr::NullPointerConstantKind NullKind =
7552       NullExpr->isNullPointerConstant(Context,
7553                                       Expr::NPC_ValueDependentIsNotNull);
7554
7555   if (NullKind == Expr::NPCK_NotNull) {
7556     NullExpr = RHSExpr;
7557     NonPointerExpr = LHSExpr;
7558     NullKind =
7559         NullExpr->isNullPointerConstant(Context,
7560                                         Expr::NPC_ValueDependentIsNotNull);
7561   }
7562
7563   if (NullKind == Expr::NPCK_NotNull)
7564     return false;
7565
7566   if (NullKind == Expr::NPCK_ZeroExpression)
7567     return false;
7568
7569   if (NullKind == Expr::NPCK_ZeroLiteral) {
7570     // In this case, check to make sure that we got here from a "NULL"
7571     // string in the source code.
7572     NullExpr = NullExpr->IgnoreParenImpCasts();
7573     SourceLocation loc = NullExpr->getExprLoc();
7574     if (!findMacroSpelling(loc, "NULL"))
7575       return false;
7576   }
7577
7578   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7579   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7580       << NonPointerExpr->getType() << DiagType
7581       << NonPointerExpr->getSourceRange();
7582   return true;
7583 }
7584
7585 /// Return false if the condition expression is valid, true otherwise.
7586 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7587   QualType CondTy = Cond->getType();
7588
7589   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7590   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7591     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7592       << CondTy << Cond->getSourceRange();
7593     return true;
7594   }
7595
7596   // C99 6.5.15p2
7597   if (CondTy->isScalarType()) return false;
7598
7599   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7600     << CondTy << Cond->getSourceRange();
7601   return true;
7602 }
7603
7604 /// Handle when one or both operands are void type.
7605 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7606                                          ExprResult &RHS) {
7607     Expr *LHSExpr = LHS.get();
7608     Expr *RHSExpr = RHS.get();
7609
7610     if (!LHSExpr->getType()->isVoidType())
7611       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7612           << RHSExpr->getSourceRange();
7613     if (!RHSExpr->getType()->isVoidType())
7614       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7615           << LHSExpr->getSourceRange();
7616     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7617     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7618     return S.Context.VoidTy;
7619 }
7620
7621 /// Return false if the NullExpr can be promoted to PointerTy,
7622 /// true otherwise.
7623 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7624                                         QualType PointerTy) {
7625   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7626       !NullExpr.get()->isNullPointerConstant(S.Context,
7627                                             Expr::NPC_ValueDependentIsNull))
7628     return true;
7629
7630   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7631   return false;
7632 }
7633
7634 /// Checks compatibility between two pointers and return the resulting
7635 /// type.
7636 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7637                                                      ExprResult &RHS,
7638                                                      SourceLocation Loc) {
7639   QualType LHSTy = LHS.get()->getType();
7640   QualType RHSTy = RHS.get()->getType();
7641
7642   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7643     // Two identical pointers types are always compatible.
7644     return LHSTy;
7645   }
7646
7647   QualType lhptee, rhptee;
7648
7649   // Get the pointee types.
7650   bool IsBlockPointer = false;
7651   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7652     lhptee = LHSBTy->getPointeeType();
7653     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7654     IsBlockPointer = true;
7655   } else {
7656     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7657     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7658   }
7659
7660   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7661   // differently qualified versions of compatible types, the result type is
7662   // a pointer to an appropriately qualified version of the composite
7663   // type.
7664
7665   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7666   // clause doesn't make sense for our extensions. E.g. address space 2 should
7667   // be incompatible with address space 3: they may live on different devices or
7668   // anything.
7669   Qualifiers lhQual = lhptee.getQualifiers();
7670   Qualifiers rhQual = rhptee.getQualifiers();
7671
7672   LangAS ResultAddrSpace = LangAS::Default;
7673   LangAS LAddrSpace = lhQual.getAddressSpace();
7674   LangAS RAddrSpace = rhQual.getAddressSpace();
7675
7676   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7677   // spaces is disallowed.
7678   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7679     ResultAddrSpace = LAddrSpace;
7680   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7681     ResultAddrSpace = RAddrSpace;
7682   else {
7683     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7684         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7685         << RHS.get()->getSourceRange();
7686     return QualType();
7687   }
7688
7689   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7690   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7691   lhQual.removeCVRQualifiers();
7692   rhQual.removeCVRQualifiers();
7693
7694   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7695   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7696   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7697   // qual types are compatible iff
7698   //  * corresponded types are compatible
7699   //  * CVR qualifiers are equal
7700   //  * address spaces are equal
7701   // Thus for conditional operator we merge CVR and address space unqualified
7702   // pointees and if there is a composite type we return a pointer to it with
7703   // merged qualifiers.
7704   LHSCastKind =
7705       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7706   RHSCastKind =
7707       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7708   lhQual.removeAddressSpace();
7709   rhQual.removeAddressSpace();
7710
7711   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7712   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7713
7714   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7715
7716   if (CompositeTy.isNull()) {
7717     // In this situation, we assume void* type. No especially good
7718     // reason, but this is what gcc does, and we do have to pick
7719     // to get a consistent AST.
7720     QualType incompatTy;
7721     incompatTy = S.Context.getPointerType(
7722         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7723     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7724     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7725
7726     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7727     // for casts between types with incompatible address space qualifiers.
7728     // For the following code the compiler produces casts between global and
7729     // local address spaces of the corresponded innermost pointees:
7730     // local int *global *a;
7731     // global int *global *b;
7732     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7733     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7734         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7735         << RHS.get()->getSourceRange();
7736
7737     return incompatTy;
7738   }
7739
7740   // The pointer types are compatible.
7741   // In case of OpenCL ResultTy should have the address space qualifier
7742   // which is a superset of address spaces of both the 2nd and the 3rd
7743   // operands of the conditional operator.
7744   QualType ResultTy = [&, ResultAddrSpace]() {
7745     if (S.getLangOpts().OpenCL) {
7746       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7747       CompositeQuals.setAddressSpace(ResultAddrSpace);
7748       return S.Context
7749           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7750           .withCVRQualifiers(MergedCVRQual);
7751     }
7752     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7753   }();
7754   if (IsBlockPointer)
7755     ResultTy = S.Context.getBlockPointerType(ResultTy);
7756   else
7757     ResultTy = S.Context.getPointerType(ResultTy);
7758
7759   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7760   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7761   return ResultTy;
7762 }
7763
7764 /// Return the resulting type when the operands are both block pointers.
7765 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7766                                                           ExprResult &LHS,
7767                                                           ExprResult &RHS,
7768                                                           SourceLocation Loc) {
7769   QualType LHSTy = LHS.get()->getType();
7770   QualType RHSTy = RHS.get()->getType();
7771
7772   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7773     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7774       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7775       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7776       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7777       return destType;
7778     }
7779     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7780       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7781       << RHS.get()->getSourceRange();
7782     return QualType();
7783   }
7784
7785   // We have 2 block pointer types.
7786   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7787 }
7788
7789 /// Return the resulting type when the operands are both pointers.
7790 static QualType
7791 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7792                                             ExprResult &RHS,
7793                                             SourceLocation Loc) {
7794   // get the pointer types
7795   QualType LHSTy = LHS.get()->getType();
7796   QualType RHSTy = RHS.get()->getType();
7797
7798   // get the "pointed to" types
7799   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7800   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7801
7802   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7803   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7804     // Figure out necessary qualifiers (C99 6.5.15p6)
7805     QualType destPointee
7806       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7807     QualType destType = S.Context.getPointerType(destPointee);
7808     // Add qualifiers if necessary.
7809     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7810     // Promote to void*.
7811     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7812     return destType;
7813   }
7814   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7815     QualType destPointee
7816       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7817     QualType destType = S.Context.getPointerType(destPointee);
7818     // Add qualifiers if necessary.
7819     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7820     // Promote to void*.
7821     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7822     return destType;
7823   }
7824
7825   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7826 }
7827
7828 /// Return false if the first expression is not an integer and the second
7829 /// expression is not a pointer, true otherwise.
7830 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7831                                         Expr* PointerExpr, SourceLocation Loc,
7832                                         bool IsIntFirstExpr) {
7833   if (!PointerExpr->getType()->isPointerType() ||
7834       !Int.get()->getType()->isIntegerType())
7835     return false;
7836
7837   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7838   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7839
7840   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7841     << Expr1->getType() << Expr2->getType()
7842     << Expr1->getSourceRange() << Expr2->getSourceRange();
7843   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7844                             CK_IntegralToPointer);
7845   return true;
7846 }
7847
7848 /// Simple conversion between integer and floating point types.
7849 ///
7850 /// Used when handling the OpenCL conditional operator where the
7851 /// condition is a vector while the other operands are scalar.
7852 ///
7853 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7854 /// types are either integer or floating type. Between the two
7855 /// operands, the type with the higher rank is defined as the "result
7856 /// type". The other operand needs to be promoted to the same type. No
7857 /// other type promotion is allowed. We cannot use
7858 /// UsualArithmeticConversions() for this purpose, since it always
7859 /// promotes promotable types.
7860 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7861                                             ExprResult &RHS,
7862                                             SourceLocation QuestionLoc) {
7863   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7864   if (LHS.isInvalid())
7865     return QualType();
7866   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7867   if (RHS.isInvalid())
7868     return QualType();
7869
7870   // For conversion purposes, we ignore any qualifiers.
7871   // For example, "const float" and "float" are equivalent.
7872   QualType LHSType =
7873     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7874   QualType RHSType =
7875     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7876
7877   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7878     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7879       << LHSType << LHS.get()->getSourceRange();
7880     return QualType();
7881   }
7882
7883   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7884     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7885       << RHSType << RHS.get()->getSourceRange();
7886     return QualType();
7887   }
7888
7889   // If both types are identical, no conversion is needed.
7890   if (LHSType == RHSType)
7891     return LHSType;
7892
7893   // Now handle "real" floating types (i.e. float, double, long double).
7894   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7895     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7896                                  /*IsCompAssign = */ false);
7897
7898   // Finally, we have two differing integer types.
7899   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7900   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7901 }
7902
7903 /// Convert scalar operands to a vector that matches the
7904 ///        condition in length.
7905 ///
7906 /// Used when handling the OpenCL conditional operator where the
7907 /// condition is a vector while the other operands are scalar.
7908 ///
7909 /// We first compute the "result type" for the scalar operands
7910 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7911 /// into a vector of that type where the length matches the condition
7912 /// vector type. s6.11.6 requires that the element types of the result
7913 /// and the condition must have the same number of bits.
7914 static QualType
7915 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7916                               QualType CondTy, SourceLocation QuestionLoc) {
7917   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7918   if (ResTy.isNull()) return QualType();
7919
7920   const VectorType *CV = CondTy->getAs<VectorType>();
7921   assert(CV);
7922
7923   // Determine the vector result type
7924   unsigned NumElements = CV->getNumElements();
7925   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7926
7927   // Ensure that all types have the same number of bits
7928   if (S.Context.getTypeSize(CV->getElementType())
7929       != S.Context.getTypeSize(ResTy)) {
7930     // Since VectorTy is created internally, it does not pretty print
7931     // with an OpenCL name. Instead, we just print a description.
7932     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7933     SmallString<64> Str;
7934     llvm::raw_svector_ostream OS(Str);
7935     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7936     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7937       << CondTy << OS.str();
7938     return QualType();
7939   }
7940
7941   // Convert operands to the vector result type
7942   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7943   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7944
7945   return VectorTy;
7946 }
7947
7948 /// Return false if this is a valid OpenCL condition vector
7949 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7950                                        SourceLocation QuestionLoc) {
7951   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7952   // integral type.
7953   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7954   assert(CondTy);
7955   QualType EleTy = CondTy->getElementType();
7956   if (EleTy->isIntegerType()) return false;
7957
7958   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7959     << Cond->getType() << Cond->getSourceRange();
7960   return true;
7961 }
7962
7963 /// Return false if the vector condition type and the vector
7964 ///        result type are compatible.
7965 ///
7966 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7967 /// number of elements, and their element types have the same number
7968 /// of bits.
7969 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7970                               SourceLocation QuestionLoc) {
7971   const VectorType *CV = CondTy->getAs<VectorType>();
7972   const VectorType *RV = VecResTy->getAs<VectorType>();
7973   assert(CV && RV);
7974
7975   if (CV->getNumElements() != RV->getNumElements()) {
7976     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7977       << CondTy << VecResTy;
7978     return true;
7979   }
7980
7981   QualType CVE = CV->getElementType();
7982   QualType RVE = RV->getElementType();
7983
7984   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7985     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7986       << CondTy << VecResTy;
7987     return true;
7988   }
7989
7990   return false;
7991 }
7992
7993 /// Return the resulting type for the conditional operator in
7994 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7995 ///        s6.3.i) when the condition is a vector type.
7996 static QualType
7997 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7998                              ExprResult &LHS, ExprResult &RHS,
7999                              SourceLocation QuestionLoc) {
8000   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8001   if (Cond.isInvalid())
8002     return QualType();
8003   QualType CondTy = Cond.get()->getType();
8004
8005   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8006     return QualType();
8007
8008   // If either operand is a vector then find the vector type of the
8009   // result as specified in OpenCL v1.1 s6.3.i.
8010   if (LHS.get()->getType()->isVectorType() ||
8011       RHS.get()->getType()->isVectorType()) {
8012     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8013                                               /*isCompAssign*/false,
8014                                               /*AllowBothBool*/true,
8015                                               /*AllowBoolConversions*/false);
8016     if (VecResTy.isNull()) return QualType();
8017     // The result type must match the condition type as specified in
8018     // OpenCL v1.1 s6.11.6.
8019     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8020       return QualType();
8021     return VecResTy;
8022   }
8023
8024   // Both operands are scalar.
8025   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8026 }
8027
8028 /// Return true if the Expr is block type
8029 static bool checkBlockType(Sema &S, const Expr *E) {
8030   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8031     QualType Ty = CE->getCallee()->getType();
8032     if (Ty->isBlockPointerType()) {
8033       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8034       return true;
8035     }
8036   }
8037   return false;
8038 }
8039
8040 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8041 /// In that case, LHS = cond.
8042 /// C99 6.5.15
8043 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8044                                         ExprResult &RHS, ExprValueKind &VK,
8045                                         ExprObjectKind &OK,
8046                                         SourceLocation QuestionLoc) {
8047
8048   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8049   if (!LHSResult.isUsable()) return QualType();
8050   LHS = LHSResult;
8051
8052   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8053   if (!RHSResult.isUsable()) return QualType();
8054   RHS = RHSResult;
8055
8056   // C++ is sufficiently different to merit its own checker.
8057   if (getLangOpts().CPlusPlus)
8058     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8059
8060   VK = VK_RValue;
8061   OK = OK_Ordinary;
8062
8063   // The OpenCL operator with a vector condition is sufficiently
8064   // different to merit its own checker.
8065   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8066       Cond.get()->getType()->isExtVectorType())
8067     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8068
8069   // First, check the condition.
8070   Cond = UsualUnaryConversions(Cond.get());
8071   if (Cond.isInvalid())
8072     return QualType();
8073   if (checkCondition(*this, Cond.get(), QuestionLoc))
8074     return QualType();
8075
8076   // Now check the two expressions.
8077   if (LHS.get()->getType()->isVectorType() ||
8078       RHS.get()->getType()->isVectorType())
8079     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8080                                /*AllowBothBool*/true,
8081                                /*AllowBoolConversions*/false);
8082
8083   QualType ResTy =
8084       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8085   if (LHS.isInvalid() || RHS.isInvalid())
8086     return QualType();
8087
8088   QualType LHSTy = LHS.get()->getType();
8089   QualType RHSTy = RHS.get()->getType();
8090
8091   // Diagnose attempts to convert between __float128 and long double where
8092   // such conversions currently can't be handled.
8093   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8094     Diag(QuestionLoc,
8095          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8096       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8097     return QualType();
8098   }
8099
8100   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8101   // selection operator (?:).
8102   if (getLangOpts().OpenCL &&
8103       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8104     return QualType();
8105   }
8106
8107   // If both operands have arithmetic type, do the usual arithmetic conversions
8108   // to find a common type: C99 6.5.15p3,5.
8109   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8110     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8111     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8112
8113     return ResTy;
8114   }
8115
8116   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8117   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8118     return LHSTy;
8119   }
8120
8121   // If both operands are the same structure or union type, the result is that
8122   // type.
8123   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8124     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8125       if (LHSRT->getDecl() == RHSRT->getDecl())
8126         // "If both the operands have structure or union type, the result has
8127         // that type."  This implies that CV qualifiers are dropped.
8128         return LHSTy.getUnqualifiedType();
8129     // FIXME: Type of conditional expression must be complete in C mode.
8130   }
8131
8132   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8133   // The following || allows only one side to be void (a GCC-ism).
8134   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8135     return checkConditionalVoidType(*this, LHS, RHS);
8136   }
8137
8138   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8139   // the type of the other operand."
8140   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8141   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8142
8143   // All objective-c pointer type analysis is done here.
8144   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8145                                                         QuestionLoc);
8146   if (LHS.isInvalid() || RHS.isInvalid())
8147     return QualType();
8148   if (!compositeType.isNull())
8149     return compositeType;
8150
8151
8152   // Handle block pointer types.
8153   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8154     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8155                                                      QuestionLoc);
8156
8157   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8158   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8159     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8160                                                        QuestionLoc);
8161
8162   // GCC compatibility: soften pointer/integer mismatch.  Note that
8163   // null pointers have been filtered out by this point.
8164   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8165       /*IsIntFirstExpr=*/true))
8166     return RHSTy;
8167   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8168       /*IsIntFirstExpr=*/false))
8169     return LHSTy;
8170
8171   // Allow ?: operations in which both operands have the same
8172   // built-in sizeless type.
8173   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8174     return LHSTy;
8175
8176   // Emit a better diagnostic if one of the expressions is a null pointer
8177   // constant and the other is not a pointer type. In this case, the user most
8178   // likely forgot to take the address of the other expression.
8179   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8180     return QualType();
8181
8182   // Otherwise, the operands are not compatible.
8183   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8184     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8185     << RHS.get()->getSourceRange();
8186   return QualType();
8187 }
8188
8189 /// FindCompositeObjCPointerType - Helper method to find composite type of
8190 /// two objective-c pointer types of the two input expressions.
8191 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8192                                             SourceLocation QuestionLoc) {
8193   QualType LHSTy = LHS.get()->getType();
8194   QualType RHSTy = RHS.get()->getType();
8195
8196   // Handle things like Class and struct objc_class*.  Here we case the result
8197   // to the pseudo-builtin, because that will be implicitly cast back to the
8198   // redefinition type if an attempt is made to access its fields.
8199   if (LHSTy->isObjCClassType() &&
8200       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8201     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8202     return LHSTy;
8203   }
8204   if (RHSTy->isObjCClassType() &&
8205       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8206     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8207     return RHSTy;
8208   }
8209   // And the same for struct objc_object* / id
8210   if (LHSTy->isObjCIdType() &&
8211       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8212     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8213     return LHSTy;
8214   }
8215   if (RHSTy->isObjCIdType() &&
8216       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8217     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8218     return RHSTy;
8219   }
8220   // And the same for struct objc_selector* / SEL
8221   if (Context.isObjCSelType(LHSTy) &&
8222       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8223     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8224     return LHSTy;
8225   }
8226   if (Context.isObjCSelType(RHSTy) &&
8227       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8228     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8229     return RHSTy;
8230   }
8231   // Check constraints for Objective-C object pointers types.
8232   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8233
8234     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8235       // Two identical object pointer types are always compatible.
8236       return LHSTy;
8237     }
8238     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8239     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8240     QualType compositeType = LHSTy;
8241
8242     // If both operands are interfaces and either operand can be
8243     // assigned to the other, use that type as the composite
8244     // type. This allows
8245     //   xxx ? (A*) a : (B*) b
8246     // where B is a subclass of A.
8247     //
8248     // Additionally, as for assignment, if either type is 'id'
8249     // allow silent coercion. Finally, if the types are
8250     // incompatible then make sure to use 'id' as the composite
8251     // type so the result is acceptable for sending messages to.
8252
8253     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8254     // It could return the composite type.
8255     if (!(compositeType =
8256           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8257       // Nothing more to do.
8258     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8259       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8260     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8261       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8262     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8263                 RHSOPT->isObjCQualifiedIdType()) &&
8264                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8265                                                          true)) {
8266       // Need to handle "id<xx>" explicitly.
8267       // GCC allows qualified id and any Objective-C type to devolve to
8268       // id. Currently localizing to here until clear this should be
8269       // part of ObjCQualifiedIdTypesAreCompatible.
8270       compositeType = Context.getObjCIdType();
8271     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8272       compositeType = Context.getObjCIdType();
8273     } else {
8274       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8275       << LHSTy << RHSTy
8276       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8277       QualType incompatTy = Context.getObjCIdType();
8278       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8279       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8280       return incompatTy;
8281     }
8282     // The object pointer types are compatible.
8283     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8284     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8285     return compositeType;
8286   }
8287   // Check Objective-C object pointer types and 'void *'
8288   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8289     if (getLangOpts().ObjCAutoRefCount) {
8290       // ARC forbids the implicit conversion of object pointers to 'void *',
8291       // so these types are not compatible.
8292       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8293           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8294       LHS = RHS = true;
8295       return QualType();
8296     }
8297     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8298     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8299     QualType destPointee
8300     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8301     QualType destType = Context.getPointerType(destPointee);
8302     // Add qualifiers if necessary.
8303     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8304     // Promote to void*.
8305     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8306     return destType;
8307   }
8308   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8309     if (getLangOpts().ObjCAutoRefCount) {
8310       // ARC forbids the implicit conversion of object pointers to 'void *',
8311       // so these types are not compatible.
8312       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8313           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8314       LHS = RHS = true;
8315       return QualType();
8316     }
8317     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8318     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8319     QualType destPointee
8320     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8321     QualType destType = Context.getPointerType(destPointee);
8322     // Add qualifiers if necessary.
8323     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8324     // Promote to void*.
8325     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8326     return destType;
8327   }
8328   return QualType();
8329 }
8330
8331 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8332 /// ParenRange in parentheses.
8333 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8334                                const PartialDiagnostic &Note,
8335                                SourceRange ParenRange) {
8336   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8337   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8338       EndLoc.isValid()) {
8339     Self.Diag(Loc, Note)
8340       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8341       << FixItHint::CreateInsertion(EndLoc, ")");
8342   } else {
8343     // We can't display the parentheses, so just show the bare note.
8344     Self.Diag(Loc, Note) << ParenRange;
8345   }
8346 }
8347
8348 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8349   return BinaryOperator::isAdditiveOp(Opc) ||
8350          BinaryOperator::isMultiplicativeOp(Opc) ||
8351          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8352   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8353   // not any of the logical operators.  Bitwise-xor is commonly used as a
8354   // logical-xor because there is no logical-xor operator.  The logical
8355   // operators, including uses of xor, have a high false positive rate for
8356   // precedence warnings.
8357 }
8358
8359 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8360 /// expression, either using a built-in or overloaded operator,
8361 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8362 /// expression.
8363 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8364                                    Expr **RHSExprs) {
8365   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8366   E = E->IgnoreImpCasts();
8367   E = E->IgnoreConversionOperator();
8368   E = E->IgnoreImpCasts();
8369   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8370     E = MTE->getSubExpr();
8371     E = E->IgnoreImpCasts();
8372   }
8373
8374   // Built-in binary operator.
8375   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8376     if (IsArithmeticOp(OP->getOpcode())) {
8377       *Opcode = OP->getOpcode();
8378       *RHSExprs = OP->getRHS();
8379       return true;
8380     }
8381   }
8382
8383   // Overloaded operator.
8384   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8385     if (Call->getNumArgs() != 2)
8386       return false;
8387
8388     // Make sure this is really a binary operator that is safe to pass into
8389     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8390     OverloadedOperatorKind OO = Call->getOperator();
8391     if (OO < OO_Plus || OO > OO_Arrow ||
8392         OO == OO_PlusPlus || OO == OO_MinusMinus)
8393       return false;
8394
8395     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8396     if (IsArithmeticOp(OpKind)) {
8397       *Opcode = OpKind;
8398       *RHSExprs = Call->getArg(1);
8399       return true;
8400     }
8401   }
8402
8403   return false;
8404 }
8405
8406 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8407 /// or is a logical expression such as (x==y) which has int type, but is
8408 /// commonly interpreted as boolean.
8409 static bool ExprLooksBoolean(Expr *E) {
8410   E = E->IgnoreParenImpCasts();
8411
8412   if (E->getType()->isBooleanType())
8413     return true;
8414   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8415     return OP->isComparisonOp() || OP->isLogicalOp();
8416   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8417     return OP->getOpcode() == UO_LNot;
8418   if (E->getType()->isPointerType())
8419     return true;
8420   // FIXME: What about overloaded operator calls returning "unspecified boolean
8421   // type"s (commonly pointer-to-members)?
8422
8423   return false;
8424 }
8425
8426 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8427 /// and binary operator are mixed in a way that suggests the programmer assumed
8428 /// the conditional operator has higher precedence, for example:
8429 /// "int x = a + someBinaryCondition ? 1 : 2".
8430 static void DiagnoseConditionalPrecedence(Sema &Self,
8431                                           SourceLocation OpLoc,
8432                                           Expr *Condition,
8433                                           Expr *LHSExpr,
8434                                           Expr *RHSExpr) {
8435   BinaryOperatorKind CondOpcode;
8436   Expr *CondRHS;
8437
8438   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8439     return;
8440   if (!ExprLooksBoolean(CondRHS))
8441     return;
8442
8443   // The condition is an arithmetic binary expression, with a right-
8444   // hand side that looks boolean, so warn.
8445
8446   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8447                         ? diag::warn_precedence_bitwise_conditional
8448                         : diag::warn_precedence_conditional;
8449
8450   Self.Diag(OpLoc, DiagID)
8451       << Condition->getSourceRange()
8452       << BinaryOperator::getOpcodeStr(CondOpcode);
8453
8454   SuggestParentheses(
8455       Self, OpLoc,
8456       Self.PDiag(diag::note_precedence_silence)
8457           << BinaryOperator::getOpcodeStr(CondOpcode),
8458       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8459
8460   SuggestParentheses(Self, OpLoc,
8461                      Self.PDiag(diag::note_precedence_conditional_first),
8462                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8463 }
8464
8465 /// Compute the nullability of a conditional expression.
8466 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8467                                               QualType LHSTy, QualType RHSTy,
8468                                               ASTContext &Ctx) {
8469   if (!ResTy->isAnyPointerType())
8470     return ResTy;
8471
8472   auto GetNullability = [&Ctx](QualType Ty) {
8473     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8474     if (Kind)
8475       return *Kind;
8476     return NullabilityKind::Unspecified;
8477   };
8478
8479   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8480   NullabilityKind MergedKind;
8481
8482   // Compute nullability of a binary conditional expression.
8483   if (IsBin) {
8484     if (LHSKind == NullabilityKind::NonNull)
8485       MergedKind = NullabilityKind::NonNull;
8486     else
8487       MergedKind = RHSKind;
8488   // Compute nullability of a normal conditional expression.
8489   } else {
8490     if (LHSKind == NullabilityKind::Nullable ||
8491         RHSKind == NullabilityKind::Nullable)
8492       MergedKind = NullabilityKind::Nullable;
8493     else if (LHSKind == NullabilityKind::NonNull)
8494       MergedKind = RHSKind;
8495     else if (RHSKind == NullabilityKind::NonNull)
8496       MergedKind = LHSKind;
8497     else
8498       MergedKind = NullabilityKind::Unspecified;
8499   }
8500
8501   // Return if ResTy already has the correct nullability.
8502   if (GetNullability(ResTy) == MergedKind)
8503     return ResTy;
8504
8505   // Strip all nullability from ResTy.
8506   while (ResTy->getNullability(Ctx))
8507     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8508
8509   // Create a new AttributedType with the new nullability kind.
8510   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8511   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8512 }
8513
8514 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8515 /// in the case of a the GNU conditional expr extension.
8516 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8517                                     SourceLocation ColonLoc,
8518                                     Expr *CondExpr, Expr *LHSExpr,
8519                                     Expr *RHSExpr) {
8520   if (!getLangOpts().CPlusPlus) {
8521     // C cannot handle TypoExpr nodes in the condition because it
8522     // doesn't handle dependent types properly, so make sure any TypoExprs have
8523     // been dealt with before checking the operands.
8524     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8525     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8526     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8527
8528     if (!CondResult.isUsable())
8529       return ExprError();
8530
8531     if (LHSExpr) {
8532       if (!LHSResult.isUsable())
8533         return ExprError();
8534     }
8535
8536     if (!RHSResult.isUsable())
8537       return ExprError();
8538
8539     CondExpr = CondResult.get();
8540     LHSExpr = LHSResult.get();
8541     RHSExpr = RHSResult.get();
8542   }
8543
8544   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8545   // was the condition.
8546   OpaqueValueExpr *opaqueValue = nullptr;
8547   Expr *commonExpr = nullptr;
8548   if (!LHSExpr) {
8549     commonExpr = CondExpr;
8550     // Lower out placeholder types first.  This is important so that we don't
8551     // try to capture a placeholder. This happens in few cases in C++; such
8552     // as Objective-C++'s dictionary subscripting syntax.
8553     if (commonExpr->hasPlaceholderType()) {
8554       ExprResult result = CheckPlaceholderExpr(commonExpr);
8555       if (!result.isUsable()) return ExprError();
8556       commonExpr = result.get();
8557     }
8558     // We usually want to apply unary conversions *before* saving, except
8559     // in the special case of a C++ l-value conditional.
8560     if (!(getLangOpts().CPlusPlus
8561           && !commonExpr->isTypeDependent()
8562           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8563           && commonExpr->isGLValue()
8564           && commonExpr->isOrdinaryOrBitFieldObject()
8565           && RHSExpr->isOrdinaryOrBitFieldObject()
8566           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8567       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8568       if (commonRes.isInvalid())
8569         return ExprError();
8570       commonExpr = commonRes.get();
8571     }
8572
8573     // If the common expression is a class or array prvalue, materialize it
8574     // so that we can safely refer to it multiple times.
8575     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8576                                    commonExpr->getType()->isArrayType())) {
8577       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8578       if (MatExpr.isInvalid())
8579         return ExprError();
8580       commonExpr = MatExpr.get();
8581     }
8582
8583     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8584                                                 commonExpr->getType(),
8585                                                 commonExpr->getValueKind(),
8586                                                 commonExpr->getObjectKind(),
8587                                                 commonExpr);
8588     LHSExpr = CondExpr = opaqueValue;
8589   }
8590
8591   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8592   ExprValueKind VK = VK_RValue;
8593   ExprObjectKind OK = OK_Ordinary;
8594   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8595   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8596                                              VK, OK, QuestionLoc);
8597   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8598       RHS.isInvalid())
8599     return ExprError();
8600
8601   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8602                                 RHS.get());
8603
8604   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8605
8606   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8607                                          Context);
8608
8609   if (!commonExpr)
8610     return new (Context)
8611         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8612                             RHS.get(), result, VK, OK);
8613
8614   return new (Context) BinaryConditionalOperator(
8615       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8616       ColonLoc, result, VK, OK);
8617 }
8618
8619 // Check if we have a conversion between incompatible cmse function pointer
8620 // types, that is, a conversion between a function pointer with the
8621 // cmse_nonsecure_call attribute and one without.
8622 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8623                                           QualType ToType) {
8624   if (const auto *ToFn =
8625           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8626     if (const auto *FromFn =
8627             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8628       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8629       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8630
8631       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8632     }
8633   }
8634   return false;
8635 }
8636
8637 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8638 // being closely modeled after the C99 spec:-). The odd characteristic of this
8639 // routine is it effectively iqnores the qualifiers on the top level pointee.
8640 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8641 // FIXME: add a couple examples in this comment.
8642 static Sema::AssignConvertType
8643 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8644   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8645   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8646
8647   // get the "pointed to" type (ignoring qualifiers at the top level)
8648   const Type *lhptee, *rhptee;
8649   Qualifiers lhq, rhq;
8650   std::tie(lhptee, lhq) =
8651       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8652   std::tie(rhptee, rhq) =
8653       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8654
8655   Sema::AssignConvertType ConvTy = Sema::Compatible;
8656
8657   // C99 6.5.16.1p1: This following citation is common to constraints
8658   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8659   // qualifiers of the type *pointed to* by the right;
8660
8661   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8662   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8663       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8664     // Ignore lifetime for further calculation.
8665     lhq.removeObjCLifetime();
8666     rhq.removeObjCLifetime();
8667   }
8668
8669   if (!lhq.compatiblyIncludes(rhq)) {
8670     // Treat address-space mismatches as fatal.
8671     if (!lhq.isAddressSpaceSupersetOf(rhq))
8672       return Sema::IncompatiblePointerDiscardsQualifiers;
8673
8674     // It's okay to add or remove GC or lifetime qualifiers when converting to
8675     // and from void*.
8676     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8677                         .compatiblyIncludes(
8678                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8679              && (lhptee->isVoidType() || rhptee->isVoidType()))
8680       ; // keep old
8681
8682     // Treat lifetime mismatches as fatal.
8683     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8684       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8685
8686     // For GCC/MS compatibility, other qualifier mismatches are treated
8687     // as still compatible in C.
8688     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8689   }
8690
8691   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8692   // incomplete type and the other is a pointer to a qualified or unqualified
8693   // version of void...
8694   if (lhptee->isVoidType()) {
8695     if (rhptee->isIncompleteOrObjectType())
8696       return ConvTy;
8697
8698     // As an extension, we allow cast to/from void* to function pointer.
8699     assert(rhptee->isFunctionType());
8700     return Sema::FunctionVoidPointer;
8701   }
8702
8703   if (rhptee->isVoidType()) {
8704     if (lhptee->isIncompleteOrObjectType())
8705       return ConvTy;
8706
8707     // As an extension, we allow cast to/from void* to function pointer.
8708     assert(lhptee->isFunctionType());
8709     return Sema::FunctionVoidPointer;
8710   }
8711
8712   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8713   // unqualified versions of compatible types, ...
8714   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8715   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8716     // Check if the pointee types are compatible ignoring the sign.
8717     // We explicitly check for char so that we catch "char" vs
8718     // "unsigned char" on systems where "char" is unsigned.
8719     if (lhptee->isCharType())
8720       ltrans = S.Context.UnsignedCharTy;
8721     else if (lhptee->hasSignedIntegerRepresentation())
8722       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8723
8724     if (rhptee->isCharType())
8725       rtrans = S.Context.UnsignedCharTy;
8726     else if (rhptee->hasSignedIntegerRepresentation())
8727       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8728
8729     if (ltrans == rtrans) {
8730       // Types are compatible ignoring the sign. Qualifier incompatibility
8731       // takes priority over sign incompatibility because the sign
8732       // warning can be disabled.
8733       if (ConvTy != Sema::Compatible)
8734         return ConvTy;
8735
8736       return Sema::IncompatiblePointerSign;
8737     }
8738
8739     // If we are a multi-level pointer, it's possible that our issue is simply
8740     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8741     // the eventual target type is the same and the pointers have the same
8742     // level of indirection, this must be the issue.
8743     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8744       do {
8745         std::tie(lhptee, lhq) =
8746           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8747         std::tie(rhptee, rhq) =
8748           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8749
8750         // Inconsistent address spaces at this point is invalid, even if the
8751         // address spaces would be compatible.
8752         // FIXME: This doesn't catch address space mismatches for pointers of
8753         // different nesting levels, like:
8754         //   __local int *** a;
8755         //   int ** b = a;
8756         // It's not clear how to actually determine when such pointers are
8757         // invalidly incompatible.
8758         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8759           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8760
8761       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8762
8763       if (lhptee == rhptee)
8764         return Sema::IncompatibleNestedPointerQualifiers;
8765     }
8766
8767     // General pointer incompatibility takes priority over qualifiers.
8768     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8769       return Sema::IncompatibleFunctionPointer;
8770     return Sema::IncompatiblePointer;
8771   }
8772   if (!S.getLangOpts().CPlusPlus &&
8773       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8774     return Sema::IncompatibleFunctionPointer;
8775   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8776     return Sema::IncompatibleFunctionPointer;
8777   return ConvTy;
8778 }
8779
8780 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8781 /// block pointer types are compatible or whether a block and normal pointer
8782 /// are compatible. It is more restrict than comparing two function pointer
8783 // types.
8784 static Sema::AssignConvertType
8785 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8786                                     QualType RHSType) {
8787   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8788   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8789
8790   QualType lhptee, rhptee;
8791
8792   // get the "pointed to" type (ignoring qualifiers at the top level)
8793   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8794   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8795
8796   // In C++, the types have to match exactly.
8797   if (S.getLangOpts().CPlusPlus)
8798     return Sema::IncompatibleBlockPointer;
8799
8800   Sema::AssignConvertType ConvTy = Sema::Compatible;
8801
8802   // For blocks we enforce that qualifiers are identical.
8803   Qualifiers LQuals = lhptee.getLocalQualifiers();
8804   Qualifiers RQuals = rhptee.getLocalQualifiers();
8805   if (S.getLangOpts().OpenCL) {
8806     LQuals.removeAddressSpace();
8807     RQuals.removeAddressSpace();
8808   }
8809   if (LQuals != RQuals)
8810     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8811
8812   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8813   // assignment.
8814   // The current behavior is similar to C++ lambdas. A block might be
8815   // assigned to a variable iff its return type and parameters are compatible
8816   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8817   // an assignment. Presumably it should behave in way that a function pointer
8818   // assignment does in C, so for each parameter and return type:
8819   //  * CVR and address space of LHS should be a superset of CVR and address
8820   //  space of RHS.
8821   //  * unqualified types should be compatible.
8822   if (S.getLangOpts().OpenCL) {
8823     if (!S.Context.typesAreBlockPointerCompatible(
8824             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8825             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8826       return Sema::IncompatibleBlockPointer;
8827   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8828     return Sema::IncompatibleBlockPointer;
8829
8830   return ConvTy;
8831 }
8832
8833 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8834 /// for assignment compatibility.
8835 static Sema::AssignConvertType
8836 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8837                                    QualType RHSType) {
8838   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8839   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8840
8841   if (LHSType->isObjCBuiltinType()) {
8842     // Class is not compatible with ObjC object pointers.
8843     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8844         !RHSType->isObjCQualifiedClassType())
8845       return Sema::IncompatiblePointer;
8846     return Sema::Compatible;
8847   }
8848   if (RHSType->isObjCBuiltinType()) {
8849     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8850         !LHSType->isObjCQualifiedClassType())
8851       return Sema::IncompatiblePointer;
8852     return Sema::Compatible;
8853   }
8854   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8855   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8856
8857   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8858       // make an exception for id<P>
8859       !LHSType->isObjCQualifiedIdType())
8860     return Sema::CompatiblePointerDiscardsQualifiers;
8861
8862   if (S.Context.typesAreCompatible(LHSType, RHSType))
8863     return Sema::Compatible;
8864   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8865     return Sema::IncompatibleObjCQualifiedId;
8866   return Sema::IncompatiblePointer;
8867 }
8868
8869 Sema::AssignConvertType
8870 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8871                                  QualType LHSType, QualType RHSType) {
8872   // Fake up an opaque expression.  We don't actually care about what
8873   // cast operations are required, so if CheckAssignmentConstraints
8874   // adds casts to this they'll be wasted, but fortunately that doesn't
8875   // usually happen on valid code.
8876   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8877   ExprResult RHSPtr = &RHSExpr;
8878   CastKind K;
8879
8880   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8881 }
8882
8883 /// This helper function returns true if QT is a vector type that has element
8884 /// type ElementType.
8885 static bool isVector(QualType QT, QualType ElementType) {
8886   if (const VectorType *VT = QT->getAs<VectorType>())
8887     return VT->getElementType().getCanonicalType() == ElementType;
8888   return false;
8889 }
8890
8891 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8892 /// has code to accommodate several GCC extensions when type checking
8893 /// pointers. Here are some objectionable examples that GCC considers warnings:
8894 ///
8895 ///  int a, *pint;
8896 ///  short *pshort;
8897 ///  struct foo *pfoo;
8898 ///
8899 ///  pint = pshort; // warning: assignment from incompatible pointer type
8900 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8901 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8902 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8903 ///
8904 /// As a result, the code for dealing with pointers is more complex than the
8905 /// C99 spec dictates.
8906 ///
8907 /// Sets 'Kind' for any result kind except Incompatible.
8908 Sema::AssignConvertType
8909 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8910                                  CastKind &Kind, bool ConvertRHS) {
8911   QualType RHSType = RHS.get()->getType();
8912   QualType OrigLHSType = LHSType;
8913
8914   // Get canonical types.  We're not formatting these types, just comparing
8915   // them.
8916   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8917   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8918
8919   // Common case: no conversion required.
8920   if (LHSType == RHSType) {
8921     Kind = CK_NoOp;
8922     return Compatible;
8923   }
8924
8925   // If we have an atomic type, try a non-atomic assignment, then just add an
8926   // atomic qualification step.
8927   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8928     Sema::AssignConvertType result =
8929       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8930     if (result != Compatible)
8931       return result;
8932     if (Kind != CK_NoOp && ConvertRHS)
8933       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8934     Kind = CK_NonAtomicToAtomic;
8935     return Compatible;
8936   }
8937
8938   // If the left-hand side is a reference type, then we are in a
8939   // (rare!) case where we've allowed the use of references in C,
8940   // e.g., as a parameter type in a built-in function. In this case,
8941   // just make sure that the type referenced is compatible with the
8942   // right-hand side type. The caller is responsible for adjusting
8943   // LHSType so that the resulting expression does not have reference
8944   // type.
8945   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8946     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8947       Kind = CK_LValueBitCast;
8948       return Compatible;
8949     }
8950     return Incompatible;
8951   }
8952
8953   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8954   // to the same ExtVector type.
8955   if (LHSType->isExtVectorType()) {
8956     if (RHSType->isExtVectorType())
8957       return Incompatible;
8958     if (RHSType->isArithmeticType()) {
8959       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8960       if (ConvertRHS)
8961         RHS = prepareVectorSplat(LHSType, RHS.get());
8962       Kind = CK_VectorSplat;
8963       return Compatible;
8964     }
8965   }
8966
8967   // Conversions to or from vector type.
8968   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8969     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8970       // Allow assignments of an AltiVec vector type to an equivalent GCC
8971       // vector type and vice versa
8972       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8973         Kind = CK_BitCast;
8974         return Compatible;
8975       }
8976
8977       // If we are allowing lax vector conversions, and LHS and RHS are both
8978       // vectors, the total size only needs to be the same. This is a bitcast;
8979       // no bits are changed but the result type is different.
8980       if (isLaxVectorConversion(RHSType, LHSType)) {
8981         Kind = CK_BitCast;
8982         return IncompatibleVectors;
8983       }
8984     }
8985
8986     // When the RHS comes from another lax conversion (e.g. binops between
8987     // scalars and vectors) the result is canonicalized as a vector. When the
8988     // LHS is also a vector, the lax is allowed by the condition above. Handle
8989     // the case where LHS is a scalar.
8990     if (LHSType->isScalarType()) {
8991       const VectorType *VecType = RHSType->getAs<VectorType>();
8992       if (VecType && VecType->getNumElements() == 1 &&
8993           isLaxVectorConversion(RHSType, LHSType)) {
8994         ExprResult *VecExpr = &RHS;
8995         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8996         Kind = CK_BitCast;
8997         return Compatible;
8998       }
8999     }
9000
9001     return Incompatible;
9002   }
9003
9004   // Diagnose attempts to convert between __float128 and long double where
9005   // such conversions currently can't be handled.
9006   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9007     return Incompatible;
9008
9009   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9010   // discards the imaginary part.
9011   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9012       !LHSType->getAs<ComplexType>())
9013     return Incompatible;
9014
9015   // Arithmetic conversions.
9016   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9017       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9018     if (ConvertRHS)
9019       Kind = PrepareScalarCast(RHS, LHSType);
9020     return Compatible;
9021   }
9022
9023   // Conversions to normal pointers.
9024   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9025     // U* -> T*
9026     if (isa<PointerType>(RHSType)) {
9027       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9028       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9029       if (AddrSpaceL != AddrSpaceR)
9030         Kind = CK_AddressSpaceConversion;
9031       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9032         Kind = CK_NoOp;
9033       else
9034         Kind = CK_BitCast;
9035       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9036     }
9037
9038     // int -> T*
9039     if (RHSType->isIntegerType()) {
9040       Kind = CK_IntegralToPointer; // FIXME: null?
9041       return IntToPointer;
9042     }
9043
9044     // C pointers are not compatible with ObjC object pointers,
9045     // with two exceptions:
9046     if (isa<ObjCObjectPointerType>(RHSType)) {
9047       //  - conversions to void*
9048       if (LHSPointer->getPointeeType()->isVoidType()) {
9049         Kind = CK_BitCast;
9050         return Compatible;
9051       }
9052
9053       //  - conversions from 'Class' to the redefinition type
9054       if (RHSType->isObjCClassType() &&
9055           Context.hasSameType(LHSType,
9056                               Context.getObjCClassRedefinitionType())) {
9057         Kind = CK_BitCast;
9058         return Compatible;
9059       }
9060
9061       Kind = CK_BitCast;
9062       return IncompatiblePointer;
9063     }
9064
9065     // U^ -> void*
9066     if (RHSType->getAs<BlockPointerType>()) {
9067       if (LHSPointer->getPointeeType()->isVoidType()) {
9068         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9069         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9070                                 ->getPointeeType()
9071                                 .getAddressSpace();
9072         Kind =
9073             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9074         return Compatible;
9075       }
9076     }
9077
9078     return Incompatible;
9079   }
9080
9081   // Conversions to block pointers.
9082   if (isa<BlockPointerType>(LHSType)) {
9083     // U^ -> T^
9084     if (RHSType->isBlockPointerType()) {
9085       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9086                               ->getPointeeType()
9087                               .getAddressSpace();
9088       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9089                               ->getPointeeType()
9090                               .getAddressSpace();
9091       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9092       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9093     }
9094
9095     // int or null -> T^
9096     if (RHSType->isIntegerType()) {
9097       Kind = CK_IntegralToPointer; // FIXME: null
9098       return IntToBlockPointer;
9099     }
9100
9101     // id -> T^
9102     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9103       Kind = CK_AnyPointerToBlockPointerCast;
9104       return Compatible;
9105     }
9106
9107     // void* -> T^
9108     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9109       if (RHSPT->getPointeeType()->isVoidType()) {
9110         Kind = CK_AnyPointerToBlockPointerCast;
9111         return Compatible;
9112       }
9113
9114     return Incompatible;
9115   }
9116
9117   // Conversions to Objective-C pointers.
9118   if (isa<ObjCObjectPointerType>(LHSType)) {
9119     // A* -> B*
9120     if (RHSType->isObjCObjectPointerType()) {
9121       Kind = CK_BitCast;
9122       Sema::AssignConvertType result =
9123         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9124       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9125           result == Compatible &&
9126           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9127         result = IncompatibleObjCWeakRef;
9128       return result;
9129     }
9130
9131     // int or null -> A*
9132     if (RHSType->isIntegerType()) {
9133       Kind = CK_IntegralToPointer; // FIXME: null
9134       return IntToPointer;
9135     }
9136
9137     // In general, C pointers are not compatible with ObjC object pointers,
9138     // with two exceptions:
9139     if (isa<PointerType>(RHSType)) {
9140       Kind = CK_CPointerToObjCPointerCast;
9141
9142       //  - conversions from 'void*'
9143       if (RHSType->isVoidPointerType()) {
9144         return Compatible;
9145       }
9146
9147       //  - conversions to 'Class' from its redefinition type
9148       if (LHSType->isObjCClassType() &&
9149           Context.hasSameType(RHSType,
9150                               Context.getObjCClassRedefinitionType())) {
9151         return Compatible;
9152       }
9153
9154       return IncompatiblePointer;
9155     }
9156
9157     // Only under strict condition T^ is compatible with an Objective-C pointer.
9158     if (RHSType->isBlockPointerType() &&
9159         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9160       if (ConvertRHS)
9161         maybeExtendBlockObject(RHS);
9162       Kind = CK_BlockPointerToObjCPointerCast;
9163       return Compatible;
9164     }
9165
9166     return Incompatible;
9167   }
9168
9169   // Conversions from pointers that are not covered by the above.
9170   if (isa<PointerType>(RHSType)) {
9171     // T* -> _Bool
9172     if (LHSType == Context.BoolTy) {
9173       Kind = CK_PointerToBoolean;
9174       return Compatible;
9175     }
9176
9177     // T* -> int
9178     if (LHSType->isIntegerType()) {
9179       Kind = CK_PointerToIntegral;
9180       return PointerToInt;
9181     }
9182
9183     return Incompatible;
9184   }
9185
9186   // Conversions from Objective-C pointers that are not covered by the above.
9187   if (isa<ObjCObjectPointerType>(RHSType)) {
9188     // T* -> _Bool
9189     if (LHSType == Context.BoolTy) {
9190       Kind = CK_PointerToBoolean;
9191       return Compatible;
9192     }
9193
9194     // T* -> int
9195     if (LHSType->isIntegerType()) {
9196       Kind = CK_PointerToIntegral;
9197       return PointerToInt;
9198     }
9199
9200     return Incompatible;
9201   }
9202
9203   // struct A -> struct B
9204   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9205     if (Context.typesAreCompatible(LHSType, RHSType)) {
9206       Kind = CK_NoOp;
9207       return Compatible;
9208     }
9209   }
9210
9211   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9212     Kind = CK_IntToOCLSampler;
9213     return Compatible;
9214   }
9215
9216   return Incompatible;
9217 }
9218
9219 /// Constructs a transparent union from an expression that is
9220 /// used to initialize the transparent union.
9221 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9222                                       ExprResult &EResult, QualType UnionType,
9223                                       FieldDecl *Field) {
9224   // Build an initializer list that designates the appropriate member
9225   // of the transparent union.
9226   Expr *E = EResult.get();
9227   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9228                                                    E, SourceLocation());
9229   Initializer->setType(UnionType);
9230   Initializer->setInitializedFieldInUnion(Field);
9231
9232   // Build a compound literal constructing a value of the transparent
9233   // union type from this initializer list.
9234   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9235   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9236                                         VK_RValue, Initializer, false);
9237 }
9238
9239 Sema::AssignConvertType
9240 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9241                                                ExprResult &RHS) {
9242   QualType RHSType = RHS.get()->getType();
9243
9244   // If the ArgType is a Union type, we want to handle a potential
9245   // transparent_union GCC extension.
9246   const RecordType *UT = ArgType->getAsUnionType();
9247   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9248     return Incompatible;
9249
9250   // The field to initialize within the transparent union.
9251   RecordDecl *UD = UT->getDecl();
9252   FieldDecl *InitField = nullptr;
9253   // It's compatible if the expression matches any of the fields.
9254   for (auto *it : UD->fields()) {
9255     if (it->getType()->isPointerType()) {
9256       // If the transparent union contains a pointer type, we allow:
9257       // 1) void pointer
9258       // 2) null pointer constant
9259       if (RHSType->isPointerType())
9260         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9261           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9262           InitField = it;
9263           break;
9264         }
9265
9266       if (RHS.get()->isNullPointerConstant(Context,
9267                                            Expr::NPC_ValueDependentIsNull)) {
9268         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9269                                 CK_NullToPointer);
9270         InitField = it;
9271         break;
9272       }
9273     }
9274
9275     CastKind Kind;
9276     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9277           == Compatible) {
9278       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9279       InitField = it;
9280       break;
9281     }
9282   }
9283
9284   if (!InitField)
9285     return Incompatible;
9286
9287   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9288   return Compatible;
9289 }
9290
9291 Sema::AssignConvertType
9292 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9293                                        bool Diagnose,
9294                                        bool DiagnoseCFAudited,
9295                                        bool ConvertRHS) {
9296   // We need to be able to tell the caller whether we diagnosed a problem, if
9297   // they ask us to issue diagnostics.
9298   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9299
9300   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9301   // we can't avoid *all* modifications at the moment, so we need some somewhere
9302   // to put the updated value.
9303   ExprResult LocalRHS = CallerRHS;
9304   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9305
9306   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9307     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9308       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9309           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9310         Diag(RHS.get()->getExprLoc(),
9311              diag::warn_noderef_to_dereferenceable_pointer)
9312             << RHS.get()->getSourceRange();
9313       }
9314     }
9315   }
9316
9317   if (getLangOpts().CPlusPlus) {
9318     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9319       // C++ 5.17p3: If the left operand is not of class type, the
9320       // expression is implicitly converted (C++ 4) to the
9321       // cv-unqualified type of the left operand.
9322       QualType RHSType = RHS.get()->getType();
9323       if (Diagnose) {
9324         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9325                                         AA_Assigning);
9326       } else {
9327         ImplicitConversionSequence ICS =
9328             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9329                                   /*SuppressUserConversions=*/false,
9330                                   AllowedExplicit::None,
9331                                   /*InOverloadResolution=*/false,
9332                                   /*CStyle=*/false,
9333                                   /*AllowObjCWritebackConversion=*/false);
9334         if (ICS.isFailure())
9335           return Incompatible;
9336         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9337                                         ICS, AA_Assigning);
9338       }
9339       if (RHS.isInvalid())
9340         return Incompatible;
9341       Sema::AssignConvertType result = Compatible;
9342       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9343           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9344         result = IncompatibleObjCWeakRef;
9345       return result;
9346     }
9347
9348     // FIXME: Currently, we fall through and treat C++ classes like C
9349     // structures.
9350     // FIXME: We also fall through for atomics; not sure what should
9351     // happen there, though.
9352   } else if (RHS.get()->getType() == Context.OverloadTy) {
9353     // As a set of extensions to C, we support overloading on functions. These
9354     // functions need to be resolved here.
9355     DeclAccessPair DAP;
9356     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9357             RHS.get(), LHSType, /*Complain=*/false, DAP))
9358       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9359     else
9360       return Incompatible;
9361   }
9362
9363   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9364   // a null pointer constant.
9365   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9366        LHSType->isBlockPointerType()) &&
9367       RHS.get()->isNullPointerConstant(Context,
9368                                        Expr::NPC_ValueDependentIsNull)) {
9369     if (Diagnose || ConvertRHS) {
9370       CastKind Kind;
9371       CXXCastPath Path;
9372       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9373                              /*IgnoreBaseAccess=*/false, Diagnose);
9374       if (ConvertRHS)
9375         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9376     }
9377     return Compatible;
9378   }
9379
9380   // OpenCL queue_t type assignment.
9381   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9382                                  Context, Expr::NPC_ValueDependentIsNull)) {
9383     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9384     return Compatible;
9385   }
9386
9387   // This check seems unnatural, however it is necessary to ensure the proper
9388   // conversion of functions/arrays. If the conversion were done for all
9389   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9390   // expressions that suppress this implicit conversion (&, sizeof).
9391   //
9392   // Suppress this for references: C++ 8.5.3p5.
9393   if (!LHSType->isReferenceType()) {
9394     // FIXME: We potentially allocate here even if ConvertRHS is false.
9395     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9396     if (RHS.isInvalid())
9397       return Incompatible;
9398   }
9399   CastKind Kind;
9400   Sema::AssignConvertType result =
9401     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9402
9403   // C99 6.5.16.1p2: The value of the right operand is converted to the
9404   // type of the assignment expression.
9405   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9406   // so that we can use references in built-in functions even in C.
9407   // The getNonReferenceType() call makes sure that the resulting expression
9408   // does not have reference type.
9409   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9410     QualType Ty = LHSType.getNonLValueExprType(Context);
9411     Expr *E = RHS.get();
9412
9413     // Check for various Objective-C errors. If we are not reporting
9414     // diagnostics and just checking for errors, e.g., during overload
9415     // resolution, return Incompatible to indicate the failure.
9416     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9417         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9418                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9419       if (!Diagnose)
9420         return Incompatible;
9421     }
9422     if (getLangOpts().ObjC &&
9423         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9424                                            E->getType(), E, Diagnose) ||
9425          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9426       if (!Diagnose)
9427         return Incompatible;
9428       // Replace the expression with a corrected version and continue so we
9429       // can find further errors.
9430       RHS = E;
9431       return Compatible;
9432     }
9433
9434     if (ConvertRHS)
9435       RHS = ImpCastExprToType(E, Ty, Kind);
9436   }
9437
9438   return result;
9439 }
9440
9441 namespace {
9442 /// The original operand to an operator, prior to the application of the usual
9443 /// arithmetic conversions and converting the arguments of a builtin operator
9444 /// candidate.
9445 struct OriginalOperand {
9446   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9447     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9448       Op = MTE->getSubExpr();
9449     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9450       Op = BTE->getSubExpr();
9451     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9452       Orig = ICE->getSubExprAsWritten();
9453       Conversion = ICE->getConversionFunction();
9454     }
9455   }
9456
9457   QualType getType() const { return Orig->getType(); }
9458
9459   Expr *Orig;
9460   NamedDecl *Conversion;
9461 };
9462 }
9463
9464 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9465                                ExprResult &RHS) {
9466   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9467
9468   Diag(Loc, diag::err_typecheck_invalid_operands)
9469     << OrigLHS.getType() << OrigRHS.getType()
9470     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9471
9472   // If a user-defined conversion was applied to either of the operands prior
9473   // to applying the built-in operator rules, tell the user about it.
9474   if (OrigLHS.Conversion) {
9475     Diag(OrigLHS.Conversion->getLocation(),
9476          diag::note_typecheck_invalid_operands_converted)
9477       << 0 << LHS.get()->getType();
9478   }
9479   if (OrigRHS.Conversion) {
9480     Diag(OrigRHS.Conversion->getLocation(),
9481          diag::note_typecheck_invalid_operands_converted)
9482       << 1 << RHS.get()->getType();
9483   }
9484
9485   return QualType();
9486 }
9487
9488 // Diagnose cases where a scalar was implicitly converted to a vector and
9489 // diagnose the underlying types. Otherwise, diagnose the error
9490 // as invalid vector logical operands for non-C++ cases.
9491 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9492                                             ExprResult &RHS) {
9493   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9494   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9495
9496   bool LHSNatVec = LHSType->isVectorType();
9497   bool RHSNatVec = RHSType->isVectorType();
9498
9499   if (!(LHSNatVec && RHSNatVec)) {
9500     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9501     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9502     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9503         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9504         << Vector->getSourceRange();
9505     return QualType();
9506   }
9507
9508   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9509       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9510       << RHS.get()->getSourceRange();
9511
9512   return QualType();
9513 }
9514
9515 /// Try to convert a value of non-vector type to a vector type by converting
9516 /// the type to the element type of the vector and then performing a splat.
9517 /// If the language is OpenCL, we only use conversions that promote scalar
9518 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9519 /// for float->int.
9520 ///
9521 /// OpenCL V2.0 6.2.6.p2:
9522 /// An error shall occur if any scalar operand type has greater rank
9523 /// than the type of the vector element.
9524 ///
9525 /// \param scalar - if non-null, actually perform the conversions
9526 /// \return true if the operation fails (but without diagnosing the failure)
9527 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9528                                      QualType scalarTy,
9529                                      QualType vectorEltTy,
9530                                      QualType vectorTy,
9531                                      unsigned &DiagID) {
9532   // The conversion to apply to the scalar before splatting it,
9533   // if necessary.
9534   CastKind scalarCast = CK_NoOp;
9535
9536   if (vectorEltTy->isIntegralType(S.Context)) {
9537     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9538         (scalarTy->isIntegerType() &&
9539          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9540       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9541       return true;
9542     }
9543     if (!scalarTy->isIntegralType(S.Context))
9544       return true;
9545     scalarCast = CK_IntegralCast;
9546   } else if (vectorEltTy->isRealFloatingType()) {
9547     if (scalarTy->isRealFloatingType()) {
9548       if (S.getLangOpts().OpenCL &&
9549           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9550         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9551         return true;
9552       }
9553       scalarCast = CK_FloatingCast;
9554     }
9555     else if (scalarTy->isIntegralType(S.Context))
9556       scalarCast = CK_IntegralToFloating;
9557     else
9558       return true;
9559   } else {
9560     return true;
9561   }
9562
9563   // Adjust scalar if desired.
9564   if (scalar) {
9565     if (scalarCast != CK_NoOp)
9566       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9567     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9568   }
9569   return false;
9570 }
9571
9572 /// Convert vector E to a vector with the same number of elements but different
9573 /// element type.
9574 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9575   const auto *VecTy = E->getType()->getAs<VectorType>();
9576   assert(VecTy && "Expression E must be a vector");
9577   QualType NewVecTy = S.Context.getVectorType(ElementType,
9578                                               VecTy->getNumElements(),
9579                                               VecTy->getVectorKind());
9580
9581   // Look through the implicit cast. Return the subexpression if its type is
9582   // NewVecTy.
9583   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9584     if (ICE->getSubExpr()->getType() == NewVecTy)
9585       return ICE->getSubExpr();
9586
9587   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9588   return S.ImpCastExprToType(E, NewVecTy, Cast);
9589 }
9590
9591 /// Test if a (constant) integer Int can be casted to another integer type
9592 /// IntTy without losing precision.
9593 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9594                                       QualType OtherIntTy) {
9595   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9596
9597   // Reject cases where the value of the Int is unknown as that would
9598   // possibly cause truncation, but accept cases where the scalar can be
9599   // demoted without loss of precision.
9600   Expr::EvalResult EVResult;
9601   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9602   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9603   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9604   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9605
9606   if (CstInt) {
9607     // If the scalar is constant and is of a higher order and has more active
9608     // bits that the vector element type, reject it.
9609     llvm::APSInt Result = EVResult.Val.getInt();
9610     unsigned NumBits = IntSigned
9611                            ? (Result.isNegative() ? Result.getMinSignedBits()
9612                                                   : Result.getActiveBits())
9613                            : Result.getActiveBits();
9614     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9615       return true;
9616
9617     // If the signedness of the scalar type and the vector element type
9618     // differs and the number of bits is greater than that of the vector
9619     // element reject it.
9620     return (IntSigned != OtherIntSigned &&
9621             NumBits > S.Context.getIntWidth(OtherIntTy));
9622   }
9623
9624   // Reject cases where the value of the scalar is not constant and it's
9625   // order is greater than that of the vector element type.
9626   return (Order < 0);
9627 }
9628
9629 /// Test if a (constant) integer Int can be casted to floating point type
9630 /// FloatTy without losing precision.
9631 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9632                                      QualType FloatTy) {
9633   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9634
9635   // Determine if the integer constant can be expressed as a floating point
9636   // number of the appropriate type.
9637   Expr::EvalResult EVResult;
9638   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9639
9640   uint64_t Bits = 0;
9641   if (CstInt) {
9642     // Reject constants that would be truncated if they were converted to
9643     // the floating point type. Test by simple to/from conversion.
9644     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9645     //        could be avoided if there was a convertFromAPInt method
9646     //        which could signal back if implicit truncation occurred.
9647     llvm::APSInt Result = EVResult.Val.getInt();
9648     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9649     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9650                            llvm::APFloat::rmTowardZero);
9651     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9652                              !IntTy->hasSignedIntegerRepresentation());
9653     bool Ignored = false;
9654     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9655                            &Ignored);
9656     if (Result != ConvertBack)
9657       return true;
9658   } else {
9659     // Reject types that cannot be fully encoded into the mantissa of
9660     // the float.
9661     Bits = S.Context.getTypeSize(IntTy);
9662     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9663         S.Context.getFloatTypeSemantics(FloatTy));
9664     if (Bits > FloatPrec)
9665       return true;
9666   }
9667
9668   return false;
9669 }
9670
9671 /// Attempt to convert and splat Scalar into a vector whose types matches
9672 /// Vector following GCC conversion rules. The rule is that implicit
9673 /// conversion can occur when Scalar can be casted to match Vector's element
9674 /// type without causing truncation of Scalar.
9675 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9676                                         ExprResult *Vector) {
9677   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9678   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9679   const VectorType *VT = VectorTy->getAs<VectorType>();
9680
9681   assert(!isa<ExtVectorType>(VT) &&
9682          "ExtVectorTypes should not be handled here!");
9683
9684   QualType VectorEltTy = VT->getElementType();
9685
9686   // Reject cases where the vector element type or the scalar element type are
9687   // not integral or floating point types.
9688   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9689     return true;
9690
9691   // The conversion to apply to the scalar before splatting it,
9692   // if necessary.
9693   CastKind ScalarCast = CK_NoOp;
9694
9695   // Accept cases where the vector elements are integers and the scalar is
9696   // an integer.
9697   // FIXME: Notionally if the scalar was a floating point value with a precise
9698   //        integral representation, we could cast it to an appropriate integer
9699   //        type and then perform the rest of the checks here. GCC will perform
9700   //        this conversion in some cases as determined by the input language.
9701   //        We should accept it on a language independent basis.
9702   if (VectorEltTy->isIntegralType(S.Context) &&
9703       ScalarTy->isIntegralType(S.Context) &&
9704       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9705
9706     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9707       return true;
9708
9709     ScalarCast = CK_IntegralCast;
9710   } else if (VectorEltTy->isIntegralType(S.Context) &&
9711              ScalarTy->isRealFloatingType()) {
9712     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9713       ScalarCast = CK_FloatingToIntegral;
9714     else
9715       return true;
9716   } else if (VectorEltTy->isRealFloatingType()) {
9717     if (ScalarTy->isRealFloatingType()) {
9718
9719       // Reject cases where the scalar type is not a constant and has a higher
9720       // Order than the vector element type.
9721       llvm::APFloat Result(0.0);
9722
9723       // Determine whether this is a constant scalar. In the event that the
9724       // value is dependent (and thus cannot be evaluated by the constant
9725       // evaluator), skip the evaluation. This will then diagnose once the
9726       // expression is instantiated.
9727       bool CstScalar = Scalar->get()->isValueDependent() ||
9728                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9729       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9730       if (!CstScalar && Order < 0)
9731         return true;
9732
9733       // If the scalar cannot be safely casted to the vector element type,
9734       // reject it.
9735       if (CstScalar) {
9736         bool Truncated = false;
9737         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9738                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9739         if (Truncated)
9740           return true;
9741       }
9742
9743       ScalarCast = CK_FloatingCast;
9744     } else if (ScalarTy->isIntegralType(S.Context)) {
9745       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9746         return true;
9747
9748       ScalarCast = CK_IntegralToFloating;
9749     } else
9750       return true;
9751   } else if (ScalarTy->isEnumeralType())
9752     return true;
9753
9754   // Adjust scalar if desired.
9755   if (Scalar) {
9756     if (ScalarCast != CK_NoOp)
9757       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9758     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9759   }
9760   return false;
9761 }
9762
9763 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9764                                    SourceLocation Loc, bool IsCompAssign,
9765                                    bool AllowBothBool,
9766                                    bool AllowBoolConversions) {
9767   if (!IsCompAssign) {
9768     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9769     if (LHS.isInvalid())
9770       return QualType();
9771   }
9772   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9773   if (RHS.isInvalid())
9774     return QualType();
9775
9776   // For conversion purposes, we ignore any qualifiers.
9777   // For example, "const float" and "float" are equivalent.
9778   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9779   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9780
9781   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9782   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9783   assert(LHSVecType || RHSVecType);
9784
9785   // AltiVec-style "vector bool op vector bool" combinations are allowed
9786   // for some operators but not others.
9787   if (!AllowBothBool &&
9788       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9789       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9790     return InvalidOperands(Loc, LHS, RHS);
9791
9792   // If the vector types are identical, return.
9793   if (Context.hasSameType(LHSType, RHSType))
9794     return LHSType;
9795
9796   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9797   if (LHSVecType && RHSVecType &&
9798       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9799     if (isa<ExtVectorType>(LHSVecType)) {
9800       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9801       return LHSType;
9802     }
9803
9804     if (!IsCompAssign)
9805       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9806     return RHSType;
9807   }
9808
9809   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9810   // can be mixed, with the result being the non-bool type.  The non-bool
9811   // operand must have integer element type.
9812   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9813       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9814       (Context.getTypeSize(LHSVecType->getElementType()) ==
9815        Context.getTypeSize(RHSVecType->getElementType()))) {
9816     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9817         LHSVecType->getElementType()->isIntegerType() &&
9818         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9819       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9820       return LHSType;
9821     }
9822     if (!IsCompAssign &&
9823         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9824         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9825         RHSVecType->getElementType()->isIntegerType()) {
9826       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9827       return RHSType;
9828     }
9829   }
9830
9831   // If there's a vector type and a scalar, try to convert the scalar to
9832   // the vector element type and splat.
9833   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9834   if (!RHSVecType) {
9835     if (isa<ExtVectorType>(LHSVecType)) {
9836       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9837                                     LHSVecType->getElementType(), LHSType,
9838                                     DiagID))
9839         return LHSType;
9840     } else {
9841       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9842         return LHSType;
9843     }
9844   }
9845   if (!LHSVecType) {
9846     if (isa<ExtVectorType>(RHSVecType)) {
9847       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9848                                     LHSType, RHSVecType->getElementType(),
9849                                     RHSType, DiagID))
9850         return RHSType;
9851     } else {
9852       if (LHS.get()->getValueKind() == VK_LValue ||
9853           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9854         return RHSType;
9855     }
9856   }
9857
9858   // FIXME: The code below also handles conversion between vectors and
9859   // non-scalars, we should break this down into fine grained specific checks
9860   // and emit proper diagnostics.
9861   QualType VecType = LHSVecType ? LHSType : RHSType;
9862   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9863   QualType OtherType = LHSVecType ? RHSType : LHSType;
9864   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9865   if (isLaxVectorConversion(OtherType, VecType)) {
9866     // If we're allowing lax vector conversions, only the total (data) size
9867     // needs to be the same. For non compound assignment, if one of the types is
9868     // scalar, the result is always the vector type.
9869     if (!IsCompAssign) {
9870       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9871       return VecType;
9872     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9873     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9874     // type. Note that this is already done by non-compound assignments in
9875     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9876     // <1 x T> -> T. The result is also a vector type.
9877     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9878                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9879       ExprResult *RHSExpr = &RHS;
9880       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9881       return VecType;
9882     }
9883   }
9884
9885   // Okay, the expression is invalid.
9886
9887   // If there's a non-vector, non-real operand, diagnose that.
9888   if ((!RHSVecType && !RHSType->isRealType()) ||
9889       (!LHSVecType && !LHSType->isRealType())) {
9890     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9891       << LHSType << RHSType
9892       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9893     return QualType();
9894   }
9895
9896   // OpenCL V1.1 6.2.6.p1:
9897   // If the operands are of more than one vector type, then an error shall
9898   // occur. Implicit conversions between vector types are not permitted, per
9899   // section 6.2.1.
9900   if (getLangOpts().OpenCL &&
9901       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9902       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9903     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9904                                                            << RHSType;
9905     return QualType();
9906   }
9907
9908
9909   // If there is a vector type that is not a ExtVector and a scalar, we reach
9910   // this point if scalar could not be converted to the vector's element type
9911   // without truncation.
9912   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9913       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9914     QualType Scalar = LHSVecType ? RHSType : LHSType;
9915     QualType Vector = LHSVecType ? LHSType : RHSType;
9916     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9917     Diag(Loc,
9918          diag::err_typecheck_vector_not_convertable_implict_truncation)
9919         << ScalarOrVector << Scalar << Vector;
9920
9921     return QualType();
9922   }
9923
9924   // Otherwise, use the generic diagnostic.
9925   Diag(Loc, DiagID)
9926     << LHSType << RHSType
9927     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9928   return QualType();
9929 }
9930
9931 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9932 // expression.  These are mainly cases where the null pointer is used as an
9933 // integer instead of a pointer.
9934 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9935                                 SourceLocation Loc, bool IsCompare) {
9936   // The canonical way to check for a GNU null is with isNullPointerConstant,
9937   // but we use a bit of a hack here for speed; this is a relatively
9938   // hot path, and isNullPointerConstant is slow.
9939   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9940   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9941
9942   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9943
9944   // Avoid analyzing cases where the result will either be invalid (and
9945   // diagnosed as such) or entirely valid and not something to warn about.
9946   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9947       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9948     return;
9949
9950   // Comparison operations would not make sense with a null pointer no matter
9951   // what the other expression is.
9952   if (!IsCompare) {
9953     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9954         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9955         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9956     return;
9957   }
9958
9959   // The rest of the operations only make sense with a null pointer
9960   // if the other expression is a pointer.
9961   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9962       NonNullType->canDecayToPointerType())
9963     return;
9964
9965   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9966       << LHSNull /* LHS is NULL */ << NonNullType
9967       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9968 }
9969
9970 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9971                                           SourceLocation Loc) {
9972   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9973   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9974   if (!LUE || !RUE)
9975     return;
9976   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9977       RUE->getKind() != UETT_SizeOf)
9978     return;
9979
9980   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9981   QualType LHSTy = LHSArg->getType();
9982   QualType RHSTy;
9983
9984   if (RUE->isArgumentType())
9985     RHSTy = RUE->getArgumentType();
9986   else
9987     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9988
9989   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9990     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9991       return;
9992
9993     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9994     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9995       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9996         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9997             << LHSArgDecl;
9998     }
9999   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10000     QualType ArrayElemTy = ArrayTy->getElementType();
10001     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10002         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10003         ArrayElemTy->isCharType() ||
10004         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10005       return;
10006     S.Diag(Loc, diag::warn_division_sizeof_array)
10007         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10008     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10009       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10010         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10011             << LHSArgDecl;
10012     }
10013
10014     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10015   }
10016 }
10017
10018 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10019                                                ExprResult &RHS,
10020                                                SourceLocation Loc, bool IsDiv) {
10021   // Check for division/remainder by zero.
10022   Expr::EvalResult RHSValue;
10023   if (!RHS.get()->isValueDependent() &&
10024       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10025       RHSValue.Val.getInt() == 0)
10026     S.DiagRuntimeBehavior(Loc, RHS.get(),
10027                           S.PDiag(diag::warn_remainder_division_by_zero)
10028                             << IsDiv << RHS.get()->getSourceRange());
10029 }
10030
10031 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10032                                            SourceLocation Loc,
10033                                            bool IsCompAssign, bool IsDiv) {
10034   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10035
10036   if (LHS.get()->getType()->isVectorType() ||
10037       RHS.get()->getType()->isVectorType())
10038     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10039                                /*AllowBothBool*/getLangOpts().AltiVec,
10040                                /*AllowBoolConversions*/false);
10041   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10042                  RHS.get()->getType()->isConstantMatrixType()))
10043     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10044
10045   QualType compType = UsualArithmeticConversions(
10046       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10047   if (LHS.isInvalid() || RHS.isInvalid())
10048     return QualType();
10049
10050
10051   if (compType.isNull() || !compType->isArithmeticType())
10052     return InvalidOperands(Loc, LHS, RHS);
10053   if (IsDiv) {
10054     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10055     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10056   }
10057   return compType;
10058 }
10059
10060 QualType Sema::CheckRemainderOperands(
10061   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10062   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10063
10064   if (LHS.get()->getType()->isVectorType() ||
10065       RHS.get()->getType()->isVectorType()) {
10066     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10067         RHS.get()->getType()->hasIntegerRepresentation())
10068       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10069                                  /*AllowBothBool*/getLangOpts().AltiVec,
10070                                  /*AllowBoolConversions*/false);
10071     return InvalidOperands(Loc, LHS, RHS);
10072   }
10073
10074   QualType compType = UsualArithmeticConversions(
10075       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10076   if (LHS.isInvalid() || RHS.isInvalid())
10077     return QualType();
10078
10079   if (compType.isNull() || !compType->isIntegerType())
10080     return InvalidOperands(Loc, LHS, RHS);
10081   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10082   return compType;
10083 }
10084
10085 /// Diagnose invalid arithmetic on two void pointers.
10086 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10087                                                 Expr *LHSExpr, Expr *RHSExpr) {
10088   S.Diag(Loc, S.getLangOpts().CPlusPlus
10089                 ? diag::err_typecheck_pointer_arith_void_type
10090                 : diag::ext_gnu_void_ptr)
10091     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10092                             << RHSExpr->getSourceRange();
10093 }
10094
10095 /// Diagnose invalid arithmetic on a void pointer.
10096 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10097                                             Expr *Pointer) {
10098   S.Diag(Loc, S.getLangOpts().CPlusPlus
10099                 ? diag::err_typecheck_pointer_arith_void_type
10100                 : diag::ext_gnu_void_ptr)
10101     << 0 /* one pointer */ << Pointer->getSourceRange();
10102 }
10103
10104 /// Diagnose invalid arithmetic on a null pointer.
10105 ///
10106 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10107 /// idiom, which we recognize as a GNU extension.
10108 ///
10109 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10110                                             Expr *Pointer, bool IsGNUIdiom) {
10111   if (IsGNUIdiom)
10112     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10113       << Pointer->getSourceRange();
10114   else
10115     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10116       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10117 }
10118
10119 /// Diagnose invalid arithmetic on two function pointers.
10120 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10121                                                     Expr *LHS, Expr *RHS) {
10122   assert(LHS->getType()->isAnyPointerType());
10123   assert(RHS->getType()->isAnyPointerType());
10124   S.Diag(Loc, S.getLangOpts().CPlusPlus
10125                 ? diag::err_typecheck_pointer_arith_function_type
10126                 : diag::ext_gnu_ptr_func_arith)
10127     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10128     // We only show the second type if it differs from the first.
10129     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10130                                                    RHS->getType())
10131     << RHS->getType()->getPointeeType()
10132     << LHS->getSourceRange() << RHS->getSourceRange();
10133 }
10134
10135 /// Diagnose invalid arithmetic on a function pointer.
10136 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10137                                                 Expr *Pointer) {
10138   assert(Pointer->getType()->isAnyPointerType());
10139   S.Diag(Loc, S.getLangOpts().CPlusPlus
10140                 ? diag::err_typecheck_pointer_arith_function_type
10141                 : diag::ext_gnu_ptr_func_arith)
10142     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10143     << 0 /* one pointer, so only one type */
10144     << Pointer->getSourceRange();
10145 }
10146
10147 /// Emit error if Operand is incomplete pointer type
10148 ///
10149 /// \returns True if pointer has incomplete type
10150 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10151                                                  Expr *Operand) {
10152   QualType ResType = Operand->getType();
10153   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10154     ResType = ResAtomicType->getValueType();
10155
10156   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10157   QualType PointeeTy = ResType->getPointeeType();
10158   return S.RequireCompleteSizedType(
10159       Loc, PointeeTy,
10160       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10161       Operand->getSourceRange());
10162 }
10163
10164 /// Check the validity of an arithmetic pointer operand.
10165 ///
10166 /// If the operand has pointer type, this code will check for pointer types
10167 /// which are invalid in arithmetic operations. These will be diagnosed
10168 /// appropriately, including whether or not the use is supported as an
10169 /// extension.
10170 ///
10171 /// \returns True when the operand is valid to use (even if as an extension).
10172 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10173                                             Expr *Operand) {
10174   QualType ResType = Operand->getType();
10175   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10176     ResType = ResAtomicType->getValueType();
10177
10178   if (!ResType->isAnyPointerType()) return true;
10179
10180   QualType PointeeTy = ResType->getPointeeType();
10181   if (PointeeTy->isVoidType()) {
10182     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10183     return !S.getLangOpts().CPlusPlus;
10184   }
10185   if (PointeeTy->isFunctionType()) {
10186     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10187     return !S.getLangOpts().CPlusPlus;
10188   }
10189
10190   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10191
10192   return true;
10193 }
10194
10195 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10196 /// operands.
10197 ///
10198 /// This routine will diagnose any invalid arithmetic on pointer operands much
10199 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10200 /// for emitting a single diagnostic even for operations where both LHS and RHS
10201 /// are (potentially problematic) pointers.
10202 ///
10203 /// \returns True when the operand is valid to use (even if as an extension).
10204 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10205                                                 Expr *LHSExpr, Expr *RHSExpr) {
10206   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10207   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10208   if (!isLHSPointer && !isRHSPointer) return true;
10209
10210   QualType LHSPointeeTy, RHSPointeeTy;
10211   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10212   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10213
10214   // if both are pointers check if operation is valid wrt address spaces
10215   if (isLHSPointer && isRHSPointer) {
10216     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10217       S.Diag(Loc,
10218              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10219           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10220           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10221       return false;
10222     }
10223   }
10224
10225   // Check for arithmetic on pointers to incomplete types.
10226   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10227   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10228   if (isLHSVoidPtr || isRHSVoidPtr) {
10229     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10230     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10231     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10232
10233     return !S.getLangOpts().CPlusPlus;
10234   }
10235
10236   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10237   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10238   if (isLHSFuncPtr || isRHSFuncPtr) {
10239     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10240     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10241                                                                 RHSExpr);
10242     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10243
10244     return !S.getLangOpts().CPlusPlus;
10245   }
10246
10247   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10248     return false;
10249   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10250     return false;
10251
10252   return true;
10253 }
10254
10255 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10256 /// literal.
10257 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10258                                   Expr *LHSExpr, Expr *RHSExpr) {
10259   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10260   Expr* IndexExpr = RHSExpr;
10261   if (!StrExpr) {
10262     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10263     IndexExpr = LHSExpr;
10264   }
10265
10266   bool IsStringPlusInt = StrExpr &&
10267       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10268   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10269     return;
10270
10271   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10272   Self.Diag(OpLoc, diag::warn_string_plus_int)
10273       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10274
10275   // Only print a fixit for "str" + int, not for int + "str".
10276   if (IndexExpr == RHSExpr) {
10277     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10278     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10279         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10280         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10281         << FixItHint::CreateInsertion(EndLoc, "]");
10282   } else
10283     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10284 }
10285
10286 /// Emit a warning when adding a char literal to a string.
10287 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10288                                    Expr *LHSExpr, Expr *RHSExpr) {
10289   const Expr *StringRefExpr = LHSExpr;
10290   const CharacterLiteral *CharExpr =
10291       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10292
10293   if (!CharExpr) {
10294     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10295     StringRefExpr = RHSExpr;
10296   }
10297
10298   if (!CharExpr || !StringRefExpr)
10299     return;
10300
10301   const QualType StringType = StringRefExpr->getType();
10302
10303   // Return if not a PointerType.
10304   if (!StringType->isAnyPointerType())
10305     return;
10306
10307   // Return if not a CharacterType.
10308   if (!StringType->getPointeeType()->isAnyCharacterType())
10309     return;
10310
10311   ASTContext &Ctx = Self.getASTContext();
10312   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10313
10314   const QualType CharType = CharExpr->getType();
10315   if (!CharType->isAnyCharacterType() &&
10316       CharType->isIntegerType() &&
10317       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10318     Self.Diag(OpLoc, diag::warn_string_plus_char)
10319         << DiagRange << Ctx.CharTy;
10320   } else {
10321     Self.Diag(OpLoc, diag::warn_string_plus_char)
10322         << DiagRange << CharExpr->getType();
10323   }
10324
10325   // Only print a fixit for str + char, not for char + str.
10326   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10327     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10328     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10329         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10330         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10331         << FixItHint::CreateInsertion(EndLoc, "]");
10332   } else {
10333     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10334   }
10335 }
10336
10337 /// Emit error when two pointers are incompatible.
10338 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10339                                            Expr *LHSExpr, Expr *RHSExpr) {
10340   assert(LHSExpr->getType()->isAnyPointerType());
10341   assert(RHSExpr->getType()->isAnyPointerType());
10342   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10343     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10344     << RHSExpr->getSourceRange();
10345 }
10346
10347 // C99 6.5.6
10348 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10349                                      SourceLocation Loc, BinaryOperatorKind Opc,
10350                                      QualType* CompLHSTy) {
10351   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10352
10353   if (LHS.get()->getType()->isVectorType() ||
10354       RHS.get()->getType()->isVectorType()) {
10355     QualType compType = CheckVectorOperands(
10356         LHS, RHS, Loc, CompLHSTy,
10357         /*AllowBothBool*/getLangOpts().AltiVec,
10358         /*AllowBoolConversions*/getLangOpts().ZVector);
10359     if (CompLHSTy) *CompLHSTy = compType;
10360     return compType;
10361   }
10362
10363   if (LHS.get()->getType()->isConstantMatrixType() ||
10364       RHS.get()->getType()->isConstantMatrixType()) {
10365     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10366   }
10367
10368   QualType compType = UsualArithmeticConversions(
10369       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10370   if (LHS.isInvalid() || RHS.isInvalid())
10371     return QualType();
10372
10373   // Diagnose "string literal" '+' int and string '+' "char literal".
10374   if (Opc == BO_Add) {
10375     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10376     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10377   }
10378
10379   // handle the common case first (both operands are arithmetic).
10380   if (!compType.isNull() && compType->isArithmeticType()) {
10381     if (CompLHSTy) *CompLHSTy = compType;
10382     return compType;
10383   }
10384
10385   // Type-checking.  Ultimately the pointer's going to be in PExp;
10386   // note that we bias towards the LHS being the pointer.
10387   Expr *PExp = LHS.get(), *IExp = RHS.get();
10388
10389   bool isObjCPointer;
10390   if (PExp->getType()->isPointerType()) {
10391     isObjCPointer = false;
10392   } else if (PExp->getType()->isObjCObjectPointerType()) {
10393     isObjCPointer = true;
10394   } else {
10395     std::swap(PExp, IExp);
10396     if (PExp->getType()->isPointerType()) {
10397       isObjCPointer = false;
10398     } else if (PExp->getType()->isObjCObjectPointerType()) {
10399       isObjCPointer = true;
10400     } else {
10401       return InvalidOperands(Loc, LHS, RHS);
10402     }
10403   }
10404   assert(PExp->getType()->isAnyPointerType());
10405
10406   if (!IExp->getType()->isIntegerType())
10407     return InvalidOperands(Loc, LHS, RHS);
10408
10409   // Adding to a null pointer results in undefined behavior.
10410   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10411           Context, Expr::NPC_ValueDependentIsNotNull)) {
10412     // In C++ adding zero to a null pointer is defined.
10413     Expr::EvalResult KnownVal;
10414     if (!getLangOpts().CPlusPlus ||
10415         (!IExp->isValueDependent() &&
10416          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10417           KnownVal.Val.getInt() != 0))) {
10418       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10419       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10420           Context, BO_Add, PExp, IExp);
10421       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10422     }
10423   }
10424
10425   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10426     return QualType();
10427
10428   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10429     return QualType();
10430
10431   // Check array bounds for pointer arithemtic
10432   CheckArrayAccess(PExp, IExp);
10433
10434   if (CompLHSTy) {
10435     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10436     if (LHSTy.isNull()) {
10437       LHSTy = LHS.get()->getType();
10438       if (LHSTy->isPromotableIntegerType())
10439         LHSTy = Context.getPromotedIntegerType(LHSTy);
10440     }
10441     *CompLHSTy = LHSTy;
10442   }
10443
10444   return PExp->getType();
10445 }
10446
10447 // C99 6.5.6
10448 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10449                                         SourceLocation Loc,
10450                                         QualType* CompLHSTy) {
10451   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10452
10453   if (LHS.get()->getType()->isVectorType() ||
10454       RHS.get()->getType()->isVectorType()) {
10455     QualType compType = CheckVectorOperands(
10456         LHS, RHS, Loc, CompLHSTy,
10457         /*AllowBothBool*/getLangOpts().AltiVec,
10458         /*AllowBoolConversions*/getLangOpts().ZVector);
10459     if (CompLHSTy) *CompLHSTy = compType;
10460     return compType;
10461   }
10462
10463   if (LHS.get()->getType()->isConstantMatrixType() ||
10464       RHS.get()->getType()->isConstantMatrixType()) {
10465     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10466   }
10467
10468   QualType compType = UsualArithmeticConversions(
10469       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10470   if (LHS.isInvalid() || RHS.isInvalid())
10471     return QualType();
10472
10473   // Enforce type constraints: C99 6.5.6p3.
10474
10475   // Handle the common case first (both operands are arithmetic).
10476   if (!compType.isNull() && compType->isArithmeticType()) {
10477     if (CompLHSTy) *CompLHSTy = compType;
10478     return compType;
10479   }
10480
10481   // Either ptr - int   or   ptr - ptr.
10482   if (LHS.get()->getType()->isAnyPointerType()) {
10483     QualType lpointee = LHS.get()->getType()->getPointeeType();
10484
10485     // Diagnose bad cases where we step over interface counts.
10486     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10487         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10488       return QualType();
10489
10490     // The result type of a pointer-int computation is the pointer type.
10491     if (RHS.get()->getType()->isIntegerType()) {
10492       // Subtracting from a null pointer should produce a warning.
10493       // The last argument to the diagnose call says this doesn't match the
10494       // GNU int-to-pointer idiom.
10495       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10496                                            Expr::NPC_ValueDependentIsNotNull)) {
10497         // In C++ adding zero to a null pointer is defined.
10498         Expr::EvalResult KnownVal;
10499         if (!getLangOpts().CPlusPlus ||
10500             (!RHS.get()->isValueDependent() &&
10501              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10502               KnownVal.Val.getInt() != 0))) {
10503           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10504         }
10505       }
10506
10507       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10508         return QualType();
10509
10510       // Check array bounds for pointer arithemtic
10511       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10512                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10513
10514       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10515       return LHS.get()->getType();
10516     }
10517
10518     // Handle pointer-pointer subtractions.
10519     if (const PointerType *RHSPTy
10520           = RHS.get()->getType()->getAs<PointerType>()) {
10521       QualType rpointee = RHSPTy->getPointeeType();
10522
10523       if (getLangOpts().CPlusPlus) {
10524         // Pointee types must be the same: C++ [expr.add]
10525         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10526           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10527         }
10528       } else {
10529         // Pointee types must be compatible C99 6.5.6p3
10530         if (!Context.typesAreCompatible(
10531                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10532                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10533           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10534           return QualType();
10535         }
10536       }
10537
10538       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10539                                                LHS.get(), RHS.get()))
10540         return QualType();
10541
10542       // FIXME: Add warnings for nullptr - ptr.
10543
10544       // The pointee type may have zero size.  As an extension, a structure or
10545       // union may have zero size or an array may have zero length.  In this
10546       // case subtraction does not make sense.
10547       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10548         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10549         if (ElementSize.isZero()) {
10550           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10551             << rpointee.getUnqualifiedType()
10552             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10553         }
10554       }
10555
10556       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10557       return Context.getPointerDiffType();
10558     }
10559   }
10560
10561   return InvalidOperands(Loc, LHS, RHS);
10562 }
10563
10564 static bool isScopedEnumerationType(QualType T) {
10565   if (const EnumType *ET = T->getAs<EnumType>())
10566     return ET->getDecl()->isScoped();
10567   return false;
10568 }
10569
10570 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10571                                    SourceLocation Loc, BinaryOperatorKind Opc,
10572                                    QualType LHSType) {
10573   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10574   // so skip remaining warnings as we don't want to modify values within Sema.
10575   if (S.getLangOpts().OpenCL)
10576     return;
10577
10578   // Check right/shifter operand
10579   Expr::EvalResult RHSResult;
10580   if (RHS.get()->isValueDependent() ||
10581       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10582     return;
10583   llvm::APSInt Right = RHSResult.Val.getInt();
10584
10585   if (Right.isNegative()) {
10586     S.DiagRuntimeBehavior(Loc, RHS.get(),
10587                           S.PDiag(diag::warn_shift_negative)
10588                             << RHS.get()->getSourceRange());
10589     return;
10590   }
10591
10592   QualType LHSExprType = LHS.get()->getType();
10593   uint64_t LeftSize = LHSExprType->isExtIntType()
10594                           ? S.Context.getIntWidth(LHSExprType)
10595                           : S.Context.getTypeSize(LHSExprType);
10596   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10597   if (Right.uge(LeftBits)) {
10598     S.DiagRuntimeBehavior(Loc, RHS.get(),
10599                           S.PDiag(diag::warn_shift_gt_typewidth)
10600                             << RHS.get()->getSourceRange());
10601     return;
10602   }
10603
10604   if (Opc != BO_Shl)
10605     return;
10606
10607   // When left shifting an ICE which is signed, we can check for overflow which
10608   // according to C++ standards prior to C++2a has undefined behavior
10609   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10610   // more than the maximum value representable in the result type, so never
10611   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10612   // expression is still probably a bug.)
10613   Expr::EvalResult LHSResult;
10614   if (LHS.get()->isValueDependent() ||
10615       LHSType->hasUnsignedIntegerRepresentation() ||
10616       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10617     return;
10618   llvm::APSInt Left = LHSResult.Val.getInt();
10619
10620   // If LHS does not have a signed type and non-negative value
10621   // then, the behavior is undefined before C++2a. Warn about it.
10622   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10623       !S.getLangOpts().CPlusPlus20) {
10624     S.DiagRuntimeBehavior(Loc, LHS.get(),
10625                           S.PDiag(diag::warn_shift_lhs_negative)
10626                             << LHS.get()->getSourceRange());
10627     return;
10628   }
10629
10630   llvm::APInt ResultBits =
10631       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10632   if (LeftBits.uge(ResultBits))
10633     return;
10634   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10635   Result = Result.shl(Right);
10636
10637   // Print the bit representation of the signed integer as an unsigned
10638   // hexadecimal number.
10639   SmallString<40> HexResult;
10640   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10641
10642   // If we are only missing a sign bit, this is less likely to result in actual
10643   // bugs -- if the result is cast back to an unsigned type, it will have the
10644   // expected value. Thus we place this behind a different warning that can be
10645   // turned off separately if needed.
10646   if (LeftBits == ResultBits - 1) {
10647     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10648         << HexResult << LHSType
10649         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10650     return;
10651   }
10652
10653   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10654     << HexResult.str() << Result.getMinSignedBits() << LHSType
10655     << Left.getBitWidth() << LHS.get()->getSourceRange()
10656     << RHS.get()->getSourceRange();
10657 }
10658
10659 /// Return the resulting type when a vector is shifted
10660 ///        by a scalar or vector shift amount.
10661 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10662                                  SourceLocation Loc, bool IsCompAssign) {
10663   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10664   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10665       !LHS.get()->getType()->isVectorType()) {
10666     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10667       << RHS.get()->getType() << LHS.get()->getType()
10668       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10669     return QualType();
10670   }
10671
10672   if (!IsCompAssign) {
10673     LHS = S.UsualUnaryConversions(LHS.get());
10674     if (LHS.isInvalid()) return QualType();
10675   }
10676
10677   RHS = S.UsualUnaryConversions(RHS.get());
10678   if (RHS.isInvalid()) return QualType();
10679
10680   QualType LHSType = LHS.get()->getType();
10681   // Note that LHS might be a scalar because the routine calls not only in
10682   // OpenCL case.
10683   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10684   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10685
10686   // Note that RHS might not be a vector.
10687   QualType RHSType = RHS.get()->getType();
10688   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10689   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10690
10691   // The operands need to be integers.
10692   if (!LHSEleType->isIntegerType()) {
10693     S.Diag(Loc, diag::err_typecheck_expect_int)
10694       << LHS.get()->getType() << LHS.get()->getSourceRange();
10695     return QualType();
10696   }
10697
10698   if (!RHSEleType->isIntegerType()) {
10699     S.Diag(Loc, diag::err_typecheck_expect_int)
10700       << RHS.get()->getType() << RHS.get()->getSourceRange();
10701     return QualType();
10702   }
10703
10704   if (!LHSVecTy) {
10705     assert(RHSVecTy);
10706     if (IsCompAssign)
10707       return RHSType;
10708     if (LHSEleType != RHSEleType) {
10709       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10710       LHSEleType = RHSEleType;
10711     }
10712     QualType VecTy =
10713         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10714     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10715     LHSType = VecTy;
10716   } else if (RHSVecTy) {
10717     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10718     // are applied component-wise. So if RHS is a vector, then ensure
10719     // that the number of elements is the same as LHS...
10720     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10721       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10722         << LHS.get()->getType() << RHS.get()->getType()
10723         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10724       return QualType();
10725     }
10726     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10727       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10728       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10729       if (LHSBT != RHSBT &&
10730           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10731         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10732             << LHS.get()->getType() << RHS.get()->getType()
10733             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10734       }
10735     }
10736   } else {
10737     // ...else expand RHS to match the number of elements in LHS.
10738     QualType VecTy =
10739       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10740     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10741   }
10742
10743   return LHSType;
10744 }
10745
10746 // C99 6.5.7
10747 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10748                                   SourceLocation Loc, BinaryOperatorKind Opc,
10749                                   bool IsCompAssign) {
10750   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10751
10752   // Vector shifts promote their scalar inputs to vector type.
10753   if (LHS.get()->getType()->isVectorType() ||
10754       RHS.get()->getType()->isVectorType()) {
10755     if (LangOpts.ZVector) {
10756       // The shift operators for the z vector extensions work basically
10757       // like general shifts, except that neither the LHS nor the RHS is
10758       // allowed to be a "vector bool".
10759       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10760         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10761           return InvalidOperands(Loc, LHS, RHS);
10762       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10763         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10764           return InvalidOperands(Loc, LHS, RHS);
10765     }
10766     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10767   }
10768
10769   // Shifts don't perform usual arithmetic conversions, they just do integer
10770   // promotions on each operand. C99 6.5.7p3
10771
10772   // For the LHS, do usual unary conversions, but then reset them away
10773   // if this is a compound assignment.
10774   ExprResult OldLHS = LHS;
10775   LHS = UsualUnaryConversions(LHS.get());
10776   if (LHS.isInvalid())
10777     return QualType();
10778   QualType LHSType = LHS.get()->getType();
10779   if (IsCompAssign) LHS = OldLHS;
10780
10781   // The RHS is simpler.
10782   RHS = UsualUnaryConversions(RHS.get());
10783   if (RHS.isInvalid())
10784     return QualType();
10785   QualType RHSType = RHS.get()->getType();
10786
10787   // C99 6.5.7p2: Each of the operands shall have integer type.
10788   if (!LHSType->hasIntegerRepresentation() ||
10789       !RHSType->hasIntegerRepresentation())
10790     return InvalidOperands(Loc, LHS, RHS);
10791
10792   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10793   // hasIntegerRepresentation() above instead of this.
10794   if (isScopedEnumerationType(LHSType) ||
10795       isScopedEnumerationType(RHSType)) {
10796     return InvalidOperands(Loc, LHS, RHS);
10797   }
10798   // Sanity-check shift operands
10799   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10800
10801   // "The type of the result is that of the promoted left operand."
10802   return LHSType;
10803 }
10804
10805 /// Diagnose bad pointer comparisons.
10806 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10807                                               ExprResult &LHS, ExprResult &RHS,
10808                                               bool IsError) {
10809   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10810                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10811     << LHS.get()->getType() << RHS.get()->getType()
10812     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10813 }
10814
10815 /// Returns false if the pointers are converted to a composite type,
10816 /// true otherwise.
10817 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10818                                            ExprResult &LHS, ExprResult &RHS) {
10819   // C++ [expr.rel]p2:
10820   //   [...] Pointer conversions (4.10) and qualification
10821   //   conversions (4.4) are performed on pointer operands (or on
10822   //   a pointer operand and a null pointer constant) to bring
10823   //   them to their composite pointer type. [...]
10824   //
10825   // C++ [expr.eq]p1 uses the same notion for (in)equality
10826   // comparisons of pointers.
10827
10828   QualType LHSType = LHS.get()->getType();
10829   QualType RHSType = RHS.get()->getType();
10830   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10831          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10832
10833   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10834   if (T.isNull()) {
10835     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10836         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10837       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10838     else
10839       S.InvalidOperands(Loc, LHS, RHS);
10840     return true;
10841   }
10842
10843   return false;
10844 }
10845
10846 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10847                                                     ExprResult &LHS,
10848                                                     ExprResult &RHS,
10849                                                     bool IsError) {
10850   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10851                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10852     << LHS.get()->getType() << RHS.get()->getType()
10853     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10854 }
10855
10856 static bool isObjCObjectLiteral(ExprResult &E) {
10857   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10858   case Stmt::ObjCArrayLiteralClass:
10859   case Stmt::ObjCDictionaryLiteralClass:
10860   case Stmt::ObjCStringLiteralClass:
10861   case Stmt::ObjCBoxedExprClass:
10862     return true;
10863   default:
10864     // Note that ObjCBoolLiteral is NOT an object literal!
10865     return false;
10866   }
10867 }
10868
10869 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10870   const ObjCObjectPointerType *Type =
10871     LHS->getType()->getAs<ObjCObjectPointerType>();
10872
10873   // If this is not actually an Objective-C object, bail out.
10874   if (!Type)
10875     return false;
10876
10877   // Get the LHS object's interface type.
10878   QualType InterfaceType = Type->getPointeeType();
10879
10880   // If the RHS isn't an Objective-C object, bail out.
10881   if (!RHS->getType()->isObjCObjectPointerType())
10882     return false;
10883
10884   // Try to find the -isEqual: method.
10885   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10886   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10887                                                       InterfaceType,
10888                                                       /*IsInstance=*/true);
10889   if (!Method) {
10890     if (Type->isObjCIdType()) {
10891       // For 'id', just check the global pool.
10892       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10893                                                   /*receiverId=*/true);
10894     } else {
10895       // Check protocols.
10896       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10897                                              /*IsInstance=*/true);
10898     }
10899   }
10900
10901   if (!Method)
10902     return false;
10903
10904   QualType T = Method->parameters()[0]->getType();
10905   if (!T->isObjCObjectPointerType())
10906     return false;
10907
10908   QualType R = Method->getReturnType();
10909   if (!R->isScalarType())
10910     return false;
10911
10912   return true;
10913 }
10914
10915 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10916   FromE = FromE->IgnoreParenImpCasts();
10917   switch (FromE->getStmtClass()) {
10918     default:
10919       break;
10920     case Stmt::ObjCStringLiteralClass:
10921       // "string literal"
10922       return LK_String;
10923     case Stmt::ObjCArrayLiteralClass:
10924       // "array literal"
10925       return LK_Array;
10926     case Stmt::ObjCDictionaryLiteralClass:
10927       // "dictionary literal"
10928       return LK_Dictionary;
10929     case Stmt::BlockExprClass:
10930       return LK_Block;
10931     case Stmt::ObjCBoxedExprClass: {
10932       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10933       switch (Inner->getStmtClass()) {
10934         case Stmt::IntegerLiteralClass:
10935         case Stmt::FloatingLiteralClass:
10936         case Stmt::CharacterLiteralClass:
10937         case Stmt::ObjCBoolLiteralExprClass:
10938         case Stmt::CXXBoolLiteralExprClass:
10939           // "numeric literal"
10940           return LK_Numeric;
10941         case Stmt::ImplicitCastExprClass: {
10942           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10943           // Boolean literals can be represented by implicit casts.
10944           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10945             return LK_Numeric;
10946           break;
10947         }
10948         default:
10949           break;
10950       }
10951       return LK_Boxed;
10952     }
10953   }
10954   return LK_None;
10955 }
10956
10957 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10958                                           ExprResult &LHS, ExprResult &RHS,
10959                                           BinaryOperator::Opcode Opc){
10960   Expr *Literal;
10961   Expr *Other;
10962   if (isObjCObjectLiteral(LHS)) {
10963     Literal = LHS.get();
10964     Other = RHS.get();
10965   } else {
10966     Literal = RHS.get();
10967     Other = LHS.get();
10968   }
10969
10970   // Don't warn on comparisons against nil.
10971   Other = Other->IgnoreParenCasts();
10972   if (Other->isNullPointerConstant(S.getASTContext(),
10973                                    Expr::NPC_ValueDependentIsNotNull))
10974     return;
10975
10976   // This should be kept in sync with warn_objc_literal_comparison.
10977   // LK_String should always be after the other literals, since it has its own
10978   // warning flag.
10979   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10980   assert(LiteralKind != Sema::LK_Block);
10981   if (LiteralKind == Sema::LK_None) {
10982     llvm_unreachable("Unknown Objective-C object literal kind");
10983   }
10984
10985   if (LiteralKind == Sema::LK_String)
10986     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10987       << Literal->getSourceRange();
10988   else
10989     S.Diag(Loc, diag::warn_objc_literal_comparison)
10990       << LiteralKind << Literal->getSourceRange();
10991
10992   if (BinaryOperator::isEqualityOp(Opc) &&
10993       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10994     SourceLocation Start = LHS.get()->getBeginLoc();
10995     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10996     CharSourceRange OpRange =
10997       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10998
10999     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11000       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11001       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11002       << FixItHint::CreateInsertion(End, "]");
11003   }
11004 }
11005
11006 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11007 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11008                                            ExprResult &RHS, SourceLocation Loc,
11009                                            BinaryOperatorKind Opc) {
11010   // Check that left hand side is !something.
11011   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11012   if (!UO || UO->getOpcode() != UO_LNot) return;
11013
11014   // Only check if the right hand side is non-bool arithmetic type.
11015   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11016
11017   // Make sure that the something in !something is not bool.
11018   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11019   if (SubExpr->isKnownToHaveBooleanValue()) return;
11020
11021   // Emit warning.
11022   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11023   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11024       << Loc << IsBitwiseOp;
11025
11026   // First note suggest !(x < y)
11027   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11028   SourceLocation FirstClose = RHS.get()->getEndLoc();
11029   FirstClose = S.getLocForEndOfToken(FirstClose);
11030   if (FirstClose.isInvalid())
11031     FirstOpen = SourceLocation();
11032   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11033       << IsBitwiseOp
11034       << FixItHint::CreateInsertion(FirstOpen, "(")
11035       << FixItHint::CreateInsertion(FirstClose, ")");
11036
11037   // Second note suggests (!x) < y
11038   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11039   SourceLocation SecondClose = LHS.get()->getEndLoc();
11040   SecondClose = S.getLocForEndOfToken(SecondClose);
11041   if (SecondClose.isInvalid())
11042     SecondOpen = SourceLocation();
11043   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11044       << FixItHint::CreateInsertion(SecondOpen, "(")
11045       << FixItHint::CreateInsertion(SecondClose, ")");
11046 }
11047
11048 // Returns true if E refers to a non-weak array.
11049 static bool checkForArray(const Expr *E) {
11050   const ValueDecl *D = nullptr;
11051   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11052     D = DR->getDecl();
11053   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11054     if (Mem->isImplicitAccess())
11055       D = Mem->getMemberDecl();
11056   }
11057   if (!D)
11058     return false;
11059   return D->getType()->isArrayType() && !D->isWeak();
11060 }
11061
11062 /// Diagnose some forms of syntactically-obvious tautological comparison.
11063 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11064                                            Expr *LHS, Expr *RHS,
11065                                            BinaryOperatorKind Opc) {
11066   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11067   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11068
11069   QualType LHSType = LHS->getType();
11070   QualType RHSType = RHS->getType();
11071   if (LHSType->hasFloatingRepresentation() ||
11072       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11073       S.inTemplateInstantiation())
11074     return;
11075
11076   // Comparisons between two array types are ill-formed for operator<=>, so
11077   // we shouldn't emit any additional warnings about it.
11078   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11079     return;
11080
11081   // For non-floating point types, check for self-comparisons of the form
11082   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11083   // often indicate logic errors in the program.
11084   //
11085   // NOTE: Don't warn about comparison expressions resulting from macro
11086   // expansion. Also don't warn about comparisons which are only self
11087   // comparisons within a template instantiation. The warnings should catch
11088   // obvious cases in the definition of the template anyways. The idea is to
11089   // warn when the typed comparison operator will always evaluate to the same
11090   // result.
11091
11092   // Used for indexing into %select in warn_comparison_always
11093   enum {
11094     AlwaysConstant,
11095     AlwaysTrue,
11096     AlwaysFalse,
11097     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11098   };
11099
11100   // C++2a [depr.array.comp]:
11101   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11102   //   operands of array type are deprecated.
11103   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11104       RHSStripped->getType()->isArrayType()) {
11105     S.Diag(Loc, diag::warn_depr_array_comparison)
11106         << LHS->getSourceRange() << RHS->getSourceRange()
11107         << LHSStripped->getType() << RHSStripped->getType();
11108     // Carry on to produce the tautological comparison warning, if this
11109     // expression is potentially-evaluated, we can resolve the array to a
11110     // non-weak declaration, and so on.
11111   }
11112
11113   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11114     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11115       unsigned Result;
11116       switch (Opc) {
11117       case BO_EQ:
11118       case BO_LE:
11119       case BO_GE:
11120         Result = AlwaysTrue;
11121         break;
11122       case BO_NE:
11123       case BO_LT:
11124       case BO_GT:
11125         Result = AlwaysFalse;
11126         break;
11127       case BO_Cmp:
11128         Result = AlwaysEqual;
11129         break;
11130       default:
11131         Result = AlwaysConstant;
11132         break;
11133       }
11134       S.DiagRuntimeBehavior(Loc, nullptr,
11135                             S.PDiag(diag::warn_comparison_always)
11136                                 << 0 /*self-comparison*/
11137                                 << Result);
11138     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11139       // What is it always going to evaluate to?
11140       unsigned Result;
11141       switch (Opc) {
11142       case BO_EQ: // e.g. array1 == array2
11143         Result = AlwaysFalse;
11144         break;
11145       case BO_NE: // e.g. array1 != array2
11146         Result = AlwaysTrue;
11147         break;
11148       default: // e.g. array1 <= array2
11149         // The best we can say is 'a constant'
11150         Result = AlwaysConstant;
11151         break;
11152       }
11153       S.DiagRuntimeBehavior(Loc, nullptr,
11154                             S.PDiag(diag::warn_comparison_always)
11155                                 << 1 /*array comparison*/
11156                                 << Result);
11157     }
11158   }
11159
11160   if (isa<CastExpr>(LHSStripped))
11161     LHSStripped = LHSStripped->IgnoreParenCasts();
11162   if (isa<CastExpr>(RHSStripped))
11163     RHSStripped = RHSStripped->IgnoreParenCasts();
11164
11165   // Warn about comparisons against a string constant (unless the other
11166   // operand is null); the user probably wants string comparison function.
11167   Expr *LiteralString = nullptr;
11168   Expr *LiteralStringStripped = nullptr;
11169   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11170       !RHSStripped->isNullPointerConstant(S.Context,
11171                                           Expr::NPC_ValueDependentIsNull)) {
11172     LiteralString = LHS;
11173     LiteralStringStripped = LHSStripped;
11174   } else if ((isa<StringLiteral>(RHSStripped) ||
11175               isa<ObjCEncodeExpr>(RHSStripped)) &&
11176              !LHSStripped->isNullPointerConstant(S.Context,
11177                                           Expr::NPC_ValueDependentIsNull)) {
11178     LiteralString = RHS;
11179     LiteralStringStripped = RHSStripped;
11180   }
11181
11182   if (LiteralString) {
11183     S.DiagRuntimeBehavior(Loc, nullptr,
11184                           S.PDiag(diag::warn_stringcompare)
11185                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11186                               << LiteralString->getSourceRange());
11187   }
11188 }
11189
11190 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11191   switch (CK) {
11192   default: {
11193 #ifndef NDEBUG
11194     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11195                  << "\n";
11196 #endif
11197     llvm_unreachable("unhandled cast kind");
11198   }
11199   case CK_UserDefinedConversion:
11200     return ICK_Identity;
11201   case CK_LValueToRValue:
11202     return ICK_Lvalue_To_Rvalue;
11203   case CK_ArrayToPointerDecay:
11204     return ICK_Array_To_Pointer;
11205   case CK_FunctionToPointerDecay:
11206     return ICK_Function_To_Pointer;
11207   case CK_IntegralCast:
11208     return ICK_Integral_Conversion;
11209   case CK_FloatingCast:
11210     return ICK_Floating_Conversion;
11211   case CK_IntegralToFloating:
11212   case CK_FloatingToIntegral:
11213     return ICK_Floating_Integral;
11214   case CK_IntegralComplexCast:
11215   case CK_FloatingComplexCast:
11216   case CK_FloatingComplexToIntegralComplex:
11217   case CK_IntegralComplexToFloatingComplex:
11218     return ICK_Complex_Conversion;
11219   case CK_FloatingComplexToReal:
11220   case CK_FloatingRealToComplex:
11221   case CK_IntegralComplexToReal:
11222   case CK_IntegralRealToComplex:
11223     return ICK_Complex_Real;
11224   }
11225 }
11226
11227 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11228                                              QualType FromType,
11229                                              SourceLocation Loc) {
11230   // Check for a narrowing implicit conversion.
11231   StandardConversionSequence SCS;
11232   SCS.setAsIdentityConversion();
11233   SCS.setToType(0, FromType);
11234   SCS.setToType(1, ToType);
11235   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11236     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11237
11238   APValue PreNarrowingValue;
11239   QualType PreNarrowingType;
11240   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11241                                PreNarrowingType,
11242                                /*IgnoreFloatToIntegralConversion*/ true)) {
11243   case NK_Dependent_Narrowing:
11244     // Implicit conversion to a narrower type, but the expression is
11245     // value-dependent so we can't tell whether it's actually narrowing.
11246   case NK_Not_Narrowing:
11247     return false;
11248
11249   case NK_Constant_Narrowing:
11250     // Implicit conversion to a narrower type, and the value is not a constant
11251     // expression.
11252     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11253         << /*Constant*/ 1
11254         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11255     return true;
11256
11257   case NK_Variable_Narrowing:
11258     // Implicit conversion to a narrower type, and the value is not a constant
11259     // expression.
11260   case NK_Type_Narrowing:
11261     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11262         << /*Constant*/ 0 << FromType << ToType;
11263     // TODO: It's not a constant expression, but what if the user intended it
11264     // to be? Can we produce notes to help them figure out why it isn't?
11265     return true;
11266   }
11267   llvm_unreachable("unhandled case in switch");
11268 }
11269
11270 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11271                                                          ExprResult &LHS,
11272                                                          ExprResult &RHS,
11273                                                          SourceLocation Loc) {
11274   QualType LHSType = LHS.get()->getType();
11275   QualType RHSType = RHS.get()->getType();
11276   // Dig out the original argument type and expression before implicit casts
11277   // were applied. These are the types/expressions we need to check the
11278   // [expr.spaceship] requirements against.
11279   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11280   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11281   QualType LHSStrippedType = LHSStripped.get()->getType();
11282   QualType RHSStrippedType = RHSStripped.get()->getType();
11283
11284   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11285   // other is not, the program is ill-formed.
11286   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11287     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11288     return QualType();
11289   }
11290
11291   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11292   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11293                     RHSStrippedType->isEnumeralType();
11294   if (NumEnumArgs == 1) {
11295     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11296     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11297     if (OtherTy->hasFloatingRepresentation()) {
11298       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11299       return QualType();
11300     }
11301   }
11302   if (NumEnumArgs == 2) {
11303     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11304     // type E, the operator yields the result of converting the operands
11305     // to the underlying type of E and applying <=> to the converted operands.
11306     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11307       S.InvalidOperands(Loc, LHS, RHS);
11308       return QualType();
11309     }
11310     QualType IntType =
11311         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11312     assert(IntType->isArithmeticType());
11313
11314     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11315     // promote the boolean type, and all other promotable integer types, to
11316     // avoid this.
11317     if (IntType->isPromotableIntegerType())
11318       IntType = S.Context.getPromotedIntegerType(IntType);
11319
11320     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11321     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11322     LHSType = RHSType = IntType;
11323   }
11324
11325   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11326   // usual arithmetic conversions are applied to the operands.
11327   QualType Type =
11328       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11329   if (LHS.isInvalid() || RHS.isInvalid())
11330     return QualType();
11331   if (Type.isNull())
11332     return S.InvalidOperands(Loc, LHS, RHS);
11333
11334   Optional<ComparisonCategoryType> CCT =
11335       getComparisonCategoryForBuiltinCmp(Type);
11336   if (!CCT)
11337     return S.InvalidOperands(Loc, LHS, RHS);
11338
11339   bool HasNarrowing = checkThreeWayNarrowingConversion(
11340       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11341   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11342                                                    RHS.get()->getBeginLoc());
11343   if (HasNarrowing)
11344     return QualType();
11345
11346   assert(!Type.isNull() && "composite type for <=> has not been set");
11347
11348   return S.CheckComparisonCategoryType(
11349       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11350 }
11351
11352 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11353                                                  ExprResult &RHS,
11354                                                  SourceLocation Loc,
11355                                                  BinaryOperatorKind Opc) {
11356   if (Opc == BO_Cmp)
11357     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11358
11359   // C99 6.5.8p3 / C99 6.5.9p4
11360   QualType Type =
11361       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11362   if (LHS.isInvalid() || RHS.isInvalid())
11363     return QualType();
11364   if (Type.isNull())
11365     return S.InvalidOperands(Loc, LHS, RHS);
11366   assert(Type->isArithmeticType() || Type->isEnumeralType());
11367
11368   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11369     return S.InvalidOperands(Loc, LHS, RHS);
11370
11371   // Check for comparisons of floating point operands using != and ==.
11372   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11373     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11374
11375   // The result of comparisons is 'bool' in C++, 'int' in C.
11376   return S.Context.getLogicalOperationType();
11377 }
11378
11379 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11380   if (!NullE.get()->getType()->isAnyPointerType())
11381     return;
11382   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11383   if (!E.get()->getType()->isAnyPointerType() &&
11384       E.get()->isNullPointerConstant(Context,
11385                                      Expr::NPC_ValueDependentIsNotNull) ==
11386         Expr::NPCK_ZeroExpression) {
11387     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11388       if (CL->getValue() == 0)
11389         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11390             << NullValue
11391             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11392                                             NullValue ? "NULL" : "(void *)0");
11393     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11394         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11395         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11396         if (T == Context.CharTy)
11397           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11398               << NullValue
11399               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11400                                               NullValue ? "NULL" : "(void *)0");
11401       }
11402   }
11403 }
11404
11405 // C99 6.5.8, C++ [expr.rel]
11406 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11407                                     SourceLocation Loc,
11408                                     BinaryOperatorKind Opc) {
11409   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11410   bool IsThreeWay = Opc == BO_Cmp;
11411   bool IsOrdered = IsRelational || IsThreeWay;
11412   auto IsAnyPointerType = [](ExprResult E) {
11413     QualType Ty = E.get()->getType();
11414     return Ty->isPointerType() || Ty->isMemberPointerType();
11415   };
11416
11417   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11418   // type, array-to-pointer, ..., conversions are performed on both operands to
11419   // bring them to their composite type.
11420   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11421   // any type-related checks.
11422   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11423     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11424     if (LHS.isInvalid())
11425       return QualType();
11426     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11427     if (RHS.isInvalid())
11428       return QualType();
11429   } else {
11430     LHS = DefaultLvalueConversion(LHS.get());
11431     if (LHS.isInvalid())
11432       return QualType();
11433     RHS = DefaultLvalueConversion(RHS.get());
11434     if (RHS.isInvalid())
11435       return QualType();
11436   }
11437
11438   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11439   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11440     CheckPtrComparisonWithNullChar(LHS, RHS);
11441     CheckPtrComparisonWithNullChar(RHS, LHS);
11442   }
11443
11444   // Handle vector comparisons separately.
11445   if (LHS.get()->getType()->isVectorType() ||
11446       RHS.get()->getType()->isVectorType())
11447     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11448
11449   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11450   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11451
11452   QualType LHSType = LHS.get()->getType();
11453   QualType RHSType = RHS.get()->getType();
11454   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11455       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11456     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11457
11458   const Expr::NullPointerConstantKind LHSNullKind =
11459       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11460   const Expr::NullPointerConstantKind RHSNullKind =
11461       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11462   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11463   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11464
11465   auto computeResultTy = [&]() {
11466     if (Opc != BO_Cmp)
11467       return Context.getLogicalOperationType();
11468     assert(getLangOpts().CPlusPlus);
11469     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11470
11471     QualType CompositeTy = LHS.get()->getType();
11472     assert(!CompositeTy->isReferenceType());
11473
11474     Optional<ComparisonCategoryType> CCT =
11475         getComparisonCategoryForBuiltinCmp(CompositeTy);
11476     if (!CCT)
11477       return InvalidOperands(Loc, LHS, RHS);
11478
11479     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11480       // P0946R0: Comparisons between a null pointer constant and an object
11481       // pointer result in std::strong_equality, which is ill-formed under
11482       // P1959R0.
11483       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11484           << (LHSIsNull ? LHS.get()->getSourceRange()
11485                         : RHS.get()->getSourceRange());
11486       return QualType();
11487     }
11488
11489     return CheckComparisonCategoryType(
11490         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11491   };
11492
11493   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11494     bool IsEquality = Opc == BO_EQ;
11495     if (RHSIsNull)
11496       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11497                                    RHS.get()->getSourceRange());
11498     else
11499       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11500                                    LHS.get()->getSourceRange());
11501   }
11502
11503   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11504       (RHSType->isIntegerType() && !RHSIsNull)) {
11505     // Skip normal pointer conversion checks in this case; we have better
11506     // diagnostics for this below.
11507   } else if (getLangOpts().CPlusPlus) {
11508     // Equality comparison of a function pointer to a void pointer is invalid,
11509     // but we allow it as an extension.
11510     // FIXME: If we really want to allow this, should it be part of composite
11511     // pointer type computation so it works in conditionals too?
11512     if (!IsOrdered &&
11513         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11514          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11515       // This is a gcc extension compatibility comparison.
11516       // In a SFINAE context, we treat this as a hard error to maintain
11517       // conformance with the C++ standard.
11518       diagnoseFunctionPointerToVoidComparison(
11519           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11520
11521       if (isSFINAEContext())
11522         return QualType();
11523
11524       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11525       return computeResultTy();
11526     }
11527
11528     // C++ [expr.eq]p2:
11529     //   If at least one operand is a pointer [...] bring them to their
11530     //   composite pointer type.
11531     // C++ [expr.spaceship]p6
11532     //  If at least one of the operands is of pointer type, [...] bring them
11533     //  to their composite pointer type.
11534     // C++ [expr.rel]p2:
11535     //   If both operands are pointers, [...] bring them to their composite
11536     //   pointer type.
11537     // For <=>, the only valid non-pointer types are arrays and functions, and
11538     // we already decayed those, so this is really the same as the relational
11539     // comparison rule.
11540     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11541             (IsOrdered ? 2 : 1) &&
11542         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11543                                          RHSType->isObjCObjectPointerType()))) {
11544       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11545         return QualType();
11546       return computeResultTy();
11547     }
11548   } else if (LHSType->isPointerType() &&
11549              RHSType->isPointerType()) { // C99 6.5.8p2
11550     // All of the following pointer-related warnings are GCC extensions, except
11551     // when handling null pointer constants.
11552     QualType LCanPointeeTy =
11553       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11554     QualType RCanPointeeTy =
11555       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11556
11557     // C99 6.5.9p2 and C99 6.5.8p2
11558     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11559                                    RCanPointeeTy.getUnqualifiedType())) {
11560       if (IsRelational) {
11561         // Pointers both need to point to complete or incomplete types
11562         if ((LCanPointeeTy->isIncompleteType() !=
11563              RCanPointeeTy->isIncompleteType()) &&
11564             !getLangOpts().C11) {
11565           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11566               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11567               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11568               << RCanPointeeTy->isIncompleteType();
11569         }
11570         if (LCanPointeeTy->isFunctionType()) {
11571           // Valid unless a relational comparison of function pointers
11572           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11573               << LHSType << RHSType << LHS.get()->getSourceRange()
11574               << RHS.get()->getSourceRange();
11575         }
11576       }
11577     } else if (!IsRelational &&
11578                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11579       // Valid unless comparison between non-null pointer and function pointer
11580       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11581           && !LHSIsNull && !RHSIsNull)
11582         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11583                                                 /*isError*/false);
11584     } else {
11585       // Invalid
11586       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11587     }
11588     if (LCanPointeeTy != RCanPointeeTy) {
11589       // Treat NULL constant as a special case in OpenCL.
11590       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11591         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11592           Diag(Loc,
11593                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11594               << LHSType << RHSType << 0 /* comparison */
11595               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11596         }
11597       }
11598       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11599       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11600       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11601                                                : CK_BitCast;
11602       if (LHSIsNull && !RHSIsNull)
11603         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11604       else
11605         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11606     }
11607     return computeResultTy();
11608   }
11609
11610   if (getLangOpts().CPlusPlus) {
11611     // C++ [expr.eq]p4:
11612     //   Two operands of type std::nullptr_t or one operand of type
11613     //   std::nullptr_t and the other a null pointer constant compare equal.
11614     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11615       if (LHSType->isNullPtrType()) {
11616         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11617         return computeResultTy();
11618       }
11619       if (RHSType->isNullPtrType()) {
11620         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11621         return computeResultTy();
11622       }
11623     }
11624
11625     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11626     // These aren't covered by the composite pointer type rules.
11627     if (!IsOrdered && RHSType->isNullPtrType() &&
11628         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11629       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11630       return computeResultTy();
11631     }
11632     if (!IsOrdered && LHSType->isNullPtrType() &&
11633         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11634       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11635       return computeResultTy();
11636     }
11637
11638     if (IsRelational &&
11639         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11640          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11641       // HACK: Relational comparison of nullptr_t against a pointer type is
11642       // invalid per DR583, but we allow it within std::less<> and friends,
11643       // since otherwise common uses of it break.
11644       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11645       // friends to have std::nullptr_t overload candidates.
11646       DeclContext *DC = CurContext;
11647       if (isa<FunctionDecl>(DC))
11648         DC = DC->getParent();
11649       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11650         if (CTSD->isInStdNamespace() &&
11651             llvm::StringSwitch<bool>(CTSD->getName())
11652                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11653                 .Default(false)) {
11654           if (RHSType->isNullPtrType())
11655             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11656           else
11657             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11658           return computeResultTy();
11659         }
11660       }
11661     }
11662
11663     // C++ [expr.eq]p2:
11664     //   If at least one operand is a pointer to member, [...] bring them to
11665     //   their composite pointer type.
11666     if (!IsOrdered &&
11667         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11668       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11669         return QualType();
11670       else
11671         return computeResultTy();
11672     }
11673   }
11674
11675   // Handle block pointer types.
11676   if (!IsOrdered && LHSType->isBlockPointerType() &&
11677       RHSType->isBlockPointerType()) {
11678     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11679     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11680
11681     if (!LHSIsNull && !RHSIsNull &&
11682         !Context.typesAreCompatible(lpointee, rpointee)) {
11683       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11684         << LHSType << RHSType << LHS.get()->getSourceRange()
11685         << RHS.get()->getSourceRange();
11686     }
11687     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11688     return computeResultTy();
11689   }
11690
11691   // Allow block pointers to be compared with null pointer constants.
11692   if (!IsOrdered
11693       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11694           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11695     if (!LHSIsNull && !RHSIsNull) {
11696       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11697              ->getPointeeType()->isVoidType())
11698             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11699                 ->getPointeeType()->isVoidType())))
11700         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11701           << LHSType << RHSType << LHS.get()->getSourceRange()
11702           << RHS.get()->getSourceRange();
11703     }
11704     if (LHSIsNull && !RHSIsNull)
11705       LHS = ImpCastExprToType(LHS.get(), RHSType,
11706                               RHSType->isPointerType() ? CK_BitCast
11707                                 : CK_AnyPointerToBlockPointerCast);
11708     else
11709       RHS = ImpCastExprToType(RHS.get(), LHSType,
11710                               LHSType->isPointerType() ? CK_BitCast
11711                                 : CK_AnyPointerToBlockPointerCast);
11712     return computeResultTy();
11713   }
11714
11715   if (LHSType->isObjCObjectPointerType() ||
11716       RHSType->isObjCObjectPointerType()) {
11717     const PointerType *LPT = LHSType->getAs<PointerType>();
11718     const PointerType *RPT = RHSType->getAs<PointerType>();
11719     if (LPT || RPT) {
11720       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11721       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11722
11723       if (!LPtrToVoid && !RPtrToVoid &&
11724           !Context.typesAreCompatible(LHSType, RHSType)) {
11725         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11726                                           /*isError*/false);
11727       }
11728       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11729       // the RHS, but we have test coverage for this behavior.
11730       // FIXME: Consider using convertPointersToCompositeType in C++.
11731       if (LHSIsNull && !RHSIsNull) {
11732         Expr *E = LHS.get();
11733         if (getLangOpts().ObjCAutoRefCount)
11734           CheckObjCConversion(SourceRange(), RHSType, E,
11735                               CCK_ImplicitConversion);
11736         LHS = ImpCastExprToType(E, RHSType,
11737                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11738       }
11739       else {
11740         Expr *E = RHS.get();
11741         if (getLangOpts().ObjCAutoRefCount)
11742           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11743                               /*Diagnose=*/true,
11744                               /*DiagnoseCFAudited=*/false, Opc);
11745         RHS = ImpCastExprToType(E, LHSType,
11746                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11747       }
11748       return computeResultTy();
11749     }
11750     if (LHSType->isObjCObjectPointerType() &&
11751         RHSType->isObjCObjectPointerType()) {
11752       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11753         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11754                                           /*isError*/false);
11755       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11756         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11757
11758       if (LHSIsNull && !RHSIsNull)
11759         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11760       else
11761         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11762       return computeResultTy();
11763     }
11764
11765     if (!IsOrdered && LHSType->isBlockPointerType() &&
11766         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11767       LHS = ImpCastExprToType(LHS.get(), RHSType,
11768                               CK_BlockPointerToObjCPointerCast);
11769       return computeResultTy();
11770     } else if (!IsOrdered &&
11771                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11772                RHSType->isBlockPointerType()) {
11773       RHS = ImpCastExprToType(RHS.get(), LHSType,
11774                               CK_BlockPointerToObjCPointerCast);
11775       return computeResultTy();
11776     }
11777   }
11778   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11779       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11780     unsigned DiagID = 0;
11781     bool isError = false;
11782     if (LangOpts.DebuggerSupport) {
11783       // Under a debugger, allow the comparison of pointers to integers,
11784       // since users tend to want to compare addresses.
11785     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11786                (RHSIsNull && RHSType->isIntegerType())) {
11787       if (IsOrdered) {
11788         isError = getLangOpts().CPlusPlus;
11789         DiagID =
11790           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11791                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11792       }
11793     } else if (getLangOpts().CPlusPlus) {
11794       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11795       isError = true;
11796     } else if (IsOrdered)
11797       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11798     else
11799       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11800
11801     if (DiagID) {
11802       Diag(Loc, DiagID)
11803         << LHSType << RHSType << LHS.get()->getSourceRange()
11804         << RHS.get()->getSourceRange();
11805       if (isError)
11806         return QualType();
11807     }
11808
11809     if (LHSType->isIntegerType())
11810       LHS = ImpCastExprToType(LHS.get(), RHSType,
11811                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11812     else
11813       RHS = ImpCastExprToType(RHS.get(), LHSType,
11814                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11815     return computeResultTy();
11816   }
11817
11818   // Handle block pointers.
11819   if (!IsOrdered && RHSIsNull
11820       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11821     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11822     return computeResultTy();
11823   }
11824   if (!IsOrdered && LHSIsNull
11825       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11826     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11827     return computeResultTy();
11828   }
11829
11830   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11831     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11832       return computeResultTy();
11833     }
11834
11835     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11836       return computeResultTy();
11837     }
11838
11839     if (LHSIsNull && RHSType->isQueueT()) {
11840       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11841       return computeResultTy();
11842     }
11843
11844     if (LHSType->isQueueT() && RHSIsNull) {
11845       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11846       return computeResultTy();
11847     }
11848   }
11849
11850   return InvalidOperands(Loc, LHS, RHS);
11851 }
11852
11853 // Return a signed ext_vector_type that is of identical size and number of
11854 // elements. For floating point vectors, return an integer type of identical
11855 // size and number of elements. In the non ext_vector_type case, search from
11856 // the largest type to the smallest type to avoid cases where long long == long,
11857 // where long gets picked over long long.
11858 QualType Sema::GetSignedVectorType(QualType V) {
11859   const VectorType *VTy = V->castAs<VectorType>();
11860   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11861
11862   if (isa<ExtVectorType>(VTy)) {
11863     if (TypeSize == Context.getTypeSize(Context.CharTy))
11864       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11865     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11866       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11867     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11868       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11869     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11870       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11871     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11872            "Unhandled vector element size in vector compare");
11873     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11874   }
11875
11876   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11877     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11878                                  VectorType::GenericVector);
11879   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11880     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11881                                  VectorType::GenericVector);
11882   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11883     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11884                                  VectorType::GenericVector);
11885   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11886     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11887                                  VectorType::GenericVector);
11888   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11889          "Unhandled vector element size in vector compare");
11890   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11891                                VectorType::GenericVector);
11892 }
11893
11894 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11895 /// operates on extended vector types.  Instead of producing an IntTy result,
11896 /// like a scalar comparison, a vector comparison produces a vector of integer
11897 /// types.
11898 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11899                                           SourceLocation Loc,
11900                                           BinaryOperatorKind Opc) {
11901   if (Opc == BO_Cmp) {
11902     Diag(Loc, diag::err_three_way_vector_comparison);
11903     return QualType();
11904   }
11905
11906   // Check to make sure we're operating on vectors of the same type and width,
11907   // Allowing one side to be a scalar of element type.
11908   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11909                               /*AllowBothBool*/true,
11910                               /*AllowBoolConversions*/getLangOpts().ZVector);
11911   if (vType.isNull())
11912     return vType;
11913
11914   QualType LHSType = LHS.get()->getType();
11915
11916   // If AltiVec, the comparison results in a numeric type, i.e.
11917   // bool for C++, int for C
11918   if (getLangOpts().AltiVec &&
11919       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11920     return Context.getLogicalOperationType();
11921
11922   // For non-floating point types, check for self-comparisons of the form
11923   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11924   // often indicate logic errors in the program.
11925   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11926
11927   // Check for comparisons of floating point operands using != and ==.
11928   if (BinaryOperator::isEqualityOp(Opc) &&
11929       LHSType->hasFloatingRepresentation()) {
11930     assert(RHS.get()->getType()->hasFloatingRepresentation());
11931     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11932   }
11933
11934   // Return a signed type for the vector.
11935   return GetSignedVectorType(vType);
11936 }
11937
11938 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11939                                     const ExprResult &XorRHS,
11940                                     const SourceLocation Loc) {
11941   // Do not diagnose macros.
11942   if (Loc.isMacroID())
11943     return;
11944
11945   bool Negative = false;
11946   bool ExplicitPlus = false;
11947   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11948   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11949
11950   if (!LHSInt)
11951     return;
11952   if (!RHSInt) {
11953     // Check negative literals.
11954     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11955       UnaryOperatorKind Opc = UO->getOpcode();
11956       if (Opc != UO_Minus && Opc != UO_Plus)
11957         return;
11958       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11959       if (!RHSInt)
11960         return;
11961       Negative = (Opc == UO_Minus);
11962       ExplicitPlus = !Negative;
11963     } else {
11964       return;
11965     }
11966   }
11967
11968   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11969   llvm::APInt RightSideValue = RHSInt->getValue();
11970   if (LeftSideValue != 2 && LeftSideValue != 10)
11971     return;
11972
11973   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11974     return;
11975
11976   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11977       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11978   llvm::StringRef ExprStr =
11979       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11980
11981   CharSourceRange XorRange =
11982       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11983   llvm::StringRef XorStr =
11984       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11985   // Do not diagnose if xor keyword/macro is used.
11986   if (XorStr == "xor")
11987     return;
11988
11989   std::string LHSStr = std::string(Lexer::getSourceText(
11990       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11991       S.getSourceManager(), S.getLangOpts()));
11992   std::string RHSStr = std::string(Lexer::getSourceText(
11993       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11994       S.getSourceManager(), S.getLangOpts()));
11995
11996   if (Negative) {
11997     RightSideValue = -RightSideValue;
11998     RHSStr = "-" + RHSStr;
11999   } else if (ExplicitPlus) {
12000     RHSStr = "+" + RHSStr;
12001   }
12002
12003   StringRef LHSStrRef = LHSStr;
12004   StringRef RHSStrRef = RHSStr;
12005   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12006   // literals.
12007   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12008       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12009       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12010       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12011       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12012       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12013       LHSStrRef.find('\'') != StringRef::npos ||
12014       RHSStrRef.find('\'') != StringRef::npos)
12015     return;
12016
12017   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12018   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12019   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12020   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12021     std::string SuggestedExpr = "1 << " + RHSStr;
12022     bool Overflow = false;
12023     llvm::APInt One = (LeftSideValue - 1);
12024     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12025     if (Overflow) {
12026       if (RightSideIntValue < 64)
12027         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12028             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12029             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12030       else if (RightSideIntValue == 64)
12031         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12032       else
12033         return;
12034     } else {
12035       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12036           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12037           << PowValue.toString(10, true)
12038           << FixItHint::CreateReplacement(
12039                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12040     }
12041
12042     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12043   } else if (LeftSideValue == 10) {
12044     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12045     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12046         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12047         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12048     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12049   }
12050 }
12051
12052 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12053                                           SourceLocation Loc) {
12054   // Ensure that either both operands are of the same vector type, or
12055   // one operand is of a vector type and the other is of its element type.
12056   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12057                                        /*AllowBothBool*/true,
12058                                        /*AllowBoolConversions*/false);
12059   if (vType.isNull())
12060     return InvalidOperands(Loc, LHS, RHS);
12061   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12062       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12063     return InvalidOperands(Loc, LHS, RHS);
12064   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12065   //        usage of the logical operators && and || with vectors in C. This
12066   //        check could be notionally dropped.
12067   if (!getLangOpts().CPlusPlus &&
12068       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12069     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12070
12071   return GetSignedVectorType(LHS.get()->getType());
12072 }
12073
12074 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12075                                               SourceLocation Loc,
12076                                               bool IsCompAssign) {
12077   if (!IsCompAssign) {
12078     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12079     if (LHS.isInvalid())
12080       return QualType();
12081   }
12082   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12083   if (RHS.isInvalid())
12084     return QualType();
12085
12086   // For conversion purposes, we ignore any qualifiers.
12087   // For example, "const float" and "float" are equivalent.
12088   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12089   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12090
12091   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12092   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12093   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12094
12095   if (Context.hasSameType(LHSType, RHSType))
12096     return LHSType;
12097
12098   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12099   // case we have to return InvalidOperands.
12100   ExprResult OriginalLHS = LHS;
12101   ExprResult OriginalRHS = RHS;
12102   if (LHSMatType && !RHSMatType) {
12103     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12104     if (!RHS.isInvalid())
12105       return LHSType;
12106
12107     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12108   }
12109
12110   if (!LHSMatType && RHSMatType) {
12111     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12112     if (!LHS.isInvalid())
12113       return RHSType;
12114     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12115   }
12116
12117   return InvalidOperands(Loc, LHS, RHS);
12118 }
12119
12120 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12121                                            SourceLocation Loc,
12122                                            bool IsCompAssign) {
12123   if (!IsCompAssign) {
12124     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12125     if (LHS.isInvalid())
12126       return QualType();
12127   }
12128   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12129   if (RHS.isInvalid())
12130     return QualType();
12131
12132   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12133   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12134   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12135
12136   if (LHSMatType && RHSMatType) {
12137     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12138       return InvalidOperands(Loc, LHS, RHS);
12139
12140     if (!Context.hasSameType(LHSMatType->getElementType(),
12141                              RHSMatType->getElementType()))
12142       return InvalidOperands(Loc, LHS, RHS);
12143
12144     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12145                                          LHSMatType->getNumRows(),
12146                                          RHSMatType->getNumColumns());
12147   }
12148   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12149 }
12150
12151 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12152                                            SourceLocation Loc,
12153                                            BinaryOperatorKind Opc) {
12154   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12155
12156   bool IsCompAssign =
12157       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12158
12159   if (LHS.get()->getType()->isVectorType() ||
12160       RHS.get()->getType()->isVectorType()) {
12161     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12162         RHS.get()->getType()->hasIntegerRepresentation())
12163       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12164                         /*AllowBothBool*/true,
12165                         /*AllowBoolConversions*/getLangOpts().ZVector);
12166     return InvalidOperands(Loc, LHS, RHS);
12167   }
12168
12169   if (Opc == BO_And)
12170     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12171
12172   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12173       RHS.get()->getType()->hasFloatingRepresentation())
12174     return InvalidOperands(Loc, LHS, RHS);
12175
12176   ExprResult LHSResult = LHS, RHSResult = RHS;
12177   QualType compType = UsualArithmeticConversions(
12178       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12179   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12180     return QualType();
12181   LHS = LHSResult.get();
12182   RHS = RHSResult.get();
12183
12184   if (Opc == BO_Xor)
12185     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12186
12187   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12188     return compType;
12189   return InvalidOperands(Loc, LHS, RHS);
12190 }
12191
12192 // C99 6.5.[13,14]
12193 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12194                                            SourceLocation Loc,
12195                                            BinaryOperatorKind Opc) {
12196   // Check vector operands differently.
12197   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12198     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12199
12200   bool EnumConstantInBoolContext = false;
12201   for (const ExprResult &HS : {LHS, RHS}) {
12202     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12203       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12204       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12205         EnumConstantInBoolContext = true;
12206     }
12207   }
12208
12209   if (EnumConstantInBoolContext)
12210     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12211
12212   // Diagnose cases where the user write a logical and/or but probably meant a
12213   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12214   // is a constant.
12215   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12216       !LHS.get()->getType()->isBooleanType() &&
12217       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12218       // Don't warn in macros or template instantiations.
12219       !Loc.isMacroID() && !inTemplateInstantiation()) {
12220     // If the RHS can be constant folded, and if it constant folds to something
12221     // that isn't 0 or 1 (which indicate a potential logical operation that
12222     // happened to fold to true/false) then warn.
12223     // Parens on the RHS are ignored.
12224     Expr::EvalResult EVResult;
12225     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12226       llvm::APSInt Result = EVResult.Val.getInt();
12227       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12228            !RHS.get()->getExprLoc().isMacroID()) ||
12229           (Result != 0 && Result != 1)) {
12230         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12231           << RHS.get()->getSourceRange()
12232           << (Opc == BO_LAnd ? "&&" : "||");
12233         // Suggest replacing the logical operator with the bitwise version
12234         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12235             << (Opc == BO_LAnd ? "&" : "|")
12236             << FixItHint::CreateReplacement(SourceRange(
12237                                                  Loc, getLocForEndOfToken(Loc)),
12238                                             Opc == BO_LAnd ? "&" : "|");
12239         if (Opc == BO_LAnd)
12240           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12241           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12242               << FixItHint::CreateRemoval(
12243                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12244                                  RHS.get()->getEndLoc()));
12245       }
12246     }
12247   }
12248
12249   if (!Context.getLangOpts().CPlusPlus) {
12250     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12251     // not operate on the built-in scalar and vector float types.
12252     if (Context.getLangOpts().OpenCL &&
12253         Context.getLangOpts().OpenCLVersion < 120) {
12254       if (LHS.get()->getType()->isFloatingType() ||
12255           RHS.get()->getType()->isFloatingType())
12256         return InvalidOperands(Loc, LHS, RHS);
12257     }
12258
12259     LHS = UsualUnaryConversions(LHS.get());
12260     if (LHS.isInvalid())
12261       return QualType();
12262
12263     RHS = UsualUnaryConversions(RHS.get());
12264     if (RHS.isInvalid())
12265       return QualType();
12266
12267     if (!LHS.get()->getType()->isScalarType() ||
12268         !RHS.get()->getType()->isScalarType())
12269       return InvalidOperands(Loc, LHS, RHS);
12270
12271     return Context.IntTy;
12272   }
12273
12274   // The following is safe because we only use this method for
12275   // non-overloadable operands.
12276
12277   // C++ [expr.log.and]p1
12278   // C++ [expr.log.or]p1
12279   // The operands are both contextually converted to type bool.
12280   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12281   if (LHSRes.isInvalid())
12282     return InvalidOperands(Loc, LHS, RHS);
12283   LHS = LHSRes;
12284
12285   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12286   if (RHSRes.isInvalid())
12287     return InvalidOperands(Loc, LHS, RHS);
12288   RHS = RHSRes;
12289
12290   // C++ [expr.log.and]p2
12291   // C++ [expr.log.or]p2
12292   // The result is a bool.
12293   return Context.BoolTy;
12294 }
12295
12296 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12297   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12298   if (!ME) return false;
12299   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12300   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12301       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12302   if (!Base) return false;
12303   return Base->getMethodDecl() != nullptr;
12304 }
12305
12306 /// Is the given expression (which must be 'const') a reference to a
12307 /// variable which was originally non-const, but which has become
12308 /// 'const' due to being captured within a block?
12309 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12310 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12311   assert(E->isLValue() && E->getType().isConstQualified());
12312   E = E->IgnoreParens();
12313
12314   // Must be a reference to a declaration from an enclosing scope.
12315   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12316   if (!DRE) return NCCK_None;
12317   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12318
12319   // The declaration must be a variable which is not declared 'const'.
12320   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12321   if (!var) return NCCK_None;
12322   if (var->getType().isConstQualified()) return NCCK_None;
12323   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12324
12325   // Decide whether the first capture was for a block or a lambda.
12326   DeclContext *DC = S.CurContext, *Prev = nullptr;
12327   // Decide whether the first capture was for a block or a lambda.
12328   while (DC) {
12329     // For init-capture, it is possible that the variable belongs to the
12330     // template pattern of the current context.
12331     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12332       if (var->isInitCapture() &&
12333           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12334         break;
12335     if (DC == var->getDeclContext())
12336       break;
12337     Prev = DC;
12338     DC = DC->getParent();
12339   }
12340   // Unless we have an init-capture, we've gone one step too far.
12341   if (!var->isInitCapture())
12342     DC = Prev;
12343   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12344 }
12345
12346 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12347   Ty = Ty.getNonReferenceType();
12348   if (IsDereference && Ty->isPointerType())
12349     Ty = Ty->getPointeeType();
12350   return !Ty.isConstQualified();
12351 }
12352
12353 // Update err_typecheck_assign_const and note_typecheck_assign_const
12354 // when this enum is changed.
12355 enum {
12356   ConstFunction,
12357   ConstVariable,
12358   ConstMember,
12359   ConstMethod,
12360   NestedConstMember,
12361   ConstUnknown,  // Keep as last element
12362 };
12363
12364 /// Emit the "read-only variable not assignable" error and print notes to give
12365 /// more information about why the variable is not assignable, such as pointing
12366 /// to the declaration of a const variable, showing that a method is const, or
12367 /// that the function is returning a const reference.
12368 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12369                                     SourceLocation Loc) {
12370   SourceRange ExprRange = E->getSourceRange();
12371
12372   // Only emit one error on the first const found.  All other consts will emit
12373   // a note to the error.
12374   bool DiagnosticEmitted = false;
12375
12376   // Track if the current expression is the result of a dereference, and if the
12377   // next checked expression is the result of a dereference.
12378   bool IsDereference = false;
12379   bool NextIsDereference = false;
12380
12381   // Loop to process MemberExpr chains.
12382   while (true) {
12383     IsDereference = NextIsDereference;
12384
12385     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12386     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12387       NextIsDereference = ME->isArrow();
12388       const ValueDecl *VD = ME->getMemberDecl();
12389       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12390         // Mutable fields can be modified even if the class is const.
12391         if (Field->isMutable()) {
12392           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12393           break;
12394         }
12395
12396         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12397           if (!DiagnosticEmitted) {
12398             S.Diag(Loc, diag::err_typecheck_assign_const)
12399                 << ExprRange << ConstMember << false /*static*/ << Field
12400                 << Field->getType();
12401             DiagnosticEmitted = true;
12402           }
12403           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12404               << ConstMember << false /*static*/ << Field << Field->getType()
12405               << Field->getSourceRange();
12406         }
12407         E = ME->getBase();
12408         continue;
12409       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12410         if (VDecl->getType().isConstQualified()) {
12411           if (!DiagnosticEmitted) {
12412             S.Diag(Loc, diag::err_typecheck_assign_const)
12413                 << ExprRange << ConstMember << true /*static*/ << VDecl
12414                 << VDecl->getType();
12415             DiagnosticEmitted = true;
12416           }
12417           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12418               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12419               << VDecl->getSourceRange();
12420         }
12421         // Static fields do not inherit constness from parents.
12422         break;
12423       }
12424       break; // End MemberExpr
12425     } else if (const ArraySubscriptExpr *ASE =
12426                    dyn_cast<ArraySubscriptExpr>(E)) {
12427       E = ASE->getBase()->IgnoreParenImpCasts();
12428       continue;
12429     } else if (const ExtVectorElementExpr *EVE =
12430                    dyn_cast<ExtVectorElementExpr>(E)) {
12431       E = EVE->getBase()->IgnoreParenImpCasts();
12432       continue;
12433     }
12434     break;
12435   }
12436
12437   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12438     // Function calls
12439     const FunctionDecl *FD = CE->getDirectCallee();
12440     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12441       if (!DiagnosticEmitted) {
12442         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12443                                                       << ConstFunction << FD;
12444         DiagnosticEmitted = true;
12445       }
12446       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12447              diag::note_typecheck_assign_const)
12448           << ConstFunction << FD << FD->getReturnType()
12449           << FD->getReturnTypeSourceRange();
12450     }
12451   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12452     // Point to variable declaration.
12453     if (const ValueDecl *VD = DRE->getDecl()) {
12454       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12455         if (!DiagnosticEmitted) {
12456           S.Diag(Loc, diag::err_typecheck_assign_const)
12457               << ExprRange << ConstVariable << VD << VD->getType();
12458           DiagnosticEmitted = true;
12459         }
12460         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12461             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12462       }
12463     }
12464   } else if (isa<CXXThisExpr>(E)) {
12465     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12466       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12467         if (MD->isConst()) {
12468           if (!DiagnosticEmitted) {
12469             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12470                                                           << ConstMethod << MD;
12471             DiagnosticEmitted = true;
12472           }
12473           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12474               << ConstMethod << MD << MD->getSourceRange();
12475         }
12476       }
12477     }
12478   }
12479
12480   if (DiagnosticEmitted)
12481     return;
12482
12483   // Can't determine a more specific message, so display the generic error.
12484   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12485 }
12486
12487 enum OriginalExprKind {
12488   OEK_Variable,
12489   OEK_Member,
12490   OEK_LValue
12491 };
12492
12493 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12494                                          const RecordType *Ty,
12495                                          SourceLocation Loc, SourceRange Range,
12496                                          OriginalExprKind OEK,
12497                                          bool &DiagnosticEmitted) {
12498   std::vector<const RecordType *> RecordTypeList;
12499   RecordTypeList.push_back(Ty);
12500   unsigned NextToCheckIndex = 0;
12501   // We walk the record hierarchy breadth-first to ensure that we print
12502   // diagnostics in field nesting order.
12503   while (RecordTypeList.size() > NextToCheckIndex) {
12504     bool IsNested = NextToCheckIndex > 0;
12505     for (const FieldDecl *Field :
12506          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12507       // First, check every field for constness.
12508       QualType FieldTy = Field->getType();
12509       if (FieldTy.isConstQualified()) {
12510         if (!DiagnosticEmitted) {
12511           S.Diag(Loc, diag::err_typecheck_assign_const)
12512               << Range << NestedConstMember << OEK << VD
12513               << IsNested << Field;
12514           DiagnosticEmitted = true;
12515         }
12516         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12517             << NestedConstMember << IsNested << Field
12518             << FieldTy << Field->getSourceRange();
12519       }
12520
12521       // Then we append it to the list to check next in order.
12522       FieldTy = FieldTy.getCanonicalType();
12523       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12524         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12525           RecordTypeList.push_back(FieldRecTy);
12526       }
12527     }
12528     ++NextToCheckIndex;
12529   }
12530 }
12531
12532 /// Emit an error for the case where a record we are trying to assign to has a
12533 /// const-qualified field somewhere in its hierarchy.
12534 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12535                                          SourceLocation Loc) {
12536   QualType Ty = E->getType();
12537   assert(Ty->isRecordType() && "lvalue was not record?");
12538   SourceRange Range = E->getSourceRange();
12539   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12540   bool DiagEmitted = false;
12541
12542   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12543     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12544             Range, OEK_Member, DiagEmitted);
12545   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12546     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12547             Range, OEK_Variable, DiagEmitted);
12548   else
12549     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12550             Range, OEK_LValue, DiagEmitted);
12551   if (!DiagEmitted)
12552     DiagnoseConstAssignment(S, E, Loc);
12553 }
12554
12555 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12556 /// emit an error and return true.  If so, return false.
12557 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12558   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12559
12560   S.CheckShadowingDeclModification(E, Loc);
12561
12562   SourceLocation OrigLoc = Loc;
12563   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12564                                                               &Loc);
12565   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12566     IsLV = Expr::MLV_InvalidMessageExpression;
12567   if (IsLV == Expr::MLV_Valid)
12568     return false;
12569
12570   unsigned DiagID = 0;
12571   bool NeedType = false;
12572   switch (IsLV) { // C99 6.5.16p2
12573   case Expr::MLV_ConstQualified:
12574     // Use a specialized diagnostic when we're assigning to an object
12575     // from an enclosing function or block.
12576     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12577       if (NCCK == NCCK_Block)
12578         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12579       else
12580         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12581       break;
12582     }
12583
12584     // In ARC, use some specialized diagnostics for occasions where we
12585     // infer 'const'.  These are always pseudo-strong variables.
12586     if (S.getLangOpts().ObjCAutoRefCount) {
12587       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12588       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12589         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12590
12591         // Use the normal diagnostic if it's pseudo-__strong but the
12592         // user actually wrote 'const'.
12593         if (var->isARCPseudoStrong() &&
12594             (!var->getTypeSourceInfo() ||
12595              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12596           // There are three pseudo-strong cases:
12597           //  - self
12598           ObjCMethodDecl *method = S.getCurMethodDecl();
12599           if (method && var == method->getSelfDecl()) {
12600             DiagID = method->isClassMethod()
12601               ? diag::err_typecheck_arc_assign_self_class_method
12602               : diag::err_typecheck_arc_assign_self;
12603
12604           //  - Objective-C externally_retained attribute.
12605           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12606                      isa<ParmVarDecl>(var)) {
12607             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12608
12609           //  - fast enumeration variables
12610           } else {
12611             DiagID = diag::err_typecheck_arr_assign_enumeration;
12612           }
12613
12614           SourceRange Assign;
12615           if (Loc != OrigLoc)
12616             Assign = SourceRange(OrigLoc, OrigLoc);
12617           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12618           // We need to preserve the AST regardless, so migration tool
12619           // can do its job.
12620           return false;
12621         }
12622       }
12623     }
12624
12625     // If none of the special cases above are triggered, then this is a
12626     // simple const assignment.
12627     if (DiagID == 0) {
12628       DiagnoseConstAssignment(S, E, Loc);
12629       return true;
12630     }
12631
12632     break;
12633   case Expr::MLV_ConstAddrSpace:
12634     DiagnoseConstAssignment(S, E, Loc);
12635     return true;
12636   case Expr::MLV_ConstQualifiedField:
12637     DiagnoseRecursiveConstFields(S, E, Loc);
12638     return true;
12639   case Expr::MLV_ArrayType:
12640   case Expr::MLV_ArrayTemporary:
12641     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12642     NeedType = true;
12643     break;
12644   case Expr::MLV_NotObjectType:
12645     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12646     NeedType = true;
12647     break;
12648   case Expr::MLV_LValueCast:
12649     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12650     break;
12651   case Expr::MLV_Valid:
12652     llvm_unreachable("did not take early return for MLV_Valid");
12653   case Expr::MLV_InvalidExpression:
12654   case Expr::MLV_MemberFunction:
12655   case Expr::MLV_ClassTemporary:
12656     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12657     break;
12658   case Expr::MLV_IncompleteType:
12659   case Expr::MLV_IncompleteVoidType:
12660     return S.RequireCompleteType(Loc, E->getType(),
12661              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12662   case Expr::MLV_DuplicateVectorComponents:
12663     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12664     break;
12665   case Expr::MLV_NoSetterProperty:
12666     llvm_unreachable("readonly properties should be processed differently");
12667   case Expr::MLV_InvalidMessageExpression:
12668     DiagID = diag::err_readonly_message_assignment;
12669     break;
12670   case Expr::MLV_SubObjCPropertySetting:
12671     DiagID = diag::err_no_subobject_property_setting;
12672     break;
12673   }
12674
12675   SourceRange Assign;
12676   if (Loc != OrigLoc)
12677     Assign = SourceRange(OrigLoc, OrigLoc);
12678   if (NeedType)
12679     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12680   else
12681     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12682   return true;
12683 }
12684
12685 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12686                                          SourceLocation Loc,
12687                                          Sema &Sema) {
12688   if (Sema.inTemplateInstantiation())
12689     return;
12690   if (Sema.isUnevaluatedContext())
12691     return;
12692   if (Loc.isInvalid() || Loc.isMacroID())
12693     return;
12694   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12695     return;
12696
12697   // C / C++ fields
12698   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12699   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12700   if (ML && MR) {
12701     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12702       return;
12703     const ValueDecl *LHSDecl =
12704         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12705     const ValueDecl *RHSDecl =
12706         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12707     if (LHSDecl != RHSDecl)
12708       return;
12709     if (LHSDecl->getType().isVolatileQualified())
12710       return;
12711     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12712       if (RefTy->getPointeeType().isVolatileQualified())
12713         return;
12714
12715     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12716   }
12717
12718   // Objective-C instance variables
12719   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12720   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12721   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12722     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12723     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12724     if (RL && RR && RL->getDecl() == RR->getDecl())
12725       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12726   }
12727 }
12728
12729 // C99 6.5.16.1
12730 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12731                                        SourceLocation Loc,
12732                                        QualType CompoundType) {
12733   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12734
12735   // Verify that LHS is a modifiable lvalue, and emit error if not.
12736   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12737     return QualType();
12738
12739   QualType LHSType = LHSExpr->getType();
12740   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12741                                              CompoundType;
12742   // OpenCL v1.2 s6.1.1.1 p2:
12743   // The half data type can only be used to declare a pointer to a buffer that
12744   // contains half values
12745   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12746     LHSType->isHalfType()) {
12747     Diag(Loc, diag::err_opencl_half_load_store) << 1
12748         << LHSType.getUnqualifiedType();
12749     return QualType();
12750   }
12751
12752   AssignConvertType ConvTy;
12753   if (CompoundType.isNull()) {
12754     Expr *RHSCheck = RHS.get();
12755
12756     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12757
12758     QualType LHSTy(LHSType);
12759     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12760     if (RHS.isInvalid())
12761       return QualType();
12762     // Special case of NSObject attributes on c-style pointer types.
12763     if (ConvTy == IncompatiblePointer &&
12764         ((Context.isObjCNSObjectType(LHSType) &&
12765           RHSType->isObjCObjectPointerType()) ||
12766          (Context.isObjCNSObjectType(RHSType) &&
12767           LHSType->isObjCObjectPointerType())))
12768       ConvTy = Compatible;
12769
12770     if (ConvTy == Compatible &&
12771         LHSType->isObjCObjectType())
12772         Diag(Loc, diag::err_objc_object_assignment)
12773           << LHSType;
12774
12775     // If the RHS is a unary plus or minus, check to see if they = and + are
12776     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12777     // instead of "x += 4".
12778     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12779       RHSCheck = ICE->getSubExpr();
12780     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12781       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12782           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12783           // Only if the two operators are exactly adjacent.
12784           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12785           // And there is a space or other character before the subexpr of the
12786           // unary +/-.  We don't want to warn on "x=-1".
12787           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12788           UO->getSubExpr()->getBeginLoc().isFileID()) {
12789         Diag(Loc, diag::warn_not_compound_assign)
12790           << (UO->getOpcode() == UO_Plus ? "+" : "-")
12791           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12792       }
12793     }
12794
12795     if (ConvTy == Compatible) {
12796       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12797         // Warn about retain cycles where a block captures the LHS, but
12798         // not if the LHS is a simple variable into which the block is
12799         // being stored...unless that variable can be captured by reference!
12800         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12801         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12802         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12803           checkRetainCycles(LHSExpr, RHS.get());
12804       }
12805
12806       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12807           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12808         // It is safe to assign a weak reference into a strong variable.
12809         // Although this code can still have problems:
12810         //   id x = self.weakProp;
12811         //   id y = self.weakProp;
12812         // we do not warn to warn spuriously when 'x' and 'y' are on separate
12813         // paths through the function. This should be revisited if
12814         // -Wrepeated-use-of-weak is made flow-sensitive.
12815         // For ObjCWeak only, we do not warn if the assign is to a non-weak
12816         // variable, which will be valid for the current autorelease scope.
12817         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12818                              RHS.get()->getBeginLoc()))
12819           getCurFunction()->markSafeWeakUse(RHS.get());
12820
12821       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12822         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12823       }
12824     }
12825   } else {
12826     // Compound assignment "x += y"
12827     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12828   }
12829
12830   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12831                                RHS.get(), AA_Assigning))
12832     return QualType();
12833
12834   CheckForNullPointerDereference(*this, LHSExpr);
12835
12836   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12837     if (CompoundType.isNull()) {
12838       // C++2a [expr.ass]p5:
12839       //   A simple-assignment whose left operand is of a volatile-qualified
12840       //   type is deprecated unless the assignment is either a discarded-value
12841       //   expression or an unevaluated operand
12842       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12843     } else {
12844       // C++2a [expr.ass]p6:
12845       //   [Compound-assignment] expressions are deprecated if E1 has
12846       //   volatile-qualified type
12847       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12848     }
12849   }
12850
12851   // C99 6.5.16p3: The type of an assignment expression is the type of the
12852   // left operand unless the left operand has qualified type, in which case
12853   // it is the unqualified version of the type of the left operand.
12854   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12855   // is converted to the type of the assignment expression (above).
12856   // C++ 5.17p1: the type of the assignment expression is that of its left
12857   // operand.
12858   return (getLangOpts().CPlusPlus
12859           ? LHSType : LHSType.getUnqualifiedType());
12860 }
12861
12862 // Only ignore explicit casts to void.
12863 static bool IgnoreCommaOperand(const Expr *E) {
12864   E = E->IgnoreParens();
12865
12866   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12867     if (CE->getCastKind() == CK_ToVoid) {
12868       return true;
12869     }
12870
12871     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12872     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12873         CE->getSubExpr()->getType()->isDependentType()) {
12874       return true;
12875     }
12876   }
12877
12878   return false;
12879 }
12880
12881 // Look for instances where it is likely the comma operator is confused with
12882 // another operator.  There is an explicit list of acceptable expressions for
12883 // the left hand side of the comma operator, otherwise emit a warning.
12884 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12885   // No warnings in macros
12886   if (Loc.isMacroID())
12887     return;
12888
12889   // Don't warn in template instantiations.
12890   if (inTemplateInstantiation())
12891     return;
12892
12893   // Scope isn't fine-grained enough to explicitly list the specific cases, so
12894   // instead, skip more than needed, then call back into here with the
12895   // CommaVisitor in SemaStmt.cpp.
12896   // The listed locations are the initialization and increment portions
12897   // of a for loop.  The additional checks are on the condition of
12898   // if statements, do/while loops, and for loops.
12899   // Differences in scope flags for C89 mode requires the extra logic.
12900   const unsigned ForIncrementFlags =
12901       getLangOpts().C99 || getLangOpts().CPlusPlus
12902           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12903           : Scope::ContinueScope | Scope::BreakScope;
12904   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12905   const unsigned ScopeFlags = getCurScope()->getFlags();
12906   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12907       (ScopeFlags & ForInitFlags) == ForInitFlags)
12908     return;
12909
12910   // If there are multiple comma operators used together, get the RHS of the
12911   // of the comma operator as the LHS.
12912   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12913     if (BO->getOpcode() != BO_Comma)
12914       break;
12915     LHS = BO->getRHS();
12916   }
12917
12918   // Only allow some expressions on LHS to not warn.
12919   if (IgnoreCommaOperand(LHS))
12920     return;
12921
12922   Diag(Loc, diag::warn_comma_operator);
12923   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12924       << LHS->getSourceRange()
12925       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12926                                     LangOpts.CPlusPlus ? "static_cast<void>("
12927                                                        : "(void)(")
12928       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12929                                     ")");
12930 }
12931
12932 // C99 6.5.17
12933 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12934                                    SourceLocation Loc) {
12935   LHS = S.CheckPlaceholderExpr(LHS.get());
12936   RHS = S.CheckPlaceholderExpr(RHS.get());
12937   if (LHS.isInvalid() || RHS.isInvalid())
12938     return QualType();
12939
12940   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12941   // operands, but not unary promotions.
12942   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12943
12944   // So we treat the LHS as a ignored value, and in C++ we allow the
12945   // containing site to determine what should be done with the RHS.
12946   LHS = S.IgnoredValueConversions(LHS.get());
12947   if (LHS.isInvalid())
12948     return QualType();
12949
12950   S.DiagnoseUnusedExprResult(LHS.get());
12951
12952   if (!S.getLangOpts().CPlusPlus) {
12953     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12954     if (RHS.isInvalid())
12955       return QualType();
12956     if (!RHS.get()->getType()->isVoidType())
12957       S.RequireCompleteType(Loc, RHS.get()->getType(),
12958                             diag::err_incomplete_type);
12959   }
12960
12961   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12962     S.DiagnoseCommaOperator(LHS.get(), Loc);
12963
12964   return RHS.get()->getType();
12965 }
12966
12967 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12968 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12969 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12970                                                ExprValueKind &VK,
12971                                                ExprObjectKind &OK,
12972                                                SourceLocation OpLoc,
12973                                                bool IsInc, bool IsPrefix) {
12974   if (Op->isTypeDependent())
12975     return S.Context.DependentTy;
12976
12977   QualType ResType = Op->getType();
12978   // Atomic types can be used for increment / decrement where the non-atomic
12979   // versions can, so ignore the _Atomic() specifier for the purpose of
12980   // checking.
12981   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12982     ResType = ResAtomicType->getValueType();
12983
12984   assert(!ResType.isNull() && "no type for increment/decrement expression");
12985
12986   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12987     // Decrement of bool is not allowed.
12988     if (!IsInc) {
12989       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12990       return QualType();
12991     }
12992     // Increment of bool sets it to true, but is deprecated.
12993     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12994                                               : diag::warn_increment_bool)
12995       << Op->getSourceRange();
12996   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12997     // Error on enum increments and decrements in C++ mode
12998     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12999     return QualType();
13000   } else if (ResType->isRealType()) {
13001     // OK!
13002   } else if (ResType->isPointerType()) {
13003     // C99 6.5.2.4p2, 6.5.6p2
13004     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13005       return QualType();
13006   } else if (ResType->isObjCObjectPointerType()) {
13007     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13008     // Otherwise, we just need a complete type.
13009     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13010         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13011       return QualType();
13012   } else if (ResType->isAnyComplexType()) {
13013     // C99 does not support ++/-- on complex types, we allow as an extension.
13014     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13015       << ResType << Op->getSourceRange();
13016   } else if (ResType->isPlaceholderType()) {
13017     ExprResult PR = S.CheckPlaceholderExpr(Op);
13018     if (PR.isInvalid()) return QualType();
13019     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13020                                           IsInc, IsPrefix);
13021   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13022     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13023   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13024              (ResType->castAs<VectorType>()->getVectorKind() !=
13025               VectorType::AltiVecBool)) {
13026     // The z vector extensions allow ++ and -- for non-bool vectors.
13027   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13028             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13029     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13030   } else {
13031     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13032       << ResType << int(IsInc) << Op->getSourceRange();
13033     return QualType();
13034   }
13035   // At this point, we know we have a real, complex or pointer type.
13036   // Now make sure the operand is a modifiable lvalue.
13037   if (CheckForModifiableLvalue(Op, OpLoc, S))
13038     return QualType();
13039   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13040     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13041     //   An operand with volatile-qualified type is deprecated
13042     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13043         << IsInc << ResType;
13044   }
13045   // In C++, a prefix increment is the same type as the operand. Otherwise
13046   // (in C or with postfix), the increment is the unqualified type of the
13047   // operand.
13048   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13049     VK = VK_LValue;
13050     OK = Op->getObjectKind();
13051     return ResType;
13052   } else {
13053     VK = VK_RValue;
13054     return ResType.getUnqualifiedType();
13055   }
13056 }
13057
13058
13059 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13060 /// This routine allows us to typecheck complex/recursive expressions
13061 /// where the declaration is needed for type checking. We only need to
13062 /// handle cases when the expression references a function designator
13063 /// or is an lvalue. Here are some examples:
13064 ///  - &(x) => x
13065 ///  - &*****f => f for f a function designator.
13066 ///  - &s.xx => s
13067 ///  - &s.zz[1].yy -> s, if zz is an array
13068 ///  - *(x + 1) -> x, if x is an array
13069 ///  - &"123"[2] -> 0
13070 ///  - & __real__ x -> x
13071 ///
13072 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13073 /// members.
13074 static ValueDecl *getPrimaryDecl(Expr *E) {
13075   switch (E->getStmtClass()) {
13076   case Stmt::DeclRefExprClass:
13077     return cast<DeclRefExpr>(E)->getDecl();
13078   case Stmt::MemberExprClass:
13079     // If this is an arrow operator, the address is an offset from
13080     // the base's value, so the object the base refers to is
13081     // irrelevant.
13082     if (cast<MemberExpr>(E)->isArrow())
13083       return nullptr;
13084     // Otherwise, the expression refers to a part of the base
13085     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13086   case Stmt::ArraySubscriptExprClass: {
13087     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13088     // promotion of register arrays earlier.
13089     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13090     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13091       if (ICE->getSubExpr()->getType()->isArrayType())
13092         return getPrimaryDecl(ICE->getSubExpr());
13093     }
13094     return nullptr;
13095   }
13096   case Stmt::UnaryOperatorClass: {
13097     UnaryOperator *UO = cast<UnaryOperator>(E);
13098
13099     switch(UO->getOpcode()) {
13100     case UO_Real:
13101     case UO_Imag:
13102     case UO_Extension:
13103       return getPrimaryDecl(UO->getSubExpr());
13104     default:
13105       return nullptr;
13106     }
13107   }
13108   case Stmt::ParenExprClass:
13109     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13110   case Stmt::ImplicitCastExprClass:
13111     // If the result of an implicit cast is an l-value, we care about
13112     // the sub-expression; otherwise, the result here doesn't matter.
13113     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13114   case Stmt::CXXUuidofExprClass:
13115     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13116   default:
13117     return nullptr;
13118   }
13119 }
13120
13121 namespace {
13122 enum {
13123   AO_Bit_Field = 0,
13124   AO_Vector_Element = 1,
13125   AO_Property_Expansion = 2,
13126   AO_Register_Variable = 3,
13127   AO_Matrix_Element = 4,
13128   AO_No_Error = 5
13129 };
13130 }
13131 /// Diagnose invalid operand for address of operations.
13132 ///
13133 /// \param Type The type of operand which cannot have its address taken.
13134 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13135                                          Expr *E, unsigned Type) {
13136   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13137 }
13138
13139 /// CheckAddressOfOperand - The operand of & must be either a function
13140 /// designator or an lvalue designating an object. If it is an lvalue, the
13141 /// object cannot be declared with storage class register or be a bit field.
13142 /// Note: The usual conversions are *not* applied to the operand of the &
13143 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13144 /// In C++, the operand might be an overloaded function name, in which case
13145 /// we allow the '&' but retain the overloaded-function type.
13146 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13147   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13148     if (PTy->getKind() == BuiltinType::Overload) {
13149       Expr *E = OrigOp.get()->IgnoreParens();
13150       if (!isa<OverloadExpr>(E)) {
13151         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13152         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13153           << OrigOp.get()->getSourceRange();
13154         return QualType();
13155       }
13156
13157       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13158       if (isa<UnresolvedMemberExpr>(Ovl))
13159         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13160           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13161             << OrigOp.get()->getSourceRange();
13162           return QualType();
13163         }
13164
13165       return Context.OverloadTy;
13166     }
13167
13168     if (PTy->getKind() == BuiltinType::UnknownAny)
13169       return Context.UnknownAnyTy;
13170
13171     if (PTy->getKind() == BuiltinType::BoundMember) {
13172       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13173         << OrigOp.get()->getSourceRange();
13174       return QualType();
13175     }
13176
13177     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13178     if (OrigOp.isInvalid()) return QualType();
13179   }
13180
13181   if (OrigOp.get()->isTypeDependent())
13182     return Context.DependentTy;
13183
13184   assert(!OrigOp.get()->getType()->isPlaceholderType());
13185
13186   // Make sure to ignore parentheses in subsequent checks
13187   Expr *op = OrigOp.get()->IgnoreParens();
13188
13189   // In OpenCL captures for blocks called as lambda functions
13190   // are located in the private address space. Blocks used in
13191   // enqueue_kernel can be located in a different address space
13192   // depending on a vendor implementation. Thus preventing
13193   // taking an address of the capture to avoid invalid AS casts.
13194   if (LangOpts.OpenCL) {
13195     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13196     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13197       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13198       return QualType();
13199     }
13200   }
13201
13202   if (getLangOpts().C99) {
13203     // Implement C99-only parts of addressof rules.
13204     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13205       if (uOp->getOpcode() == UO_Deref)
13206         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13207         // (assuming the deref expression is valid).
13208         return uOp->getSubExpr()->getType();
13209     }
13210     // Technically, there should be a check for array subscript
13211     // expressions here, but the result of one is always an lvalue anyway.
13212   }
13213   ValueDecl *dcl = getPrimaryDecl(op);
13214
13215   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13216     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13217                                            op->getBeginLoc()))
13218       return QualType();
13219
13220   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13221   unsigned AddressOfError = AO_No_Error;
13222
13223   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13224     bool sfinae = (bool)isSFINAEContext();
13225     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13226                                   : diag::ext_typecheck_addrof_temporary)
13227       << op->getType() << op->getSourceRange();
13228     if (sfinae)
13229       return QualType();
13230     // Materialize the temporary as an lvalue so that we can take its address.
13231     OrigOp = op =
13232         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13233   } else if (isa<ObjCSelectorExpr>(op)) {
13234     return Context.getPointerType(op->getType());
13235   } else if (lval == Expr::LV_MemberFunction) {
13236     // If it's an instance method, make a member pointer.
13237     // The expression must have exactly the form &A::foo.
13238
13239     // If the underlying expression isn't a decl ref, give up.
13240     if (!isa<DeclRefExpr>(op)) {
13241       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13242         << OrigOp.get()->getSourceRange();
13243       return QualType();
13244     }
13245     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13246     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13247
13248     // The id-expression was parenthesized.
13249     if (OrigOp.get() != DRE) {
13250       Diag(OpLoc, diag::err_parens_pointer_member_function)
13251         << OrigOp.get()->getSourceRange();
13252
13253     // The method was named without a qualifier.
13254     } else if (!DRE->getQualifier()) {
13255       if (MD->getParent()->getName().empty())
13256         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13257           << op->getSourceRange();
13258       else {
13259         SmallString<32> Str;
13260         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13261         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13262           << op->getSourceRange()
13263           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13264       }
13265     }
13266
13267     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13268     if (isa<CXXDestructorDecl>(MD))
13269       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13270
13271     QualType MPTy = Context.getMemberPointerType(
13272         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13273     // Under the MS ABI, lock down the inheritance model now.
13274     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13275       (void)isCompleteType(OpLoc, MPTy);
13276     return MPTy;
13277   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13278     // C99 6.5.3.2p1
13279     // The operand must be either an l-value or a function designator
13280     if (!op->getType()->isFunctionType()) {
13281       // Use a special diagnostic for loads from property references.
13282       if (isa<PseudoObjectExpr>(op)) {
13283         AddressOfError = AO_Property_Expansion;
13284       } else {
13285         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13286           << op->getType() << op->getSourceRange();
13287         return QualType();
13288       }
13289     }
13290   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13291     // The operand cannot be a bit-field
13292     AddressOfError = AO_Bit_Field;
13293   } else if (op->getObjectKind() == OK_VectorComponent) {
13294     // The operand cannot be an element of a vector
13295     AddressOfError = AO_Vector_Element;
13296   } else if (op->getObjectKind() == OK_MatrixComponent) {
13297     // The operand cannot be an element of a matrix.
13298     AddressOfError = AO_Matrix_Element;
13299   } else if (dcl) { // C99 6.5.3.2p1
13300     // We have an lvalue with a decl. Make sure the decl is not declared
13301     // with the register storage-class specifier.
13302     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13303       // in C++ it is not error to take address of a register
13304       // variable (c++03 7.1.1P3)
13305       if (vd->getStorageClass() == SC_Register &&
13306           !getLangOpts().CPlusPlus) {
13307         AddressOfError = AO_Register_Variable;
13308       }
13309     } else if (isa<MSPropertyDecl>(dcl)) {
13310       AddressOfError = AO_Property_Expansion;
13311     } else if (isa<FunctionTemplateDecl>(dcl)) {
13312       return Context.OverloadTy;
13313     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13314       // Okay: we can take the address of a field.
13315       // Could be a pointer to member, though, if there is an explicit
13316       // scope qualifier for the class.
13317       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13318         DeclContext *Ctx = dcl->getDeclContext();
13319         if (Ctx && Ctx->isRecord()) {
13320           if (dcl->getType()->isReferenceType()) {
13321             Diag(OpLoc,
13322                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13323               << dcl->getDeclName() << dcl->getType();
13324             return QualType();
13325           }
13326
13327           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13328             Ctx = Ctx->getParent();
13329
13330           QualType MPTy = Context.getMemberPointerType(
13331               op->getType(),
13332               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13333           // Under the MS ABI, lock down the inheritance model now.
13334           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13335             (void)isCompleteType(OpLoc, MPTy);
13336           return MPTy;
13337         }
13338       }
13339     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13340                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13341       llvm_unreachable("Unknown/unexpected decl type");
13342   }
13343
13344   if (AddressOfError != AO_No_Error) {
13345     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13346     return QualType();
13347   }
13348
13349   if (lval == Expr::LV_IncompleteVoidType) {
13350     // Taking the address of a void variable is technically illegal, but we
13351     // allow it in cases which are otherwise valid.
13352     // Example: "extern void x; void* y = &x;".
13353     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13354   }
13355
13356   // If the operand has type "type", the result has type "pointer to type".
13357   if (op->getType()->isObjCObjectType())
13358     return Context.getObjCObjectPointerType(op->getType());
13359
13360   CheckAddressOfPackedMember(op);
13361
13362   return Context.getPointerType(op->getType());
13363 }
13364
13365 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13366   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13367   if (!DRE)
13368     return;
13369   const Decl *D = DRE->getDecl();
13370   if (!D)
13371     return;
13372   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13373   if (!Param)
13374     return;
13375   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13376     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13377       return;
13378   if (FunctionScopeInfo *FD = S.getCurFunction())
13379     if (!FD->ModifiedNonNullParams.count(Param))
13380       FD->ModifiedNonNullParams.insert(Param);
13381 }
13382
13383 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13384 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13385                                         SourceLocation OpLoc) {
13386   if (Op->isTypeDependent())
13387     return S.Context.DependentTy;
13388
13389   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13390   if (ConvResult.isInvalid())
13391     return QualType();
13392   Op = ConvResult.get();
13393   QualType OpTy = Op->getType();
13394   QualType Result;
13395
13396   if (isa<CXXReinterpretCastExpr>(Op)) {
13397     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13398     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13399                                      Op->getSourceRange());
13400   }
13401
13402   if (const PointerType *PT = OpTy->getAs<PointerType>())
13403   {
13404     Result = PT->getPointeeType();
13405   }
13406   else if (const ObjCObjectPointerType *OPT =
13407              OpTy->getAs<ObjCObjectPointerType>())
13408     Result = OPT->getPointeeType();
13409   else {
13410     ExprResult PR = S.CheckPlaceholderExpr(Op);
13411     if (PR.isInvalid()) return QualType();
13412     if (PR.get() != Op)
13413       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13414   }
13415
13416   if (Result.isNull()) {
13417     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13418       << OpTy << Op->getSourceRange();
13419     return QualType();
13420   }
13421
13422   // Note that per both C89 and C99, indirection is always legal, even if Result
13423   // is an incomplete type or void.  It would be possible to warn about
13424   // dereferencing a void pointer, but it's completely well-defined, and such a
13425   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13426   // for pointers to 'void' but is fine for any other pointer type:
13427   //
13428   // C++ [expr.unary.op]p1:
13429   //   [...] the expression to which [the unary * operator] is applied shall
13430   //   be a pointer to an object type, or a pointer to a function type
13431   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13432     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13433       << OpTy << Op->getSourceRange();
13434
13435   // Dereferences are usually l-values...
13436   VK = VK_LValue;
13437
13438   // ...except that certain expressions are never l-values in C.
13439   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13440     VK = VK_RValue;
13441
13442   return Result;
13443 }
13444
13445 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13446   BinaryOperatorKind Opc;
13447   switch (Kind) {
13448   default: llvm_unreachable("Unknown binop!");
13449   case tok::periodstar:           Opc = BO_PtrMemD; break;
13450   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13451   case tok::star:                 Opc = BO_Mul; break;
13452   case tok::slash:                Opc = BO_Div; break;
13453   case tok::percent:              Opc = BO_Rem; break;
13454   case tok::plus:                 Opc = BO_Add; break;
13455   case tok::minus:                Opc = BO_Sub; break;
13456   case tok::lessless:             Opc = BO_Shl; break;
13457   case tok::greatergreater:       Opc = BO_Shr; break;
13458   case tok::lessequal:            Opc = BO_LE; break;
13459   case tok::less:                 Opc = BO_LT; break;
13460   case tok::greaterequal:         Opc = BO_GE; break;
13461   case tok::greater:              Opc = BO_GT; break;
13462   case tok::exclaimequal:         Opc = BO_NE; break;
13463   case tok::equalequal:           Opc = BO_EQ; break;
13464   case tok::spaceship:            Opc = BO_Cmp; break;
13465   case tok::amp:                  Opc = BO_And; break;
13466   case tok::caret:                Opc = BO_Xor; break;
13467   case tok::pipe:                 Opc = BO_Or; break;
13468   case tok::ampamp:               Opc = BO_LAnd; break;
13469   case tok::pipepipe:             Opc = BO_LOr; break;
13470   case tok::equal:                Opc = BO_Assign; break;
13471   case tok::starequal:            Opc = BO_MulAssign; break;
13472   case tok::slashequal:           Opc = BO_DivAssign; break;
13473   case tok::percentequal:         Opc = BO_RemAssign; break;
13474   case tok::plusequal:            Opc = BO_AddAssign; break;
13475   case tok::minusequal:           Opc = BO_SubAssign; break;
13476   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13477   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13478   case tok::ampequal:             Opc = BO_AndAssign; break;
13479   case tok::caretequal:           Opc = BO_XorAssign; break;
13480   case tok::pipeequal:            Opc = BO_OrAssign; break;
13481   case tok::comma:                Opc = BO_Comma; break;
13482   }
13483   return Opc;
13484 }
13485
13486 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13487   tok::TokenKind Kind) {
13488   UnaryOperatorKind Opc;
13489   switch (Kind) {
13490   default: llvm_unreachable("Unknown unary op!");
13491   case tok::plusplus:     Opc = UO_PreInc; break;
13492   case tok::minusminus:   Opc = UO_PreDec; break;
13493   case tok::amp:          Opc = UO_AddrOf; break;
13494   case tok::star:         Opc = UO_Deref; break;
13495   case tok::plus:         Opc = UO_Plus; break;
13496   case tok::minus:        Opc = UO_Minus; break;
13497   case tok::tilde:        Opc = UO_Not; break;
13498   case tok::exclaim:      Opc = UO_LNot; break;
13499   case tok::kw___real:    Opc = UO_Real; break;
13500   case tok::kw___imag:    Opc = UO_Imag; break;
13501   case tok::kw___extension__: Opc = UO_Extension; break;
13502   }
13503   return Opc;
13504 }
13505
13506 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13507 /// This warning suppressed in the event of macro expansions.
13508 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13509                                    SourceLocation OpLoc, bool IsBuiltin) {
13510   if (S.inTemplateInstantiation())
13511     return;
13512   if (S.isUnevaluatedContext())
13513     return;
13514   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13515     return;
13516   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13517   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13518   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13519   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13520   if (!LHSDeclRef || !RHSDeclRef ||
13521       LHSDeclRef->getLocation().isMacroID() ||
13522       RHSDeclRef->getLocation().isMacroID())
13523     return;
13524   const ValueDecl *LHSDecl =
13525     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13526   const ValueDecl *RHSDecl =
13527     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13528   if (LHSDecl != RHSDecl)
13529     return;
13530   if (LHSDecl->getType().isVolatileQualified())
13531     return;
13532   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13533     if (RefTy->getPointeeType().isVolatileQualified())
13534       return;
13535
13536   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13537                           : diag::warn_self_assignment_overloaded)
13538       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13539       << RHSExpr->getSourceRange();
13540 }
13541
13542 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13543 /// is usually indicative of introspection within the Objective-C pointer.
13544 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13545                                           SourceLocation OpLoc) {
13546   if (!S.getLangOpts().ObjC)
13547     return;
13548
13549   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13550   const Expr *LHS = L.get();
13551   const Expr *RHS = R.get();
13552
13553   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13554     ObjCPointerExpr = LHS;
13555     OtherExpr = RHS;
13556   }
13557   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13558     ObjCPointerExpr = RHS;
13559     OtherExpr = LHS;
13560   }
13561
13562   // This warning is deliberately made very specific to reduce false
13563   // positives with logic that uses '&' for hashing.  This logic mainly
13564   // looks for code trying to introspect into tagged pointers, which
13565   // code should generally never do.
13566   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13567     unsigned Diag = diag::warn_objc_pointer_masking;
13568     // Determine if we are introspecting the result of performSelectorXXX.
13569     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13570     // Special case messages to -performSelector and friends, which
13571     // can return non-pointer values boxed in a pointer value.
13572     // Some clients may wish to silence warnings in this subcase.
13573     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13574       Selector S = ME->getSelector();
13575       StringRef SelArg0 = S.getNameForSlot(0);
13576       if (SelArg0.startswith("performSelector"))
13577         Diag = diag::warn_objc_pointer_masking_performSelector;
13578     }
13579
13580     S.Diag(OpLoc, Diag)
13581       << ObjCPointerExpr->getSourceRange();
13582   }
13583 }
13584
13585 static NamedDecl *getDeclFromExpr(Expr *E) {
13586   if (!E)
13587     return nullptr;
13588   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13589     return DRE->getDecl();
13590   if (auto *ME = dyn_cast<MemberExpr>(E))
13591     return ME->getMemberDecl();
13592   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13593     return IRE->getDecl();
13594   return nullptr;
13595 }
13596
13597 // This helper function promotes a binary operator's operands (which are of a
13598 // half vector type) to a vector of floats and then truncates the result to
13599 // a vector of either half or short.
13600 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13601                                       BinaryOperatorKind Opc, QualType ResultTy,
13602                                       ExprValueKind VK, ExprObjectKind OK,
13603                                       bool IsCompAssign, SourceLocation OpLoc,
13604                                       FPOptionsOverride FPFeatures) {
13605   auto &Context = S.getASTContext();
13606   assert((isVector(ResultTy, Context.HalfTy) ||
13607           isVector(ResultTy, Context.ShortTy)) &&
13608          "Result must be a vector of half or short");
13609   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13610          isVector(RHS.get()->getType(), Context.HalfTy) &&
13611          "both operands expected to be a half vector");
13612
13613   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13614   QualType BinOpResTy = RHS.get()->getType();
13615
13616   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13617   // change BinOpResTy to a vector of ints.
13618   if (isVector(ResultTy, Context.ShortTy))
13619     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13620
13621   if (IsCompAssign)
13622     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13623                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13624                                           BinOpResTy, BinOpResTy);
13625
13626   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13627   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13628                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13629   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13630 }
13631
13632 static std::pair<ExprResult, ExprResult>
13633 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13634                            Expr *RHSExpr) {
13635   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13636   if (!S.getLangOpts().CPlusPlus) {
13637     // C cannot handle TypoExpr nodes on either side of a binop because it
13638     // doesn't handle dependent types properly, so make sure any TypoExprs have
13639     // been dealt with before checking the operands.
13640     LHS = S.CorrectDelayedTyposInExpr(LHS);
13641     RHS = S.CorrectDelayedTyposInExpr(
13642         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13643         [Opc, LHS](Expr *E) {
13644           if (Opc != BO_Assign)
13645             return ExprResult(E);
13646           // Avoid correcting the RHS to the same Expr as the LHS.
13647           Decl *D = getDeclFromExpr(E);
13648           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13649         });
13650   }
13651   return std::make_pair(LHS, RHS);
13652 }
13653
13654 /// Returns true if conversion between vectors of halfs and vectors of floats
13655 /// is needed.
13656 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13657                                      Expr *E0, Expr *E1 = nullptr) {
13658   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13659       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13660     return false;
13661
13662   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13663     QualType Ty = E->IgnoreImplicit()->getType();
13664
13665     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13666     // to vectors of floats. Although the element type of the vectors is __fp16,
13667     // the vectors shouldn't be treated as storage-only types. See the
13668     // discussion here: https://reviews.llvm.org/rG825235c140e7
13669     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13670       if (VT->getVectorKind() == VectorType::NeonVector)
13671         return false;
13672       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13673     }
13674     return false;
13675   };
13676
13677   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13678 }
13679
13680 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13681 /// operator @p Opc at location @c TokLoc. This routine only supports
13682 /// built-in operations; ActOnBinOp handles overloaded operators.
13683 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13684                                     BinaryOperatorKind Opc,
13685                                     Expr *LHSExpr, Expr *RHSExpr) {
13686   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13687     // The syntax only allows initializer lists on the RHS of assignment,
13688     // so we don't need to worry about accepting invalid code for
13689     // non-assignment operators.
13690     // C++11 5.17p9:
13691     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13692     //   of x = {} is x = T().
13693     InitializationKind Kind = InitializationKind::CreateDirectList(
13694         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13695     InitializedEntity Entity =
13696         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13697     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13698     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13699     if (Init.isInvalid())
13700       return Init;
13701     RHSExpr = Init.get();
13702   }
13703
13704   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13705   QualType ResultTy;     // Result type of the binary operator.
13706   // The following two variables are used for compound assignment operators
13707   QualType CompLHSTy;    // Type of LHS after promotions for computation
13708   QualType CompResultTy; // Type of computation result
13709   ExprValueKind VK = VK_RValue;
13710   ExprObjectKind OK = OK_Ordinary;
13711   bool ConvertHalfVec = false;
13712
13713   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13714   if (!LHS.isUsable() || !RHS.isUsable())
13715     return ExprError();
13716
13717   if (getLangOpts().OpenCL) {
13718     QualType LHSTy = LHSExpr->getType();
13719     QualType RHSTy = RHSExpr->getType();
13720     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13721     // the ATOMIC_VAR_INIT macro.
13722     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13723       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13724       if (BO_Assign == Opc)
13725         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13726       else
13727         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13728       return ExprError();
13729     }
13730
13731     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13732     // only with a builtin functions and therefore should be disallowed here.
13733     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13734         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13735         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13736         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13737       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13738       return ExprError();
13739     }
13740   }
13741
13742   switch (Opc) {
13743   case BO_Assign:
13744     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13745     if (getLangOpts().CPlusPlus &&
13746         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13747       VK = LHS.get()->getValueKind();
13748       OK = LHS.get()->getObjectKind();
13749     }
13750     if (!ResultTy.isNull()) {
13751       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13752       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13753
13754       // Avoid copying a block to the heap if the block is assigned to a local
13755       // auto variable that is declared in the same scope as the block. This
13756       // optimization is unsafe if the local variable is declared in an outer
13757       // scope. For example:
13758       //
13759       // BlockTy b;
13760       // {
13761       //   b = ^{...};
13762       // }
13763       // // It is unsafe to invoke the block here if it wasn't copied to the
13764       // // heap.
13765       // b();
13766
13767       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13768         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13769           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13770             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13771               BE->getBlockDecl()->setCanAvoidCopyToHeap();
13772
13773       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13774         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13775                               NTCUC_Assignment, NTCUK_Copy);
13776     }
13777     RecordModifiableNonNullParam(*this, LHS.get());
13778     break;
13779   case BO_PtrMemD:
13780   case BO_PtrMemI:
13781     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13782                                             Opc == BO_PtrMemI);
13783     break;
13784   case BO_Mul:
13785   case BO_Div:
13786     ConvertHalfVec = true;
13787     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13788                                            Opc == BO_Div);
13789     break;
13790   case BO_Rem:
13791     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13792     break;
13793   case BO_Add:
13794     ConvertHalfVec = true;
13795     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13796     break;
13797   case BO_Sub:
13798     ConvertHalfVec = true;
13799     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13800     break;
13801   case BO_Shl:
13802   case BO_Shr:
13803     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13804     break;
13805   case BO_LE:
13806   case BO_LT:
13807   case BO_GE:
13808   case BO_GT:
13809     ConvertHalfVec = true;
13810     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13811     break;
13812   case BO_EQ:
13813   case BO_NE:
13814     ConvertHalfVec = true;
13815     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13816     break;
13817   case BO_Cmp:
13818     ConvertHalfVec = true;
13819     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13820     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13821     break;
13822   case BO_And:
13823     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13824     LLVM_FALLTHROUGH;
13825   case BO_Xor:
13826   case BO_Or:
13827     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13828     break;
13829   case BO_LAnd:
13830   case BO_LOr:
13831     ConvertHalfVec = true;
13832     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13833     break;
13834   case BO_MulAssign:
13835   case BO_DivAssign:
13836     ConvertHalfVec = true;
13837     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13838                                                Opc == BO_DivAssign);
13839     CompLHSTy = CompResultTy;
13840     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13841       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13842     break;
13843   case BO_RemAssign:
13844     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13845     CompLHSTy = CompResultTy;
13846     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13847       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13848     break;
13849   case BO_AddAssign:
13850     ConvertHalfVec = true;
13851     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13852     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13853       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13854     break;
13855   case BO_SubAssign:
13856     ConvertHalfVec = true;
13857     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13858     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13859       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13860     break;
13861   case BO_ShlAssign:
13862   case BO_ShrAssign:
13863     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13864     CompLHSTy = CompResultTy;
13865     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13866       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13867     break;
13868   case BO_AndAssign:
13869   case BO_OrAssign: // fallthrough
13870     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13871     LLVM_FALLTHROUGH;
13872   case BO_XorAssign:
13873     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13874     CompLHSTy = CompResultTy;
13875     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13876       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13877     break;
13878   case BO_Comma:
13879     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13880     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13881       VK = RHS.get()->getValueKind();
13882       OK = RHS.get()->getObjectKind();
13883     }
13884     break;
13885   }
13886   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13887     return ExprError();
13888
13889   // Some of the binary operations require promoting operands of half vector to
13890   // float vectors and truncating the result back to half vector. For now, we do
13891   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13892   // arm64).
13893   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13894          isVector(LHS.get()->getType(), Context.HalfTy) &&
13895          "both sides are half vectors or neither sides are");
13896   ConvertHalfVec =
13897       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13898
13899   // Check for array bounds violations for both sides of the BinaryOperator
13900   CheckArrayAccess(LHS.get());
13901   CheckArrayAccess(RHS.get());
13902
13903   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13904     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13905                                                  &Context.Idents.get("object_setClass"),
13906                                                  SourceLocation(), LookupOrdinaryName);
13907     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13908       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13909       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13910           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13911                                         "object_setClass(")
13912           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13913                                           ",")
13914           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13915     }
13916     else
13917       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13918   }
13919   else if (const ObjCIvarRefExpr *OIRE =
13920            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13921     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13922
13923   // Opc is not a compound assignment if CompResultTy is null.
13924   if (CompResultTy.isNull()) {
13925     if (ConvertHalfVec)
13926       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13927                                  OpLoc, CurFPFeatureOverrides());
13928     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13929                                   VK, OK, OpLoc, CurFPFeatureOverrides());
13930   }
13931
13932   // Handle compound assignments.
13933   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13934       OK_ObjCProperty) {
13935     VK = VK_LValue;
13936     OK = LHS.get()->getObjectKind();
13937   }
13938
13939   // The LHS is not converted to the result type for fixed-point compound
13940   // assignment as the common type is computed on demand. Reset the CompLHSTy
13941   // to the LHS type we would have gotten after unary conversions.
13942   if (CompResultTy->isFixedPointType())
13943     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13944
13945   if (ConvertHalfVec)
13946     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13947                                OpLoc, CurFPFeatureOverrides());
13948
13949   return CompoundAssignOperator::Create(
13950       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
13951       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
13952 }
13953
13954 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13955 /// operators are mixed in a way that suggests that the programmer forgot that
13956 /// comparison operators have higher precedence. The most typical example of
13957 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13958 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13959                                       SourceLocation OpLoc, Expr *LHSExpr,
13960                                       Expr *RHSExpr) {
13961   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13962   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13963
13964   // Check that one of the sides is a comparison operator and the other isn't.
13965   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13966   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13967   if (isLeftComp == isRightComp)
13968     return;
13969
13970   // Bitwise operations are sometimes used as eager logical ops.
13971   // Don't diagnose this.
13972   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13973   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13974   if (isLeftBitwise || isRightBitwise)
13975     return;
13976
13977   SourceRange DiagRange = isLeftComp
13978                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13979                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13980   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13981   SourceRange ParensRange =
13982       isLeftComp
13983           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13984           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13985
13986   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13987     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13988   SuggestParentheses(Self, OpLoc,
13989     Self.PDiag(diag::note_precedence_silence) << OpStr,
13990     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13991   SuggestParentheses(Self, OpLoc,
13992     Self.PDiag(diag::note_precedence_bitwise_first)
13993       << BinaryOperator::getOpcodeStr(Opc),
13994     ParensRange);
13995 }
13996
13997 /// It accepts a '&&' expr that is inside a '||' one.
13998 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13999 /// in parentheses.
14000 static void
14001 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14002                                        BinaryOperator *Bop) {
14003   assert(Bop->getOpcode() == BO_LAnd);
14004   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14005       << Bop->getSourceRange() << OpLoc;
14006   SuggestParentheses(Self, Bop->getOperatorLoc(),
14007     Self.PDiag(diag::note_precedence_silence)
14008       << Bop->getOpcodeStr(),
14009     Bop->getSourceRange());
14010 }
14011
14012 /// Returns true if the given expression can be evaluated as a constant
14013 /// 'true'.
14014 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14015   bool Res;
14016   return !E->isValueDependent() &&
14017          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14018 }
14019
14020 /// Returns true if the given expression can be evaluated as a constant
14021 /// 'false'.
14022 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14023   bool Res;
14024   return !E->isValueDependent() &&
14025          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14026 }
14027
14028 /// Look for '&&' in the left hand of a '||' expr.
14029 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14030                                              Expr *LHSExpr, Expr *RHSExpr) {
14031   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14032     if (Bop->getOpcode() == BO_LAnd) {
14033       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14034       if (EvaluatesAsFalse(S, RHSExpr))
14035         return;
14036       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14037       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14038         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14039     } else if (Bop->getOpcode() == BO_LOr) {
14040       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14041         // If it's "a || b && 1 || c" we didn't warn earlier for
14042         // "a || b && 1", but warn now.
14043         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14044           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14045       }
14046     }
14047   }
14048 }
14049
14050 /// Look for '&&' in the right hand of a '||' expr.
14051 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14052                                              Expr *LHSExpr, Expr *RHSExpr) {
14053   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14054     if (Bop->getOpcode() == BO_LAnd) {
14055       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14056       if (EvaluatesAsFalse(S, LHSExpr))
14057         return;
14058       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14059       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14060         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14061     }
14062   }
14063 }
14064
14065 /// Look for bitwise op in the left or right hand of a bitwise op with
14066 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14067 /// the '&' expression in parentheses.
14068 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14069                                          SourceLocation OpLoc, Expr *SubExpr) {
14070   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14071     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14072       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14073         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14074         << Bop->getSourceRange() << OpLoc;
14075       SuggestParentheses(S, Bop->getOperatorLoc(),
14076         S.PDiag(diag::note_precedence_silence)
14077           << Bop->getOpcodeStr(),
14078         Bop->getSourceRange());
14079     }
14080   }
14081 }
14082
14083 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14084                                     Expr *SubExpr, StringRef Shift) {
14085   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14086     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14087       StringRef Op = Bop->getOpcodeStr();
14088       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14089           << Bop->getSourceRange() << OpLoc << Shift << Op;
14090       SuggestParentheses(S, Bop->getOperatorLoc(),
14091           S.PDiag(diag::note_precedence_silence) << Op,
14092           Bop->getSourceRange());
14093     }
14094   }
14095 }
14096
14097 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14098                                  Expr *LHSExpr, Expr *RHSExpr) {
14099   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14100   if (!OCE)
14101     return;
14102
14103   FunctionDecl *FD = OCE->getDirectCallee();
14104   if (!FD || !FD->isOverloadedOperator())
14105     return;
14106
14107   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14108   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14109     return;
14110
14111   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14112       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14113       << (Kind == OO_LessLess);
14114   SuggestParentheses(S, OCE->getOperatorLoc(),
14115                      S.PDiag(diag::note_precedence_silence)
14116                          << (Kind == OO_LessLess ? "<<" : ">>"),
14117                      OCE->getSourceRange());
14118   SuggestParentheses(
14119       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14120       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14121 }
14122
14123 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14124 /// precedence.
14125 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14126                                     SourceLocation OpLoc, Expr *LHSExpr,
14127                                     Expr *RHSExpr){
14128   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14129   if (BinaryOperator::isBitwiseOp(Opc))
14130     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14131
14132   // Diagnose "arg1 & arg2 | arg3"
14133   if ((Opc == BO_Or || Opc == BO_Xor) &&
14134       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14135     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14136     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14137   }
14138
14139   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14140   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14141   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14142     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14143     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14144   }
14145
14146   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14147       || Opc == BO_Shr) {
14148     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14149     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14150     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14151   }
14152
14153   // Warn on overloaded shift operators and comparisons, such as:
14154   // cout << 5 == 4;
14155   if (BinaryOperator::isComparisonOp(Opc))
14156     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14157 }
14158
14159 // Binary Operators.  'Tok' is the token for the operator.
14160 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14161                             tok::TokenKind Kind,
14162                             Expr *LHSExpr, Expr *RHSExpr) {
14163   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14164   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14165   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14166
14167   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14168   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14169
14170   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14171 }
14172
14173 /// Build an overloaded binary operator expression in the given scope.
14174 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14175                                        BinaryOperatorKind Opc,
14176                                        Expr *LHS, Expr *RHS) {
14177   switch (Opc) {
14178   case BO_Assign:
14179   case BO_DivAssign:
14180   case BO_RemAssign:
14181   case BO_SubAssign:
14182   case BO_AndAssign:
14183   case BO_OrAssign:
14184   case BO_XorAssign:
14185     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14186     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14187     break;
14188   default:
14189     break;
14190   }
14191
14192   // Find all of the overloaded operators visible from this
14193   // point. We perform both an operator-name lookup from the local
14194   // scope and an argument-dependent lookup based on the types of
14195   // the arguments.
14196   UnresolvedSet<16> Functions;
14197   OverloadedOperatorKind OverOp
14198     = BinaryOperator::getOverloadedOperator(Opc);
14199   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14200     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14201                                    RHS->getType(), Functions);
14202
14203   // In C++20 onwards, we may have a second operator to look up.
14204   if (S.getLangOpts().CPlusPlus20) {
14205     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14206       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14207                                      RHS->getType(), Functions);
14208   }
14209
14210   // Build the (potentially-overloaded, potentially-dependent)
14211   // binary operation.
14212   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14213 }
14214
14215 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14216                             BinaryOperatorKind Opc,
14217                             Expr *LHSExpr, Expr *RHSExpr) {
14218   ExprResult LHS, RHS;
14219   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14220   if (!LHS.isUsable() || !RHS.isUsable())
14221     return ExprError();
14222   LHSExpr = LHS.get();
14223   RHSExpr = RHS.get();
14224
14225   // We want to end up calling one of checkPseudoObjectAssignment
14226   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14227   // both expressions are overloadable or either is type-dependent),
14228   // or CreateBuiltinBinOp (in any other case).  We also want to get
14229   // any placeholder types out of the way.
14230
14231   // Handle pseudo-objects in the LHS.
14232   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14233     // Assignments with a pseudo-object l-value need special analysis.
14234     if (pty->getKind() == BuiltinType::PseudoObject &&
14235         BinaryOperator::isAssignmentOp(Opc))
14236       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14237
14238     // Don't resolve overloads if the other type is overloadable.
14239     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14240       // We can't actually test that if we still have a placeholder,
14241       // though.  Fortunately, none of the exceptions we see in that
14242       // code below are valid when the LHS is an overload set.  Note
14243       // that an overload set can be dependently-typed, but it never
14244       // instantiates to having an overloadable type.
14245       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14246       if (resolvedRHS.isInvalid()) return ExprError();
14247       RHSExpr = resolvedRHS.get();
14248
14249       if (RHSExpr->isTypeDependent() ||
14250           RHSExpr->getType()->isOverloadableType())
14251         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14252     }
14253
14254     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14255     // template, diagnose the missing 'template' keyword instead of diagnosing
14256     // an invalid use of a bound member function.
14257     //
14258     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14259     // to C++1z [over.over]/1.4, but we already checked for that case above.
14260     if (Opc == BO_LT && inTemplateInstantiation() &&
14261         (pty->getKind() == BuiltinType::BoundMember ||
14262          pty->getKind() == BuiltinType::Overload)) {
14263       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14264       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14265           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14266             return isa<FunctionTemplateDecl>(ND);
14267           })) {
14268         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14269                                 : OE->getNameLoc(),
14270              diag::err_template_kw_missing)
14271           << OE->getName().getAsString() << "";
14272         return ExprError();
14273       }
14274     }
14275
14276     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14277     if (LHS.isInvalid()) return ExprError();
14278     LHSExpr = LHS.get();
14279   }
14280
14281   // Handle pseudo-objects in the RHS.
14282   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14283     // An overload in the RHS can potentially be resolved by the type
14284     // being assigned to.
14285     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14286       if (getLangOpts().CPlusPlus &&
14287           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14288            LHSExpr->getType()->isOverloadableType()))
14289         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14290
14291       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14292     }
14293
14294     // Don't resolve overloads if the other type is overloadable.
14295     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14296         LHSExpr->getType()->isOverloadableType())
14297       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14298
14299     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14300     if (!resolvedRHS.isUsable()) return ExprError();
14301     RHSExpr = resolvedRHS.get();
14302   }
14303
14304   if (getLangOpts().CPlusPlus) {
14305     // If either expression is type-dependent, always build an
14306     // overloaded op.
14307     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14308       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14309
14310     // Otherwise, build an overloaded op if either expression has an
14311     // overloadable type.
14312     if (LHSExpr->getType()->isOverloadableType() ||
14313         RHSExpr->getType()->isOverloadableType())
14314       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14315   }
14316
14317   // Build a built-in binary operation.
14318   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14319 }
14320
14321 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14322   if (T.isNull() || T->isDependentType())
14323     return false;
14324
14325   if (!T->isPromotableIntegerType())
14326     return true;
14327
14328   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14329 }
14330
14331 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14332                                       UnaryOperatorKind Opc,
14333                                       Expr *InputExpr) {
14334   ExprResult Input = InputExpr;
14335   ExprValueKind VK = VK_RValue;
14336   ExprObjectKind OK = OK_Ordinary;
14337   QualType resultType;
14338   bool CanOverflow = false;
14339
14340   bool ConvertHalfVec = false;
14341   if (getLangOpts().OpenCL) {
14342     QualType Ty = InputExpr->getType();
14343     // The only legal unary operation for atomics is '&'.
14344     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14345     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14346     // only with a builtin functions and therefore should be disallowed here.
14347         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14348         || Ty->isBlockPointerType())) {
14349       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14350                        << InputExpr->getType()
14351                        << Input.get()->getSourceRange());
14352     }
14353   }
14354
14355   switch (Opc) {
14356   case UO_PreInc:
14357   case UO_PreDec:
14358   case UO_PostInc:
14359   case UO_PostDec:
14360     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14361                                                 OpLoc,
14362                                                 Opc == UO_PreInc ||
14363                                                 Opc == UO_PostInc,
14364                                                 Opc == UO_PreInc ||
14365                                                 Opc == UO_PreDec);
14366     CanOverflow = isOverflowingIntegerType(Context, resultType);
14367     break;
14368   case UO_AddrOf:
14369     resultType = CheckAddressOfOperand(Input, OpLoc);
14370     CheckAddressOfNoDeref(InputExpr);
14371     RecordModifiableNonNullParam(*this, InputExpr);
14372     break;
14373   case UO_Deref: {
14374     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14375     if (Input.isInvalid()) return ExprError();
14376     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14377     break;
14378   }
14379   case UO_Plus:
14380   case UO_Minus:
14381     CanOverflow = Opc == UO_Minus &&
14382                   isOverflowingIntegerType(Context, Input.get()->getType());
14383     Input = UsualUnaryConversions(Input.get());
14384     if (Input.isInvalid()) return ExprError();
14385     // Unary plus and minus require promoting an operand of half vector to a
14386     // float vector and truncating the result back to a half vector. For now, we
14387     // do this only when HalfArgsAndReturns is set (that is, when the target is
14388     // arm or arm64).
14389     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14390
14391     // If the operand is a half vector, promote it to a float vector.
14392     if (ConvertHalfVec)
14393       Input = convertVector(Input.get(), Context.FloatTy, *this);
14394     resultType = Input.get()->getType();
14395     if (resultType->isDependentType())
14396       break;
14397     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14398       break;
14399     else if (resultType->isVectorType() &&
14400              // The z vector extensions don't allow + or - with bool vectors.
14401              (!Context.getLangOpts().ZVector ||
14402               resultType->castAs<VectorType>()->getVectorKind() !=
14403               VectorType::AltiVecBool))
14404       break;
14405     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14406              Opc == UO_Plus &&
14407              resultType->isPointerType())
14408       break;
14409
14410     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14411       << resultType << Input.get()->getSourceRange());
14412
14413   case UO_Not: // bitwise complement
14414     Input = UsualUnaryConversions(Input.get());
14415     if (Input.isInvalid())
14416       return ExprError();
14417     resultType = Input.get()->getType();
14418     if (resultType->isDependentType())
14419       break;
14420     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14421     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14422       // C99 does not support '~' for complex conjugation.
14423       Diag(OpLoc, diag::ext_integer_complement_complex)
14424           << resultType << Input.get()->getSourceRange();
14425     else if (resultType->hasIntegerRepresentation())
14426       break;
14427     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14428       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14429       // on vector float types.
14430       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14431       if (!T->isIntegerType())
14432         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14433                           << resultType << Input.get()->getSourceRange());
14434     } else {
14435       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14436                        << resultType << Input.get()->getSourceRange());
14437     }
14438     break;
14439
14440   case UO_LNot: // logical negation
14441     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14442     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14443     if (Input.isInvalid()) return ExprError();
14444     resultType = Input.get()->getType();
14445
14446     // Though we still have to promote half FP to float...
14447     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14448       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14449       resultType = Context.FloatTy;
14450     }
14451
14452     if (resultType->isDependentType())
14453       break;
14454     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14455       // C99 6.5.3.3p1: ok, fallthrough;
14456       if (Context.getLangOpts().CPlusPlus) {
14457         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14458         // operand contextually converted to bool.
14459         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14460                                   ScalarTypeToBooleanCastKind(resultType));
14461       } else if (Context.getLangOpts().OpenCL &&
14462                  Context.getLangOpts().OpenCLVersion < 120) {
14463         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14464         // operate on scalar float types.
14465         if (!resultType->isIntegerType() && !resultType->isPointerType())
14466           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14467                            << resultType << Input.get()->getSourceRange());
14468       }
14469     } else if (resultType->isExtVectorType()) {
14470       if (Context.getLangOpts().OpenCL &&
14471           Context.getLangOpts().OpenCLVersion < 120 &&
14472           !Context.getLangOpts().OpenCLCPlusPlus) {
14473         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14474         // operate on vector float types.
14475         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14476         if (!T->isIntegerType())
14477           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14478                            << resultType << Input.get()->getSourceRange());
14479       }
14480       // Vector logical not returns the signed variant of the operand type.
14481       resultType = GetSignedVectorType(resultType);
14482       break;
14483     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14484       const VectorType *VTy = resultType->castAs<VectorType>();
14485       if (VTy->getVectorKind() != VectorType::GenericVector)
14486         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14487                          << resultType << Input.get()->getSourceRange());
14488
14489       // Vector logical not returns the signed variant of the operand type.
14490       resultType = GetSignedVectorType(resultType);
14491       break;
14492     } else {
14493       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14494         << resultType << Input.get()->getSourceRange());
14495     }
14496
14497     // LNot always has type int. C99 6.5.3.3p5.
14498     // In C++, it's bool. C++ 5.3.1p8
14499     resultType = Context.getLogicalOperationType();
14500     break;
14501   case UO_Real:
14502   case UO_Imag:
14503     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14504     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14505     // complex l-values to ordinary l-values and all other values to r-values.
14506     if (Input.isInvalid()) return ExprError();
14507     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14508       if (Input.get()->getValueKind() != VK_RValue &&
14509           Input.get()->getObjectKind() == OK_Ordinary)
14510         VK = Input.get()->getValueKind();
14511     } else if (!getLangOpts().CPlusPlus) {
14512       // In C, a volatile scalar is read by __imag. In C++, it is not.
14513       Input = DefaultLvalueConversion(Input.get());
14514     }
14515     break;
14516   case UO_Extension:
14517     resultType = Input.get()->getType();
14518     VK = Input.get()->getValueKind();
14519     OK = Input.get()->getObjectKind();
14520     break;
14521   case UO_Coawait:
14522     // It's unnecessary to represent the pass-through operator co_await in the
14523     // AST; just return the input expression instead.
14524     assert(!Input.get()->getType()->isDependentType() &&
14525                    "the co_await expression must be non-dependant before "
14526                    "building operator co_await");
14527     return Input;
14528   }
14529   if (resultType.isNull() || Input.isInvalid())
14530     return ExprError();
14531
14532   // Check for array bounds violations in the operand of the UnaryOperator,
14533   // except for the '*' and '&' operators that have to be handled specially
14534   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14535   // that are explicitly defined as valid by the standard).
14536   if (Opc != UO_AddrOf && Opc != UO_Deref)
14537     CheckArrayAccess(Input.get());
14538
14539   auto *UO =
14540       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14541                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14542
14543   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14544       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14545     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14546
14547   // Convert the result back to a half vector.
14548   if (ConvertHalfVec)
14549     return convertVector(UO, Context.HalfTy, *this);
14550   return UO;
14551 }
14552
14553 /// Determine whether the given expression is a qualified member
14554 /// access expression, of a form that could be turned into a pointer to member
14555 /// with the address-of operator.
14556 bool Sema::isQualifiedMemberAccess(Expr *E) {
14557   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14558     if (!DRE->getQualifier())
14559       return false;
14560
14561     ValueDecl *VD = DRE->getDecl();
14562     if (!VD->isCXXClassMember())
14563       return false;
14564
14565     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14566       return true;
14567     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14568       return Method->isInstance();
14569
14570     return false;
14571   }
14572
14573   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14574     if (!ULE->getQualifier())
14575       return false;
14576
14577     for (NamedDecl *D : ULE->decls()) {
14578       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14579         if (Method->isInstance())
14580           return true;
14581       } else {
14582         // Overload set does not contain methods.
14583         break;
14584       }
14585     }
14586
14587     return false;
14588   }
14589
14590   return false;
14591 }
14592
14593 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14594                               UnaryOperatorKind Opc, Expr *Input) {
14595   // First things first: handle placeholders so that the
14596   // overloaded-operator check considers the right type.
14597   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14598     // Increment and decrement of pseudo-object references.
14599     if (pty->getKind() == BuiltinType::PseudoObject &&
14600         UnaryOperator::isIncrementDecrementOp(Opc))
14601       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14602
14603     // extension is always a builtin operator.
14604     if (Opc == UO_Extension)
14605       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14606
14607     // & gets special logic for several kinds of placeholder.
14608     // The builtin code knows what to do.
14609     if (Opc == UO_AddrOf &&
14610         (pty->getKind() == BuiltinType::Overload ||
14611          pty->getKind() == BuiltinType::UnknownAny ||
14612          pty->getKind() == BuiltinType::BoundMember))
14613       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14614
14615     // Anything else needs to be handled now.
14616     ExprResult Result = CheckPlaceholderExpr(Input);
14617     if (Result.isInvalid()) return ExprError();
14618     Input = Result.get();
14619   }
14620
14621   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14622       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14623       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14624     // Find all of the overloaded operators visible from this
14625     // point. We perform both an operator-name lookup from the local
14626     // scope and an argument-dependent lookup based on the types of
14627     // the arguments.
14628     UnresolvedSet<16> Functions;
14629     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14630     if (S && OverOp != OO_None)
14631       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14632                                    Functions);
14633
14634     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14635   }
14636
14637   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14638 }
14639
14640 // Unary Operators.  'Tok' is the token for the operator.
14641 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14642                               tok::TokenKind Op, Expr *Input) {
14643   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14644 }
14645
14646 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14647 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14648                                 LabelDecl *TheDecl) {
14649   TheDecl->markUsed(Context);
14650   // Create the AST node.  The address of a label always has type 'void*'.
14651   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14652                                      Context.getPointerType(Context.VoidTy));
14653 }
14654
14655 void Sema::ActOnStartStmtExpr() {
14656   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14657 }
14658
14659 void Sema::ActOnStmtExprError() {
14660   // Note that function is also called by TreeTransform when leaving a
14661   // StmtExpr scope without rebuilding anything.
14662
14663   DiscardCleanupsInEvaluationContext();
14664   PopExpressionEvaluationContext();
14665 }
14666
14667 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14668                                SourceLocation RPLoc) {
14669   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14670 }
14671
14672 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14673                                SourceLocation RPLoc, unsigned TemplateDepth) {
14674   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14675   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14676
14677   if (hasAnyUnrecoverableErrorsInThisFunction())
14678     DiscardCleanupsInEvaluationContext();
14679   assert(!Cleanup.exprNeedsCleanups() &&
14680          "cleanups within StmtExpr not correctly bound!");
14681   PopExpressionEvaluationContext();
14682
14683   // FIXME: there are a variety of strange constraints to enforce here, for
14684   // example, it is not possible to goto into a stmt expression apparently.
14685   // More semantic analysis is needed.
14686
14687   // If there are sub-stmts in the compound stmt, take the type of the last one
14688   // as the type of the stmtexpr.
14689   QualType Ty = Context.VoidTy;
14690   bool StmtExprMayBindToTemp = false;
14691   if (!Compound->body_empty()) {
14692     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14693     if (const auto *LastStmt =
14694             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14695       if (const Expr *Value = LastStmt->getExprStmt()) {
14696         StmtExprMayBindToTemp = true;
14697         Ty = Value->getType();
14698       }
14699     }
14700   }
14701
14702   // FIXME: Check that expression type is complete/non-abstract; statement
14703   // expressions are not lvalues.
14704   Expr *ResStmtExpr =
14705       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14706   if (StmtExprMayBindToTemp)
14707     return MaybeBindToTemporary(ResStmtExpr);
14708   return ResStmtExpr;
14709 }
14710
14711 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14712   if (ER.isInvalid())
14713     return ExprError();
14714
14715   // Do function/array conversion on the last expression, but not
14716   // lvalue-to-rvalue.  However, initialize an unqualified type.
14717   ER = DefaultFunctionArrayConversion(ER.get());
14718   if (ER.isInvalid())
14719     return ExprError();
14720   Expr *E = ER.get();
14721
14722   if (E->isTypeDependent())
14723     return E;
14724
14725   // In ARC, if the final expression ends in a consume, splice
14726   // the consume out and bind it later.  In the alternate case
14727   // (when dealing with a retainable type), the result
14728   // initialization will create a produce.  In both cases the
14729   // result will be +1, and we'll need to balance that out with
14730   // a bind.
14731   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14732   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14733     return Cast->getSubExpr();
14734
14735   // FIXME: Provide a better location for the initialization.
14736   return PerformCopyInitialization(
14737       InitializedEntity::InitializeStmtExprResult(
14738           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14739       SourceLocation(), E);
14740 }
14741
14742 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14743                                       TypeSourceInfo *TInfo,
14744                                       ArrayRef<OffsetOfComponent> Components,
14745                                       SourceLocation RParenLoc) {
14746   QualType ArgTy = TInfo->getType();
14747   bool Dependent = ArgTy->isDependentType();
14748   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14749
14750   // We must have at least one component that refers to the type, and the first
14751   // one is known to be a field designator.  Verify that the ArgTy represents
14752   // a struct/union/class.
14753   if (!Dependent && !ArgTy->isRecordType())
14754     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14755                        << ArgTy << TypeRange);
14756
14757   // Type must be complete per C99 7.17p3 because a declaring a variable
14758   // with an incomplete type would be ill-formed.
14759   if (!Dependent
14760       && RequireCompleteType(BuiltinLoc, ArgTy,
14761                              diag::err_offsetof_incomplete_type, TypeRange))
14762     return ExprError();
14763
14764   bool DidWarnAboutNonPOD = false;
14765   QualType CurrentType = ArgTy;
14766   SmallVector<OffsetOfNode, 4> Comps;
14767   SmallVector<Expr*, 4> Exprs;
14768   for (const OffsetOfComponent &OC : Components) {
14769     if (OC.isBrackets) {
14770       // Offset of an array sub-field.  TODO: Should we allow vector elements?
14771       if (!CurrentType->isDependentType()) {
14772         const ArrayType *AT = Context.getAsArrayType(CurrentType);
14773         if(!AT)
14774           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14775                            << CurrentType);
14776         CurrentType = AT->getElementType();
14777       } else
14778         CurrentType = Context.DependentTy;
14779
14780       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14781       if (IdxRval.isInvalid())
14782         return ExprError();
14783       Expr *Idx = IdxRval.get();
14784
14785       // The expression must be an integral expression.
14786       // FIXME: An integral constant expression?
14787       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14788           !Idx->getType()->isIntegerType())
14789         return ExprError(
14790             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14791             << Idx->getSourceRange());
14792
14793       // Record this array index.
14794       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14795       Exprs.push_back(Idx);
14796       continue;
14797     }
14798
14799     // Offset of a field.
14800     if (CurrentType->isDependentType()) {
14801       // We have the offset of a field, but we can't look into the dependent
14802       // type. Just record the identifier of the field.
14803       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14804       CurrentType = Context.DependentTy;
14805       continue;
14806     }
14807
14808     // We need to have a complete type to look into.
14809     if (RequireCompleteType(OC.LocStart, CurrentType,
14810                             diag::err_offsetof_incomplete_type))
14811       return ExprError();
14812
14813     // Look for the designated field.
14814     const RecordType *RC = CurrentType->getAs<RecordType>();
14815     if (!RC)
14816       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14817                        << CurrentType);
14818     RecordDecl *RD = RC->getDecl();
14819
14820     // C++ [lib.support.types]p5:
14821     //   The macro offsetof accepts a restricted set of type arguments in this
14822     //   International Standard. type shall be a POD structure or a POD union
14823     //   (clause 9).
14824     // C++11 [support.types]p4:
14825     //   If type is not a standard-layout class (Clause 9), the results are
14826     //   undefined.
14827     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14828       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14829       unsigned DiagID =
14830         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14831                             : diag::ext_offsetof_non_pod_type;
14832
14833       if (!IsSafe && !DidWarnAboutNonPOD &&
14834           DiagRuntimeBehavior(BuiltinLoc, nullptr,
14835                               PDiag(DiagID)
14836                               << SourceRange(Components[0].LocStart, OC.LocEnd)
14837                               << CurrentType))
14838         DidWarnAboutNonPOD = true;
14839     }
14840
14841     // Look for the field.
14842     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14843     LookupQualifiedName(R, RD);
14844     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14845     IndirectFieldDecl *IndirectMemberDecl = nullptr;
14846     if (!MemberDecl) {
14847       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14848         MemberDecl = IndirectMemberDecl->getAnonField();
14849     }
14850
14851     if (!MemberDecl)
14852       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14853                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14854                                                               OC.LocEnd));
14855
14856     // C99 7.17p3:
14857     //   (If the specified member is a bit-field, the behavior is undefined.)
14858     //
14859     // We diagnose this as an error.
14860     if (MemberDecl->isBitField()) {
14861       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14862         << MemberDecl->getDeclName()
14863         << SourceRange(BuiltinLoc, RParenLoc);
14864       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14865       return ExprError();
14866     }
14867
14868     RecordDecl *Parent = MemberDecl->getParent();
14869     if (IndirectMemberDecl)
14870       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14871
14872     // If the member was found in a base class, introduce OffsetOfNodes for
14873     // the base class indirections.
14874     CXXBasePaths Paths;
14875     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14876                       Paths)) {
14877       if (Paths.getDetectedVirtual()) {
14878         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14879           << MemberDecl->getDeclName()
14880           << SourceRange(BuiltinLoc, RParenLoc);
14881         return ExprError();
14882       }
14883
14884       CXXBasePath &Path = Paths.front();
14885       for (const CXXBasePathElement &B : Path)
14886         Comps.push_back(OffsetOfNode(B.Base));
14887     }
14888
14889     if (IndirectMemberDecl) {
14890       for (auto *FI : IndirectMemberDecl->chain()) {
14891         assert(isa<FieldDecl>(FI));
14892         Comps.push_back(OffsetOfNode(OC.LocStart,
14893                                      cast<FieldDecl>(FI), OC.LocEnd));
14894       }
14895     } else
14896       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14897
14898     CurrentType = MemberDecl->getType().getNonReferenceType();
14899   }
14900
14901   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14902                               Comps, Exprs, RParenLoc);
14903 }
14904
14905 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14906                                       SourceLocation BuiltinLoc,
14907                                       SourceLocation TypeLoc,
14908                                       ParsedType ParsedArgTy,
14909                                       ArrayRef<OffsetOfComponent> Components,
14910                                       SourceLocation RParenLoc) {
14911
14912   TypeSourceInfo *ArgTInfo;
14913   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14914   if (ArgTy.isNull())
14915     return ExprError();
14916
14917   if (!ArgTInfo)
14918     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14919
14920   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14921 }
14922
14923
14924 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14925                                  Expr *CondExpr,
14926                                  Expr *LHSExpr, Expr *RHSExpr,
14927                                  SourceLocation RPLoc) {
14928   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14929
14930   ExprValueKind VK = VK_RValue;
14931   ExprObjectKind OK = OK_Ordinary;
14932   QualType resType;
14933   bool CondIsTrue = false;
14934   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14935     resType = Context.DependentTy;
14936   } else {
14937     // The conditional expression is required to be a constant expression.
14938     llvm::APSInt condEval(32);
14939     ExprResult CondICE
14940       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14941           diag::err_typecheck_choose_expr_requires_constant, false);
14942     if (CondICE.isInvalid())
14943       return ExprError();
14944     CondExpr = CondICE.get();
14945     CondIsTrue = condEval.getZExtValue();
14946
14947     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14948     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14949
14950     resType = ActiveExpr->getType();
14951     VK = ActiveExpr->getValueKind();
14952     OK = ActiveExpr->getObjectKind();
14953   }
14954
14955   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14956                                   resType, VK, OK, RPLoc, CondIsTrue);
14957 }
14958
14959 //===----------------------------------------------------------------------===//
14960 // Clang Extensions.
14961 //===----------------------------------------------------------------------===//
14962
14963 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14964 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14965   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14966
14967   if (LangOpts.CPlusPlus) {
14968     MangleNumberingContext *MCtx;
14969     Decl *ManglingContextDecl;
14970     std::tie(MCtx, ManglingContextDecl) =
14971         getCurrentMangleNumberContext(Block->getDeclContext());
14972     if (MCtx) {
14973       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14974       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14975     }
14976   }
14977
14978   PushBlockScope(CurScope, Block);
14979   CurContext->addDecl(Block);
14980   if (CurScope)
14981     PushDeclContext(CurScope, Block);
14982   else
14983     CurContext = Block;
14984
14985   getCurBlock()->HasImplicitReturnType = true;
14986
14987   // Enter a new evaluation context to insulate the block from any
14988   // cleanups from the enclosing full-expression.
14989   PushExpressionEvaluationContext(
14990       ExpressionEvaluationContext::PotentiallyEvaluated);
14991 }
14992
14993 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14994                                Scope *CurScope) {
14995   assert(ParamInfo.getIdentifier() == nullptr &&
14996          "block-id should have no identifier!");
14997   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14998   BlockScopeInfo *CurBlock = getCurBlock();
14999
15000   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15001   QualType T = Sig->getType();
15002
15003   // FIXME: We should allow unexpanded parameter packs here, but that would,
15004   // in turn, make the block expression contain unexpanded parameter packs.
15005   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15006     // Drop the parameters.
15007     FunctionProtoType::ExtProtoInfo EPI;
15008     EPI.HasTrailingReturn = false;
15009     EPI.TypeQuals.addConst();
15010     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15011     Sig = Context.getTrivialTypeSourceInfo(T);
15012   }
15013
15014   // GetTypeForDeclarator always produces a function type for a block
15015   // literal signature.  Furthermore, it is always a FunctionProtoType
15016   // unless the function was written with a typedef.
15017   assert(T->isFunctionType() &&
15018          "GetTypeForDeclarator made a non-function block signature");
15019
15020   // Look for an explicit signature in that function type.
15021   FunctionProtoTypeLoc ExplicitSignature;
15022
15023   if ((ExplicitSignature = Sig->getTypeLoc()
15024                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15025
15026     // Check whether that explicit signature was synthesized by
15027     // GetTypeForDeclarator.  If so, don't save that as part of the
15028     // written signature.
15029     if (ExplicitSignature.getLocalRangeBegin() ==
15030         ExplicitSignature.getLocalRangeEnd()) {
15031       // This would be much cheaper if we stored TypeLocs instead of
15032       // TypeSourceInfos.
15033       TypeLoc Result = ExplicitSignature.getReturnLoc();
15034       unsigned Size = Result.getFullDataSize();
15035       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15036       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15037
15038       ExplicitSignature = FunctionProtoTypeLoc();
15039     }
15040   }
15041
15042   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15043   CurBlock->FunctionType = T;
15044
15045   const FunctionType *Fn = T->getAs<FunctionType>();
15046   QualType RetTy = Fn->getReturnType();
15047   bool isVariadic =
15048     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15049
15050   CurBlock->TheDecl->setIsVariadic(isVariadic);
15051
15052   // Context.DependentTy is used as a placeholder for a missing block
15053   // return type.  TODO:  what should we do with declarators like:
15054   //   ^ * { ... }
15055   // If the answer is "apply template argument deduction"....
15056   if (RetTy != Context.DependentTy) {
15057     CurBlock->ReturnType = RetTy;
15058     CurBlock->TheDecl->setBlockMissingReturnType(false);
15059     CurBlock->HasImplicitReturnType = false;
15060   }
15061
15062   // Push block parameters from the declarator if we had them.
15063   SmallVector<ParmVarDecl*, 8> Params;
15064   if (ExplicitSignature) {
15065     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15066       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15067       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15068           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15069         // Diagnose this as an extension in C17 and earlier.
15070         if (!getLangOpts().C2x)
15071           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15072       }
15073       Params.push_back(Param);
15074     }
15075
15076   // Fake up parameter variables if we have a typedef, like
15077   //   ^ fntype { ... }
15078   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15079     for (const auto &I : Fn->param_types()) {
15080       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15081           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15082       Params.push_back(Param);
15083     }
15084   }
15085
15086   // Set the parameters on the block decl.
15087   if (!Params.empty()) {
15088     CurBlock->TheDecl->setParams(Params);
15089     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15090                              /*CheckParameterNames=*/false);
15091   }
15092
15093   // Finally we can process decl attributes.
15094   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15095
15096   // Put the parameter variables in scope.
15097   for (auto AI : CurBlock->TheDecl->parameters()) {
15098     AI->setOwningFunction(CurBlock->TheDecl);
15099
15100     // If this has an identifier, add it to the scope stack.
15101     if (AI->getIdentifier()) {
15102       CheckShadow(CurBlock->TheScope, AI);
15103
15104       PushOnScopeChains(AI, CurBlock->TheScope);
15105     }
15106   }
15107 }
15108
15109 /// ActOnBlockError - If there is an error parsing a block, this callback
15110 /// is invoked to pop the information about the block from the action impl.
15111 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15112   // Leave the expression-evaluation context.
15113   DiscardCleanupsInEvaluationContext();
15114   PopExpressionEvaluationContext();
15115
15116   // Pop off CurBlock, handle nested blocks.
15117   PopDeclContext();
15118   PopFunctionScopeInfo();
15119 }
15120
15121 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15122 /// literal was successfully completed.  ^(int x){...}
15123 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15124                                     Stmt *Body, Scope *CurScope) {
15125   // If blocks are disabled, emit an error.
15126   if (!LangOpts.Blocks)
15127     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15128
15129   // Leave the expression-evaluation context.
15130   if (hasAnyUnrecoverableErrorsInThisFunction())
15131     DiscardCleanupsInEvaluationContext();
15132   assert(!Cleanup.exprNeedsCleanups() &&
15133          "cleanups within block not correctly bound!");
15134   PopExpressionEvaluationContext();
15135
15136   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15137   BlockDecl *BD = BSI->TheDecl;
15138
15139   if (BSI->HasImplicitReturnType)
15140     deduceClosureReturnType(*BSI);
15141
15142   QualType RetTy = Context.VoidTy;
15143   if (!BSI->ReturnType.isNull())
15144     RetTy = BSI->ReturnType;
15145
15146   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15147   QualType BlockTy;
15148
15149   // If the user wrote a function type in some form, try to use that.
15150   if (!BSI->FunctionType.isNull()) {
15151     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15152
15153     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15154     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15155
15156     // Turn protoless block types into nullary block types.
15157     if (isa<FunctionNoProtoType>(FTy)) {
15158       FunctionProtoType::ExtProtoInfo EPI;
15159       EPI.ExtInfo = Ext;
15160       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15161
15162     // Otherwise, if we don't need to change anything about the function type,
15163     // preserve its sugar structure.
15164     } else if (FTy->getReturnType() == RetTy &&
15165                (!NoReturn || FTy->getNoReturnAttr())) {
15166       BlockTy = BSI->FunctionType;
15167
15168     // Otherwise, make the minimal modifications to the function type.
15169     } else {
15170       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15171       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15172       EPI.TypeQuals = Qualifiers();
15173       EPI.ExtInfo = Ext;
15174       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15175     }
15176
15177   // If we don't have a function type, just build one from nothing.
15178   } else {
15179     FunctionProtoType::ExtProtoInfo EPI;
15180     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15181     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15182   }
15183
15184   DiagnoseUnusedParameters(BD->parameters());
15185   BlockTy = Context.getBlockPointerType(BlockTy);
15186
15187   // If needed, diagnose invalid gotos and switches in the block.
15188   if (getCurFunction()->NeedsScopeChecking() &&
15189       !PP.isCodeCompletionEnabled())
15190     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15191
15192   BD->setBody(cast<CompoundStmt>(Body));
15193
15194   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15195     DiagnoseUnguardedAvailabilityViolations(BD);
15196
15197   // Try to apply the named return value optimization. We have to check again
15198   // if we can do this, though, because blocks keep return statements around
15199   // to deduce an implicit return type.
15200   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15201       !BD->isDependentContext())
15202     computeNRVO(Body, BSI);
15203
15204   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15205       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15206     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15207                           NTCUK_Destruct|NTCUK_Copy);
15208
15209   PopDeclContext();
15210
15211   // Pop the block scope now but keep it alive to the end of this function.
15212   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15213   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15214
15215   // Set the captured variables on the block.
15216   SmallVector<BlockDecl::Capture, 4> Captures;
15217   for (Capture &Cap : BSI->Captures) {
15218     if (Cap.isInvalid() || Cap.isThisCapture())
15219       continue;
15220
15221     VarDecl *Var = Cap.getVariable();
15222     Expr *CopyExpr = nullptr;
15223     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15224       if (const RecordType *Record =
15225               Cap.getCaptureType()->getAs<RecordType>()) {
15226         // The capture logic needs the destructor, so make sure we mark it.
15227         // Usually this is unnecessary because most local variables have
15228         // their destructors marked at declaration time, but parameters are
15229         // an exception because it's technically only the call site that
15230         // actually requires the destructor.
15231         if (isa<ParmVarDecl>(Var))
15232           FinalizeVarWithDestructor(Var, Record);
15233
15234         // Enter a separate potentially-evaluated context while building block
15235         // initializers to isolate their cleanups from those of the block
15236         // itself.
15237         // FIXME: Is this appropriate even when the block itself occurs in an
15238         // unevaluated operand?
15239         EnterExpressionEvaluationContext EvalContext(
15240             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15241
15242         SourceLocation Loc = Cap.getLocation();
15243
15244         ExprResult Result = BuildDeclarationNameExpr(
15245             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15246
15247         // According to the blocks spec, the capture of a variable from
15248         // the stack requires a const copy constructor.  This is not true
15249         // of the copy/move done to move a __block variable to the heap.
15250         if (!Result.isInvalid() &&
15251             !Result.get()->getType().isConstQualified()) {
15252           Result = ImpCastExprToType(Result.get(),
15253                                      Result.get()->getType().withConst(),
15254                                      CK_NoOp, VK_LValue);
15255         }
15256
15257         if (!Result.isInvalid()) {
15258           Result = PerformCopyInitialization(
15259               InitializedEntity::InitializeBlock(Var->getLocation(),
15260                                                  Cap.getCaptureType(), false),
15261               Loc, Result.get());
15262         }
15263
15264         // Build a full-expression copy expression if initialization
15265         // succeeded and used a non-trivial constructor.  Recover from
15266         // errors by pretending that the copy isn't necessary.
15267         if (!Result.isInvalid() &&
15268             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15269                 ->isTrivial()) {
15270           Result = MaybeCreateExprWithCleanups(Result);
15271           CopyExpr = Result.get();
15272         }
15273       }
15274     }
15275
15276     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15277                               CopyExpr);
15278     Captures.push_back(NewCap);
15279   }
15280   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15281
15282   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15283
15284   // If the block isn't obviously global, i.e. it captures anything at
15285   // all, then we need to do a few things in the surrounding context:
15286   if (Result->getBlockDecl()->hasCaptures()) {
15287     // First, this expression has a new cleanup object.
15288     ExprCleanupObjects.push_back(Result->getBlockDecl());
15289     Cleanup.setExprNeedsCleanups(true);
15290
15291     // It also gets a branch-protected scope if any of the captured
15292     // variables needs destruction.
15293     for (const auto &CI : Result->getBlockDecl()->captures()) {
15294       const VarDecl *var = CI.getVariable();
15295       if (var->getType().isDestructedType() != QualType::DK_none) {
15296         setFunctionHasBranchProtectedScope();
15297         break;
15298       }
15299     }
15300   }
15301
15302   if (getCurFunction())
15303     getCurFunction()->addBlock(BD);
15304
15305   return Result;
15306 }
15307
15308 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15309                             SourceLocation RPLoc) {
15310   TypeSourceInfo *TInfo;
15311   GetTypeFromParser(Ty, &TInfo);
15312   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15313 }
15314
15315 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15316                                 Expr *E, TypeSourceInfo *TInfo,
15317                                 SourceLocation RPLoc) {
15318   Expr *OrigExpr = E;
15319   bool IsMS = false;
15320
15321   // CUDA device code does not support varargs.
15322   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15323     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15324       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15325       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15326         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15327     }
15328   }
15329
15330   // NVPTX does not support va_arg expression.
15331   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15332       Context.getTargetInfo().getTriple().isNVPTX())
15333     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15334
15335   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15336   // as Microsoft ABI on an actual Microsoft platform, where
15337   // __builtin_ms_va_list and __builtin_va_list are the same.)
15338   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15339       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15340     QualType MSVaListType = Context.getBuiltinMSVaListType();
15341     if (Context.hasSameType(MSVaListType, E->getType())) {
15342       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15343         return ExprError();
15344       IsMS = true;
15345     }
15346   }
15347
15348   // Get the va_list type
15349   QualType VaListType = Context.getBuiltinVaListType();
15350   if (!IsMS) {
15351     if (VaListType->isArrayType()) {
15352       // Deal with implicit array decay; for example, on x86-64,
15353       // va_list is an array, but it's supposed to decay to
15354       // a pointer for va_arg.
15355       VaListType = Context.getArrayDecayedType(VaListType);
15356       // Make sure the input expression also decays appropriately.
15357       ExprResult Result = UsualUnaryConversions(E);
15358       if (Result.isInvalid())
15359         return ExprError();
15360       E = Result.get();
15361     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15362       // If va_list is a record type and we are compiling in C++ mode,
15363       // check the argument using reference binding.
15364       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15365           Context, Context.getLValueReferenceType(VaListType), false);
15366       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15367       if (Init.isInvalid())
15368         return ExprError();
15369       E = Init.getAs<Expr>();
15370     } else {
15371       // Otherwise, the va_list argument must be an l-value because
15372       // it is modified by va_arg.
15373       if (!E->isTypeDependent() &&
15374           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15375         return ExprError();
15376     }
15377   }
15378
15379   if (!IsMS && !E->isTypeDependent() &&
15380       !Context.hasSameType(VaListType, E->getType()))
15381     return ExprError(
15382         Diag(E->getBeginLoc(),
15383              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15384         << OrigExpr->getType() << E->getSourceRange());
15385
15386   if (!TInfo->getType()->isDependentType()) {
15387     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15388                             diag::err_second_parameter_to_va_arg_incomplete,
15389                             TInfo->getTypeLoc()))
15390       return ExprError();
15391
15392     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15393                                TInfo->getType(),
15394                                diag::err_second_parameter_to_va_arg_abstract,
15395                                TInfo->getTypeLoc()))
15396       return ExprError();
15397
15398     if (!TInfo->getType().isPODType(Context)) {
15399       Diag(TInfo->getTypeLoc().getBeginLoc(),
15400            TInfo->getType()->isObjCLifetimeType()
15401              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15402              : diag::warn_second_parameter_to_va_arg_not_pod)
15403         << TInfo->getType()
15404         << TInfo->getTypeLoc().getSourceRange();
15405     }
15406
15407     // Check for va_arg where arguments of the given type will be promoted
15408     // (i.e. this va_arg is guaranteed to have undefined behavior).
15409     QualType PromoteType;
15410     if (TInfo->getType()->isPromotableIntegerType()) {
15411       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15412       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15413         PromoteType = QualType();
15414     }
15415     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15416       PromoteType = Context.DoubleTy;
15417     if (!PromoteType.isNull())
15418       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15419                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15420                           << TInfo->getType()
15421                           << PromoteType
15422                           << TInfo->getTypeLoc().getSourceRange());
15423   }
15424
15425   QualType T = TInfo->getType().getNonLValueExprType(Context);
15426   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15427 }
15428
15429 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15430   // The type of __null will be int or long, depending on the size of
15431   // pointers on the target.
15432   QualType Ty;
15433   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15434   if (pw == Context.getTargetInfo().getIntWidth())
15435     Ty = Context.IntTy;
15436   else if (pw == Context.getTargetInfo().getLongWidth())
15437     Ty = Context.LongTy;
15438   else if (pw == Context.getTargetInfo().getLongLongWidth())
15439     Ty = Context.LongLongTy;
15440   else {
15441     llvm_unreachable("I don't know size of pointer!");
15442   }
15443
15444   return new (Context) GNUNullExpr(Ty, TokenLoc);
15445 }
15446
15447 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15448                                     SourceLocation BuiltinLoc,
15449                                     SourceLocation RPLoc) {
15450   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15451 }
15452
15453 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15454                                     SourceLocation BuiltinLoc,
15455                                     SourceLocation RPLoc,
15456                                     DeclContext *ParentContext) {
15457   return new (Context)
15458       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15459 }
15460
15461 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15462                                         bool Diagnose) {
15463   if (!getLangOpts().ObjC)
15464     return false;
15465
15466   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15467   if (!PT)
15468     return false;
15469   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15470
15471   // Ignore any parens, implicit casts (should only be
15472   // array-to-pointer decays), and not-so-opaque values.  The last is
15473   // important for making this trigger for property assignments.
15474   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15475   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15476     if (OV->getSourceExpr())
15477       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15478
15479   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15480     if (!PT->isObjCIdType() &&
15481         !(ID && ID->getIdentifier()->isStr("NSString")))
15482       return false;
15483     if (!SL->isAscii())
15484       return false;
15485
15486     if (Diagnose) {
15487       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15488           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15489       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15490     }
15491     return true;
15492   }
15493
15494   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15495       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15496       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15497       !SrcExpr->isNullPointerConstant(
15498           getASTContext(), Expr::NPC_NeverValueDependent)) {
15499     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15500       return false;
15501     if (Diagnose) {
15502       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15503           << /*number*/1
15504           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15505       Expr *NumLit =
15506           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15507       if (NumLit)
15508         Exp = NumLit;
15509     }
15510     return true;
15511   }
15512
15513   return false;
15514 }
15515
15516 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15517                                               const Expr *SrcExpr) {
15518   if (!DstType->isFunctionPointerType() ||
15519       !SrcExpr->getType()->isFunctionType())
15520     return false;
15521
15522   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15523   if (!DRE)
15524     return false;
15525
15526   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15527   if (!FD)
15528     return false;
15529
15530   return !S.checkAddressOfFunctionIsAvailable(FD,
15531                                               /*Complain=*/true,
15532                                               SrcExpr->getBeginLoc());
15533 }
15534
15535 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15536                                     SourceLocation Loc,
15537                                     QualType DstType, QualType SrcType,
15538                                     Expr *SrcExpr, AssignmentAction Action,
15539                                     bool *Complained) {
15540   if (Complained)
15541     *Complained = false;
15542
15543   // Decode the result (notice that AST's are still created for extensions).
15544   bool CheckInferredResultType = false;
15545   bool isInvalid = false;
15546   unsigned DiagKind = 0;
15547   FixItHint Hint;
15548   ConversionFixItGenerator ConvHints;
15549   bool MayHaveConvFixit = false;
15550   bool MayHaveFunctionDiff = false;
15551   const ObjCInterfaceDecl *IFace = nullptr;
15552   const ObjCProtocolDecl *PDecl = nullptr;
15553
15554   switch (ConvTy) {
15555   case Compatible:
15556       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15557       return false;
15558
15559   case PointerToInt:
15560     if (getLangOpts().CPlusPlus) {
15561       DiagKind = diag::err_typecheck_convert_pointer_int;
15562       isInvalid = true;
15563     } else {
15564       DiagKind = diag::ext_typecheck_convert_pointer_int;
15565     }
15566     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15567     MayHaveConvFixit = true;
15568     break;
15569   case IntToPointer:
15570     if (getLangOpts().CPlusPlus) {
15571       DiagKind = diag::err_typecheck_convert_int_pointer;
15572       isInvalid = true;
15573     } else {
15574       DiagKind = diag::ext_typecheck_convert_int_pointer;
15575     }
15576     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15577     MayHaveConvFixit = true;
15578     break;
15579   case IncompatibleFunctionPointer:
15580     if (getLangOpts().CPlusPlus) {
15581       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15582       isInvalid = true;
15583     } else {
15584       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15585     }
15586     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15587     MayHaveConvFixit = true;
15588     break;
15589   case IncompatiblePointer:
15590     if (Action == AA_Passing_CFAudited) {
15591       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15592     } else if (getLangOpts().CPlusPlus) {
15593       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15594       isInvalid = true;
15595     } else {
15596       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15597     }
15598     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15599       SrcType->isObjCObjectPointerType();
15600     if (Hint.isNull() && !CheckInferredResultType) {
15601       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15602     }
15603     else if (CheckInferredResultType) {
15604       SrcType = SrcType.getUnqualifiedType();
15605       DstType = DstType.getUnqualifiedType();
15606     }
15607     MayHaveConvFixit = true;
15608     break;
15609   case IncompatiblePointerSign:
15610     if (getLangOpts().CPlusPlus) {
15611       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15612       isInvalid = true;
15613     } else {
15614       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15615     }
15616     break;
15617   case FunctionVoidPointer:
15618     if (getLangOpts().CPlusPlus) {
15619       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15620       isInvalid = true;
15621     } else {
15622       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15623     }
15624     break;
15625   case IncompatiblePointerDiscardsQualifiers: {
15626     // Perform array-to-pointer decay if necessary.
15627     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15628
15629     isInvalid = true;
15630
15631     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15632     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15633     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15634       DiagKind = diag::err_typecheck_incompatible_address_space;
15635       break;
15636
15637     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15638       DiagKind = diag::err_typecheck_incompatible_ownership;
15639       break;
15640     }
15641
15642     llvm_unreachable("unknown error case for discarding qualifiers!");
15643     // fallthrough
15644   }
15645   case CompatiblePointerDiscardsQualifiers:
15646     // If the qualifiers lost were because we were applying the
15647     // (deprecated) C++ conversion from a string literal to a char*
15648     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15649     // Ideally, this check would be performed in
15650     // checkPointerTypesForAssignment. However, that would require a
15651     // bit of refactoring (so that the second argument is an
15652     // expression, rather than a type), which should be done as part
15653     // of a larger effort to fix checkPointerTypesForAssignment for
15654     // C++ semantics.
15655     if (getLangOpts().CPlusPlus &&
15656         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15657       return false;
15658     if (getLangOpts().CPlusPlus) {
15659       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15660       isInvalid = true;
15661     } else {
15662       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15663     }
15664
15665     break;
15666   case IncompatibleNestedPointerQualifiers:
15667     if (getLangOpts().CPlusPlus) {
15668       isInvalid = true;
15669       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15670     } else {
15671       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15672     }
15673     break;
15674   case IncompatibleNestedPointerAddressSpaceMismatch:
15675     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15676     isInvalid = true;
15677     break;
15678   case IntToBlockPointer:
15679     DiagKind = diag::err_int_to_block_pointer;
15680     isInvalid = true;
15681     break;
15682   case IncompatibleBlockPointer:
15683     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15684     isInvalid = true;
15685     break;
15686   case IncompatibleObjCQualifiedId: {
15687     if (SrcType->isObjCQualifiedIdType()) {
15688       const ObjCObjectPointerType *srcOPT =
15689                 SrcType->castAs<ObjCObjectPointerType>();
15690       for (auto *srcProto : srcOPT->quals()) {
15691         PDecl = srcProto;
15692         break;
15693       }
15694       if (const ObjCInterfaceType *IFaceT =
15695             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15696         IFace = IFaceT->getDecl();
15697     }
15698     else if (DstType->isObjCQualifiedIdType()) {
15699       const ObjCObjectPointerType *dstOPT =
15700         DstType->castAs<ObjCObjectPointerType>();
15701       for (auto *dstProto : dstOPT->quals()) {
15702         PDecl = dstProto;
15703         break;
15704       }
15705       if (const ObjCInterfaceType *IFaceT =
15706             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15707         IFace = IFaceT->getDecl();
15708     }
15709     if (getLangOpts().CPlusPlus) {
15710       DiagKind = diag::err_incompatible_qualified_id;
15711       isInvalid = true;
15712     } else {
15713       DiagKind = diag::warn_incompatible_qualified_id;
15714     }
15715     break;
15716   }
15717   case IncompatibleVectors:
15718     if (getLangOpts().CPlusPlus) {
15719       DiagKind = diag::err_incompatible_vectors;
15720       isInvalid = true;
15721     } else {
15722       DiagKind = diag::warn_incompatible_vectors;
15723     }
15724     break;
15725   case IncompatibleObjCWeakRef:
15726     DiagKind = diag::err_arc_weak_unavailable_assign;
15727     isInvalid = true;
15728     break;
15729   case Incompatible:
15730     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15731       if (Complained)
15732         *Complained = true;
15733       return true;
15734     }
15735
15736     DiagKind = diag::err_typecheck_convert_incompatible;
15737     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15738     MayHaveConvFixit = true;
15739     isInvalid = true;
15740     MayHaveFunctionDiff = true;
15741     break;
15742   }
15743
15744   QualType FirstType, SecondType;
15745   switch (Action) {
15746   case AA_Assigning:
15747   case AA_Initializing:
15748     // The destination type comes first.
15749     FirstType = DstType;
15750     SecondType = SrcType;
15751     break;
15752
15753   case AA_Returning:
15754   case AA_Passing:
15755   case AA_Passing_CFAudited:
15756   case AA_Converting:
15757   case AA_Sending:
15758   case AA_Casting:
15759     // The source type comes first.
15760     FirstType = SrcType;
15761     SecondType = DstType;
15762     break;
15763   }
15764
15765   PartialDiagnostic FDiag = PDiag(DiagKind);
15766   if (Action == AA_Passing_CFAudited)
15767     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15768   else
15769     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15770
15771   // If we can fix the conversion, suggest the FixIts.
15772   assert(ConvHints.isNull() || Hint.isNull());
15773   if (!ConvHints.isNull()) {
15774     for (FixItHint &H : ConvHints.Hints)
15775       FDiag << H;
15776   } else {
15777     FDiag << Hint;
15778   }
15779   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15780
15781   if (MayHaveFunctionDiff)
15782     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15783
15784   Diag(Loc, FDiag);
15785   if ((DiagKind == diag::warn_incompatible_qualified_id ||
15786        DiagKind == diag::err_incompatible_qualified_id) &&
15787       PDecl && IFace && !IFace->hasDefinition())
15788     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15789         << IFace << PDecl;
15790
15791   if (SecondType == Context.OverloadTy)
15792     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15793                               FirstType, /*TakingAddress=*/true);
15794
15795   if (CheckInferredResultType)
15796     EmitRelatedResultTypeNote(SrcExpr);
15797
15798   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15799     EmitRelatedResultTypeNoteForReturn(DstType);
15800
15801   if (Complained)
15802     *Complained = true;
15803   return isInvalid;
15804 }
15805
15806 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15807                                                  llvm::APSInt *Result) {
15808   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15809   public:
15810     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15811       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15812     }
15813   } Diagnoser;
15814
15815   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15816 }
15817
15818 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15819                                                  llvm::APSInt *Result,
15820                                                  unsigned DiagID,
15821                                                  bool AllowFold) {
15822   class IDDiagnoser : public VerifyICEDiagnoser {
15823     unsigned DiagID;
15824
15825   public:
15826     IDDiagnoser(unsigned DiagID)
15827       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15828
15829     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15830       S.Diag(Loc, DiagID) << SR;
15831     }
15832   } Diagnoser(DiagID);
15833
15834   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15835 }
15836
15837 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15838                                             SourceRange SR) {
15839   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15840 }
15841
15842 ExprResult
15843 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15844                                       VerifyICEDiagnoser &Diagnoser,
15845                                       bool AllowFold) {
15846   SourceLocation DiagLoc = E->getBeginLoc();
15847
15848   if (getLangOpts().CPlusPlus11) {
15849     // C++11 [expr.const]p5:
15850     //   If an expression of literal class type is used in a context where an
15851     //   integral constant expression is required, then that class type shall
15852     //   have a single non-explicit conversion function to an integral or
15853     //   unscoped enumeration type
15854     ExprResult Converted;
15855     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15856     public:
15857       CXX11ConvertDiagnoser(bool Silent)
15858           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15859                                 Silent, true) {}
15860
15861       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15862                                            QualType T) override {
15863         return S.Diag(Loc, diag::err_ice_not_integral) << T;
15864       }
15865
15866       SemaDiagnosticBuilder diagnoseIncomplete(
15867           Sema &S, SourceLocation Loc, QualType T) override {
15868         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15869       }
15870
15871       SemaDiagnosticBuilder diagnoseExplicitConv(
15872           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15873         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15874       }
15875
15876       SemaDiagnosticBuilder noteExplicitConv(
15877           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15878         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15879                  << ConvTy->isEnumeralType() << ConvTy;
15880       }
15881
15882       SemaDiagnosticBuilder diagnoseAmbiguous(
15883           Sema &S, SourceLocation Loc, QualType T) override {
15884         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15885       }
15886
15887       SemaDiagnosticBuilder noteAmbiguous(
15888           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15889         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15890                  << ConvTy->isEnumeralType() << ConvTy;
15891       }
15892
15893       SemaDiagnosticBuilder diagnoseConversion(
15894           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15895         llvm_unreachable("conversion functions are permitted");
15896       }
15897     } ConvertDiagnoser(Diagnoser.Suppress);
15898
15899     Converted = PerformContextualImplicitConversion(DiagLoc, E,
15900                                                     ConvertDiagnoser);
15901     if (Converted.isInvalid())
15902       return Converted;
15903     E = Converted.get();
15904     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15905       return ExprError();
15906   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15907     // An ICE must be of integral or unscoped enumeration type.
15908     if (!Diagnoser.Suppress)
15909       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15910     return ExprError();
15911   }
15912
15913   ExprResult RValueExpr = DefaultLvalueConversion(E);
15914   if (RValueExpr.isInvalid())
15915     return ExprError();
15916
15917   E = RValueExpr.get();
15918
15919   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15920   // in the non-ICE case.
15921   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15922     if (Result)
15923       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15924     if (!isa<ConstantExpr>(E))
15925       E = ConstantExpr::Create(Context, E);
15926     return E;
15927   }
15928
15929   Expr::EvalResult EvalResult;
15930   SmallVector<PartialDiagnosticAt, 8> Notes;
15931   EvalResult.Diag = &Notes;
15932
15933   // Try to evaluate the expression, and produce diagnostics explaining why it's
15934   // not a constant expression as a side-effect.
15935   bool Folded =
15936       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15937       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15938
15939   if (!isa<ConstantExpr>(E))
15940     E = ConstantExpr::Create(Context, E, EvalResult.Val);
15941
15942   // In C++11, we can rely on diagnostics being produced for any expression
15943   // which is not a constant expression. If no diagnostics were produced, then
15944   // this is a constant expression.
15945   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15946     if (Result)
15947       *Result = EvalResult.Val.getInt();
15948     return E;
15949   }
15950
15951   // If our only note is the usual "invalid subexpression" note, just point
15952   // the caret at its location rather than producing an essentially
15953   // redundant note.
15954   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15955         diag::note_invalid_subexpr_in_const_expr) {
15956     DiagLoc = Notes[0].first;
15957     Notes.clear();
15958   }
15959
15960   if (!Folded || !AllowFold) {
15961     if (!Diagnoser.Suppress) {
15962       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15963       for (const PartialDiagnosticAt &Note : Notes)
15964         Diag(Note.first, Note.second);
15965     }
15966
15967     return ExprError();
15968   }
15969
15970   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15971   for (const PartialDiagnosticAt &Note : Notes)
15972     Diag(Note.first, Note.second);
15973
15974   if (Result)
15975     *Result = EvalResult.Val.getInt();
15976   return E;
15977 }
15978
15979 namespace {
15980   // Handle the case where we conclude a expression which we speculatively
15981   // considered to be unevaluated is actually evaluated.
15982   class TransformToPE : public TreeTransform<TransformToPE> {
15983     typedef TreeTransform<TransformToPE> BaseTransform;
15984
15985   public:
15986     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15987
15988     // Make sure we redo semantic analysis
15989     bool AlwaysRebuild() { return true; }
15990     bool ReplacingOriginal() { return true; }
15991
15992     // We need to special-case DeclRefExprs referring to FieldDecls which
15993     // are not part of a member pointer formation; normal TreeTransforming
15994     // doesn't catch this case because of the way we represent them in the AST.
15995     // FIXME: This is a bit ugly; is it really the best way to handle this
15996     // case?
15997     //
15998     // Error on DeclRefExprs referring to FieldDecls.
15999     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16000       if (isa<FieldDecl>(E->getDecl()) &&
16001           !SemaRef.isUnevaluatedContext())
16002         return SemaRef.Diag(E->getLocation(),
16003                             diag::err_invalid_non_static_member_use)
16004             << E->getDecl() << E->getSourceRange();
16005
16006       return BaseTransform::TransformDeclRefExpr(E);
16007     }
16008
16009     // Exception: filter out member pointer formation
16010     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16011       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16012         return E;
16013
16014       return BaseTransform::TransformUnaryOperator(E);
16015     }
16016
16017     // The body of a lambda-expression is in a separate expression evaluation
16018     // context so never needs to be transformed.
16019     // FIXME: Ideally we wouldn't transform the closure type either, and would
16020     // just recreate the capture expressions and lambda expression.
16021     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16022       return SkipLambdaBody(E, Body);
16023     }
16024   };
16025 }
16026
16027 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16028   assert(isUnevaluatedContext() &&
16029          "Should only transform unevaluated expressions");
16030   ExprEvalContexts.back().Context =
16031       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16032   if (isUnevaluatedContext())
16033     return E;
16034   return TransformToPE(*this).TransformExpr(E);
16035 }
16036
16037 void
16038 Sema::PushExpressionEvaluationContext(
16039     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16040     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16041   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16042                                 LambdaContextDecl, ExprContext);
16043   Cleanup.reset();
16044   if (!MaybeODRUseExprs.empty())
16045     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16046 }
16047
16048 void
16049 Sema::PushExpressionEvaluationContext(
16050     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16051     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16052   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16053   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16054 }
16055
16056 namespace {
16057
16058 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16059   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16060   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16061     if (E->getOpcode() == UO_Deref)
16062       return CheckPossibleDeref(S, E->getSubExpr());
16063   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16064     return CheckPossibleDeref(S, E->getBase());
16065   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16066     return CheckPossibleDeref(S, E->getBase());
16067   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16068     QualType Inner;
16069     QualType Ty = E->getType();
16070     if (const auto *Ptr = Ty->getAs<PointerType>())
16071       Inner = Ptr->getPointeeType();
16072     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16073       Inner = Arr->getElementType();
16074     else
16075       return nullptr;
16076
16077     if (Inner->hasAttr(attr::NoDeref))
16078       return E;
16079   }
16080   return nullptr;
16081 }
16082
16083 } // namespace
16084
16085 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16086   for (const Expr *E : Rec.PossibleDerefs) {
16087     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16088     if (DeclRef) {
16089       const ValueDecl *Decl = DeclRef->getDecl();
16090       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16091           << Decl->getName() << E->getSourceRange();
16092       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16093     } else {
16094       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16095           << E->getSourceRange();
16096     }
16097   }
16098   Rec.PossibleDerefs.clear();
16099 }
16100
16101 /// Check whether E, which is either a discarded-value expression or an
16102 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16103 /// and if so, remove it from the list of volatile-qualified assignments that
16104 /// we are going to warn are deprecated.
16105 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16106   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16107     return;
16108
16109   // Note: ignoring parens here is not justified by the standard rules, but
16110   // ignoring parentheses seems like a more reasonable approach, and this only
16111   // drives a deprecation warning so doesn't affect conformance.
16112   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16113     if (BO->getOpcode() == BO_Assign) {
16114       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16115       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16116                  LHSs.end());
16117     }
16118   }
16119 }
16120
16121 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16122   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16123       RebuildingImmediateInvocation)
16124     return E;
16125
16126   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16127   /// It's OK if this fails; we'll also remove this in
16128   /// HandleImmediateInvocations, but catching it here allows us to avoid
16129   /// walking the AST looking for it in simple cases.
16130   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16131     if (auto *DeclRef =
16132             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16133       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16134
16135   E = MaybeCreateExprWithCleanups(E);
16136
16137   ConstantExpr *Res = ConstantExpr::Create(
16138       getASTContext(), E.get(),
16139       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16140                                    getASTContext()),
16141       /*IsImmediateInvocation*/ true);
16142   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16143   return Res;
16144 }
16145
16146 static void EvaluateAndDiagnoseImmediateInvocation(
16147     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16148   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16149   Expr::EvalResult Eval;
16150   Eval.Diag = &Notes;
16151   ConstantExpr *CE = Candidate.getPointer();
16152   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16153                                            SemaRef.getASTContext(), true);
16154   if (!Result || !Notes.empty()) {
16155     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16156     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16157       InnerExpr = FunctionalCast->getSubExpr();
16158     FunctionDecl *FD = nullptr;
16159     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16160       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16161     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16162       FD = Call->getConstructor();
16163     else
16164       llvm_unreachable("unhandled decl kind");
16165     assert(FD->isConsteval());
16166     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16167     for (auto &Note : Notes)
16168       SemaRef.Diag(Note.first, Note.second);
16169     return;
16170   }
16171   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16172 }
16173
16174 static void RemoveNestedImmediateInvocation(
16175     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16176     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16177   struct ComplexRemove : TreeTransform<ComplexRemove> {
16178     using Base = TreeTransform<ComplexRemove>;
16179     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16180     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16181     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16182         CurrentII;
16183     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16184                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16185                   SmallVector<Sema::ImmediateInvocationCandidate,
16186                               4>::reverse_iterator Current)
16187         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16188     void RemoveImmediateInvocation(ConstantExpr* E) {
16189       auto It = std::find_if(CurrentII, IISet.rend(),
16190                              [E](Sema::ImmediateInvocationCandidate Elem) {
16191                                return Elem.getPointer() == E;
16192                              });
16193       assert(It != IISet.rend() &&
16194              "ConstantExpr marked IsImmediateInvocation should "
16195              "be present");
16196       It->setInt(1); // Mark as deleted
16197     }
16198     ExprResult TransformConstantExpr(ConstantExpr *E) {
16199       if (!E->isImmediateInvocation())
16200         return Base::TransformConstantExpr(E);
16201       RemoveImmediateInvocation(E);
16202       return Base::TransformExpr(E->getSubExpr());
16203     }
16204     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16205     /// we need to remove its DeclRefExpr from the DRSet.
16206     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16207       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16208       return Base::TransformCXXOperatorCallExpr(E);
16209     }
16210     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16211     /// here.
16212     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16213       if (!Init)
16214         return Init;
16215       /// ConstantExpr are the first layer of implicit node to be removed so if
16216       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16217       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16218         if (CE->isImmediateInvocation())
16219           RemoveImmediateInvocation(CE);
16220       return Base::TransformInitializer(Init, NotCopyInit);
16221     }
16222     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16223       DRSet.erase(E);
16224       return E;
16225     }
16226     bool AlwaysRebuild() { return false; }
16227     bool ReplacingOriginal() { return true; }
16228     bool AllowSkippingCXXConstructExpr() {
16229       bool Res = AllowSkippingFirstCXXConstructExpr;
16230       AllowSkippingFirstCXXConstructExpr = true;
16231       return Res;
16232     }
16233     bool AllowSkippingFirstCXXConstructExpr = true;
16234   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16235                 Rec.ImmediateInvocationCandidates, It);
16236
16237   /// CXXConstructExpr with a single argument are getting skipped by
16238   /// TreeTransform in some situtation because they could be implicit. This
16239   /// can only occur for the top-level CXXConstructExpr because it is used
16240   /// nowhere in the expression being transformed therefore will not be rebuilt.
16241   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16242   /// skipping the first CXXConstructExpr.
16243   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16244     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16245
16246   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16247   assert(Res.isUsable());
16248   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16249   It->getPointer()->setSubExpr(Res.get());
16250 }
16251
16252 static void
16253 HandleImmediateInvocations(Sema &SemaRef,
16254                            Sema::ExpressionEvaluationContextRecord &Rec) {
16255   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16256        Rec.ReferenceToConsteval.size() == 0) ||
16257       SemaRef.RebuildingImmediateInvocation)
16258     return;
16259
16260   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16261   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16262   /// need to remove ReferenceToConsteval in the immediate invocation.
16263   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16264
16265     /// Prevent sema calls during the tree transform from adding pointers that
16266     /// are already in the sets.
16267     llvm::SaveAndRestore<bool> DisableIITracking(
16268         SemaRef.RebuildingImmediateInvocation, true);
16269
16270     /// Prevent diagnostic during tree transfrom as they are duplicates
16271     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16272
16273     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16274          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16275       if (!It->getInt())
16276         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16277   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16278              Rec.ReferenceToConsteval.size()) {
16279     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16280       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16281       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16282       bool VisitDeclRefExpr(DeclRefExpr *E) {
16283         DRSet.erase(E);
16284         return DRSet.size();
16285       }
16286     } Visitor(Rec.ReferenceToConsteval);
16287     Visitor.TraverseStmt(
16288         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16289   }
16290   for (auto CE : Rec.ImmediateInvocationCandidates)
16291     if (!CE.getInt())
16292       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16293   for (auto DR : Rec.ReferenceToConsteval) {
16294     auto *FD = cast<FunctionDecl>(DR->getDecl());
16295     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16296         << FD;
16297     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16298   }
16299 }
16300
16301 void Sema::PopExpressionEvaluationContext() {
16302   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16303   unsigned NumTypos = Rec.NumTypos;
16304
16305   if (!Rec.Lambdas.empty()) {
16306     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16307     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16308         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16309       unsigned D;
16310       if (Rec.isUnevaluated()) {
16311         // C++11 [expr.prim.lambda]p2:
16312         //   A lambda-expression shall not appear in an unevaluated operand
16313         //   (Clause 5).
16314         D = diag::err_lambda_unevaluated_operand;
16315       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16316         // C++1y [expr.const]p2:
16317         //   A conditional-expression e is a core constant expression unless the
16318         //   evaluation of e, following the rules of the abstract machine, would
16319         //   evaluate [...] a lambda-expression.
16320         D = diag::err_lambda_in_constant_expression;
16321       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16322         // C++17 [expr.prim.lamda]p2:
16323         // A lambda-expression shall not appear [...] in a template-argument.
16324         D = diag::err_lambda_in_invalid_context;
16325       } else
16326         llvm_unreachable("Couldn't infer lambda error message.");
16327
16328       for (const auto *L : Rec.Lambdas)
16329         Diag(L->getBeginLoc(), D);
16330     }
16331   }
16332
16333   WarnOnPendingNoDerefs(Rec);
16334   HandleImmediateInvocations(*this, Rec);
16335
16336   // Warn on any volatile-qualified simple-assignments that are not discarded-
16337   // value expressions nor unevaluated operands (those cases get removed from
16338   // this list by CheckUnusedVolatileAssignment).
16339   for (auto *BO : Rec.VolatileAssignmentLHSs)
16340     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16341         << BO->getType();
16342
16343   // When are coming out of an unevaluated context, clear out any
16344   // temporaries that we may have created as part of the evaluation of
16345   // the expression in that context: they aren't relevant because they
16346   // will never be constructed.
16347   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16348     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16349                              ExprCleanupObjects.end());
16350     Cleanup = Rec.ParentCleanup;
16351     CleanupVarDeclMarking();
16352     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16353   // Otherwise, merge the contexts together.
16354   } else {
16355     Cleanup.mergeFrom(Rec.ParentCleanup);
16356     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16357                             Rec.SavedMaybeODRUseExprs.end());
16358   }
16359
16360   // Pop the current expression evaluation context off the stack.
16361   ExprEvalContexts.pop_back();
16362
16363   // The global expression evaluation context record is never popped.
16364   ExprEvalContexts.back().NumTypos += NumTypos;
16365 }
16366
16367 void Sema::DiscardCleanupsInEvaluationContext() {
16368   ExprCleanupObjects.erase(
16369          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16370          ExprCleanupObjects.end());
16371   Cleanup.reset();
16372   MaybeODRUseExprs.clear();
16373 }
16374
16375 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16376   ExprResult Result = CheckPlaceholderExpr(E);
16377   if (Result.isInvalid())
16378     return ExprError();
16379   E = Result.get();
16380   if (!E->getType()->isVariablyModifiedType())
16381     return E;
16382   return TransformToPotentiallyEvaluated(E);
16383 }
16384
16385 /// Are we in a context that is potentially constant evaluated per C++20
16386 /// [expr.const]p12?
16387 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16388   /// C++2a [expr.const]p12:
16389   //   An expression or conversion is potentially constant evaluated if it is
16390   switch (SemaRef.ExprEvalContexts.back().Context) {
16391     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16392       // -- a manifestly constant-evaluated expression,
16393     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16394     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16395     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16396       // -- a potentially-evaluated expression,
16397     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16398       // -- an immediate subexpression of a braced-init-list,
16399
16400       // -- [FIXME] an expression of the form & cast-expression that occurs
16401       //    within a templated entity
16402       // -- a subexpression of one of the above that is not a subexpression of
16403       // a nested unevaluated operand.
16404       return true;
16405
16406     case Sema::ExpressionEvaluationContext::Unevaluated:
16407     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16408       // Expressions in this context are never evaluated.
16409       return false;
16410   }
16411   llvm_unreachable("Invalid context");
16412 }
16413
16414 /// Return true if this function has a calling convention that requires mangling
16415 /// in the size of the parameter pack.
16416 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16417   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16418   // we don't need parameter type sizes.
16419   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16420   if (!TT.isOSWindows() || !TT.isX86())
16421     return false;
16422
16423   // If this is C++ and this isn't an extern "C" function, parameters do not
16424   // need to be complete. In this case, C++ mangling will apply, which doesn't
16425   // use the size of the parameters.
16426   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16427     return false;
16428
16429   // Stdcall, fastcall, and vectorcall need this special treatment.
16430   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16431   switch (CC) {
16432   case CC_X86StdCall:
16433   case CC_X86FastCall:
16434   case CC_X86VectorCall:
16435     return true;
16436   default:
16437     break;
16438   }
16439   return false;
16440 }
16441
16442 /// Require that all of the parameter types of function be complete. Normally,
16443 /// parameter types are only required to be complete when a function is called
16444 /// or defined, but to mangle functions with certain calling conventions, the
16445 /// mangler needs to know the size of the parameter list. In this situation,
16446 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16447 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16448 /// result in a linker error. Clang doesn't implement this behavior, and instead
16449 /// attempts to error at compile time.
16450 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16451                                                   SourceLocation Loc) {
16452   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16453     FunctionDecl *FD;
16454     ParmVarDecl *Param;
16455
16456   public:
16457     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16458         : FD(FD), Param(Param) {}
16459
16460     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16461       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16462       StringRef CCName;
16463       switch (CC) {
16464       case CC_X86StdCall:
16465         CCName = "stdcall";
16466         break;
16467       case CC_X86FastCall:
16468         CCName = "fastcall";
16469         break;
16470       case CC_X86VectorCall:
16471         CCName = "vectorcall";
16472         break;
16473       default:
16474         llvm_unreachable("CC does not need mangling");
16475       }
16476
16477       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16478           << Param->getDeclName() << FD->getDeclName() << CCName;
16479     }
16480   };
16481
16482   for (ParmVarDecl *Param : FD->parameters()) {
16483     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16484     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16485   }
16486 }
16487
16488 namespace {
16489 enum class OdrUseContext {
16490   /// Declarations in this context are not odr-used.
16491   None,
16492   /// Declarations in this context are formally odr-used, but this is a
16493   /// dependent context.
16494   Dependent,
16495   /// Declarations in this context are odr-used but not actually used (yet).
16496   FormallyOdrUsed,
16497   /// Declarations in this context are used.
16498   Used
16499 };
16500 }
16501
16502 /// Are we within a context in which references to resolved functions or to
16503 /// variables result in odr-use?
16504 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16505   OdrUseContext Result;
16506
16507   switch (SemaRef.ExprEvalContexts.back().Context) {
16508     case Sema::ExpressionEvaluationContext::Unevaluated:
16509     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16510     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16511       return OdrUseContext::None;
16512
16513     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16514     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16515       Result = OdrUseContext::Used;
16516       break;
16517
16518     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16519       Result = OdrUseContext::FormallyOdrUsed;
16520       break;
16521
16522     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16523       // A default argument formally results in odr-use, but doesn't actually
16524       // result in a use in any real sense until it itself is used.
16525       Result = OdrUseContext::FormallyOdrUsed;
16526       break;
16527   }
16528
16529   if (SemaRef.CurContext->isDependentContext())
16530     return OdrUseContext::Dependent;
16531
16532   return Result;
16533 }
16534
16535 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16536   return Func->isConstexpr() &&
16537          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16538 }
16539
16540 /// Mark a function referenced, and check whether it is odr-used
16541 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16542 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16543                                   bool MightBeOdrUse) {
16544   assert(Func && "No function?");
16545
16546   Func->setReferenced();
16547
16548   // Recursive functions aren't really used until they're used from some other
16549   // context.
16550   bool IsRecursiveCall = CurContext == Func;
16551
16552   // C++11 [basic.def.odr]p3:
16553   //   A function whose name appears as a potentially-evaluated expression is
16554   //   odr-used if it is the unique lookup result or the selected member of a
16555   //   set of overloaded functions [...].
16556   //
16557   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16558   // can just check that here.
16559   OdrUseContext OdrUse =
16560       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16561   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16562     OdrUse = OdrUseContext::FormallyOdrUsed;
16563
16564   // Trivial default constructors and destructors are never actually used.
16565   // FIXME: What about other special members?
16566   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16567       OdrUse == OdrUseContext::Used) {
16568     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16569       if (Constructor->isDefaultConstructor())
16570         OdrUse = OdrUseContext::FormallyOdrUsed;
16571     if (isa<CXXDestructorDecl>(Func))
16572       OdrUse = OdrUseContext::FormallyOdrUsed;
16573   }
16574
16575   // C++20 [expr.const]p12:
16576   //   A function [...] is needed for constant evaluation if it is [...] a
16577   //   constexpr function that is named by an expression that is potentially
16578   //   constant evaluated
16579   bool NeededForConstantEvaluation =
16580       isPotentiallyConstantEvaluatedContext(*this) &&
16581       isImplicitlyDefinableConstexprFunction(Func);
16582
16583   // Determine whether we require a function definition to exist, per
16584   // C++11 [temp.inst]p3:
16585   //   Unless a function template specialization has been explicitly
16586   //   instantiated or explicitly specialized, the function template
16587   //   specialization is implicitly instantiated when the specialization is
16588   //   referenced in a context that requires a function definition to exist.
16589   // C++20 [temp.inst]p7:
16590   //   The existence of a definition of a [...] function is considered to
16591   //   affect the semantics of the program if the [...] function is needed for
16592   //   constant evaluation by an expression
16593   // C++20 [basic.def.odr]p10:
16594   //   Every program shall contain exactly one definition of every non-inline
16595   //   function or variable that is odr-used in that program outside of a
16596   //   discarded statement
16597   // C++20 [special]p1:
16598   //   The implementation will implicitly define [defaulted special members]
16599   //   if they are odr-used or needed for constant evaluation.
16600   //
16601   // Note that we skip the implicit instantiation of templates that are only
16602   // used in unused default arguments or by recursive calls to themselves.
16603   // This is formally non-conforming, but seems reasonable in practice.
16604   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16605                                              NeededForConstantEvaluation);
16606
16607   // C++14 [temp.expl.spec]p6:
16608   //   If a template [...] is explicitly specialized then that specialization
16609   //   shall be declared before the first use of that specialization that would
16610   //   cause an implicit instantiation to take place, in every translation unit
16611   //   in which such a use occurs
16612   if (NeedDefinition &&
16613       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16614        Func->getMemberSpecializationInfo()))
16615     checkSpecializationVisibility(Loc, Func);
16616
16617   if (getLangOpts().CUDA)
16618     CheckCUDACall(Loc, Func);
16619
16620   if (getLangOpts().SYCLIsDevice)
16621     checkSYCLDeviceFunction(Loc, Func);
16622
16623   // If we need a definition, try to create one.
16624   if (NeedDefinition && !Func->getBody()) {
16625     runWithSufficientStackSpace(Loc, [&] {
16626       if (CXXConstructorDecl *Constructor =
16627               dyn_cast<CXXConstructorDecl>(Func)) {
16628         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16629         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16630           if (Constructor->isDefaultConstructor()) {
16631             if (Constructor->isTrivial() &&
16632                 !Constructor->hasAttr<DLLExportAttr>())
16633               return;
16634             DefineImplicitDefaultConstructor(Loc, Constructor);
16635           } else if (Constructor->isCopyConstructor()) {
16636             DefineImplicitCopyConstructor(Loc, Constructor);
16637           } else if (Constructor->isMoveConstructor()) {
16638             DefineImplicitMoveConstructor(Loc, Constructor);
16639           }
16640         } else if (Constructor->getInheritedConstructor()) {
16641           DefineInheritingConstructor(Loc, Constructor);
16642         }
16643       } else if (CXXDestructorDecl *Destructor =
16644                      dyn_cast<CXXDestructorDecl>(Func)) {
16645         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16646         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16647           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16648             return;
16649           DefineImplicitDestructor(Loc, Destructor);
16650         }
16651         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16652           MarkVTableUsed(Loc, Destructor->getParent());
16653       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16654         if (MethodDecl->isOverloadedOperator() &&
16655             MethodDecl->getOverloadedOperator() == OO_Equal) {
16656           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16657           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16658             if (MethodDecl->isCopyAssignmentOperator())
16659               DefineImplicitCopyAssignment(Loc, MethodDecl);
16660             else if (MethodDecl->isMoveAssignmentOperator())
16661               DefineImplicitMoveAssignment(Loc, MethodDecl);
16662           }
16663         } else if (isa<CXXConversionDecl>(MethodDecl) &&
16664                    MethodDecl->getParent()->isLambda()) {
16665           CXXConversionDecl *Conversion =
16666               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16667           if (Conversion->isLambdaToBlockPointerConversion())
16668             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16669           else
16670             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16671         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16672           MarkVTableUsed(Loc, MethodDecl->getParent());
16673       }
16674
16675       if (Func->isDefaulted() && !Func->isDeleted()) {
16676         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16677         if (DCK != DefaultedComparisonKind::None)
16678           DefineDefaultedComparison(Loc, Func, DCK);
16679       }
16680
16681       // Implicit instantiation of function templates and member functions of
16682       // class templates.
16683       if (Func->isImplicitlyInstantiable()) {
16684         TemplateSpecializationKind TSK =
16685             Func->getTemplateSpecializationKindForInstantiation();
16686         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16687         bool FirstInstantiation = PointOfInstantiation.isInvalid();
16688         if (FirstInstantiation) {
16689           PointOfInstantiation = Loc;
16690           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16691         } else if (TSK != TSK_ImplicitInstantiation) {
16692           // Use the point of use as the point of instantiation, instead of the
16693           // point of explicit instantiation (which we track as the actual point
16694           // of instantiation). This gives better backtraces in diagnostics.
16695           PointOfInstantiation = Loc;
16696         }
16697
16698         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16699             Func->isConstexpr()) {
16700           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16701               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16702               CodeSynthesisContexts.size())
16703             PendingLocalImplicitInstantiations.push_back(
16704                 std::make_pair(Func, PointOfInstantiation));
16705           else if (Func->isConstexpr())
16706             // Do not defer instantiations of constexpr functions, to avoid the
16707             // expression evaluator needing to call back into Sema if it sees a
16708             // call to such a function.
16709             InstantiateFunctionDefinition(PointOfInstantiation, Func);
16710           else {
16711             Func->setInstantiationIsPending(true);
16712             PendingInstantiations.push_back(
16713                 std::make_pair(Func, PointOfInstantiation));
16714             // Notify the consumer that a function was implicitly instantiated.
16715             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16716           }
16717         }
16718       } else {
16719         // Walk redefinitions, as some of them may be instantiable.
16720         for (auto i : Func->redecls()) {
16721           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16722             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16723         }
16724       }
16725     });
16726   }
16727
16728   // C++14 [except.spec]p17:
16729   //   An exception-specification is considered to be needed when:
16730   //   - the function is odr-used or, if it appears in an unevaluated operand,
16731   //     would be odr-used if the expression were potentially-evaluated;
16732   //
16733   // Note, we do this even if MightBeOdrUse is false. That indicates that the
16734   // function is a pure virtual function we're calling, and in that case the
16735   // function was selected by overload resolution and we need to resolve its
16736   // exception specification for a different reason.
16737   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16738   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16739     ResolveExceptionSpec(Loc, FPT);
16740
16741   // If this is the first "real" use, act on that.
16742   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16743     // Keep track of used but undefined functions.
16744     if (!Func->isDefined()) {
16745       if (mightHaveNonExternalLinkage(Func))
16746         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16747       else if (Func->getMostRecentDecl()->isInlined() &&
16748                !LangOpts.GNUInline &&
16749                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16750         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16751       else if (isExternalWithNoLinkageType(Func))
16752         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16753     }
16754
16755     // Some x86 Windows calling conventions mangle the size of the parameter
16756     // pack into the name. Computing the size of the parameters requires the
16757     // parameter types to be complete. Check that now.
16758     if (funcHasParameterSizeMangling(*this, Func))
16759       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16760
16761     // In the MS C++ ABI, the compiler emits destructor variants where they are
16762     // used. If the destructor is used here but defined elsewhere, mark the
16763     // virtual base destructors referenced. If those virtual base destructors
16764     // are inline, this will ensure they are defined when emitting the complete
16765     // destructor variant. This checking may be redundant if the destructor is
16766     // provided later in this TU.
16767     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16768       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16769         CXXRecordDecl *Parent = Dtor->getParent();
16770         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16771           CheckCompleteDestructorVariant(Loc, Dtor);
16772       }
16773     }
16774
16775     Func->markUsed(Context);
16776   }
16777 }
16778
16779 /// Directly mark a variable odr-used. Given a choice, prefer to use
16780 /// MarkVariableReferenced since it does additional checks and then
16781 /// calls MarkVarDeclODRUsed.
16782 /// If the variable must be captured:
16783 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16784 ///  - else capture it in the DeclContext that maps to the
16785 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16786 static void
16787 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16788                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16789   // Keep track of used but undefined variables.
16790   // FIXME: We shouldn't suppress this warning for static data members.
16791   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16792       (!Var->isExternallyVisible() || Var->isInline() ||
16793        SemaRef.isExternalWithNoLinkageType(Var)) &&
16794       !(Var->isStaticDataMember() && Var->hasInit())) {
16795     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16796     if (old.isInvalid())
16797       old = Loc;
16798   }
16799   QualType CaptureType, DeclRefType;
16800   if (SemaRef.LangOpts.OpenMP)
16801     SemaRef.tryCaptureOpenMPLambdas(Var);
16802   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16803     /*EllipsisLoc*/ SourceLocation(),
16804     /*BuildAndDiagnose*/ true,
16805     CaptureType, DeclRefType,
16806     FunctionScopeIndexToStopAt);
16807
16808   Var->markUsed(SemaRef.Context);
16809 }
16810
16811 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16812                                              SourceLocation Loc,
16813                                              unsigned CapturingScopeIndex) {
16814   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16815 }
16816
16817 static void
16818 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16819                                    ValueDecl *var, DeclContext *DC) {
16820   DeclContext *VarDC = var->getDeclContext();
16821
16822   //  If the parameter still belongs to the translation unit, then
16823   //  we're actually just using one parameter in the declaration of
16824   //  the next.
16825   if (isa<ParmVarDecl>(var) &&
16826       isa<TranslationUnitDecl>(VarDC))
16827     return;
16828
16829   // For C code, don't diagnose about capture if we're not actually in code
16830   // right now; it's impossible to write a non-constant expression outside of
16831   // function context, so we'll get other (more useful) diagnostics later.
16832   //
16833   // For C++, things get a bit more nasty... it would be nice to suppress this
16834   // diagnostic for certain cases like using a local variable in an array bound
16835   // for a member of a local class, but the correct predicate is not obvious.
16836   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16837     return;
16838
16839   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16840   unsigned ContextKind = 3; // unknown
16841   if (isa<CXXMethodDecl>(VarDC) &&
16842       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16843     ContextKind = 2;
16844   } else if (isa<FunctionDecl>(VarDC)) {
16845     ContextKind = 0;
16846   } else if (isa<BlockDecl>(VarDC)) {
16847     ContextKind = 1;
16848   }
16849
16850   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16851     << var << ValueKind << ContextKind << VarDC;
16852   S.Diag(var->getLocation(), diag::note_entity_declared_at)
16853       << var;
16854
16855   // FIXME: Add additional diagnostic info about class etc. which prevents
16856   // capture.
16857 }
16858
16859
16860 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16861                                       bool &SubCapturesAreNested,
16862                                       QualType &CaptureType,
16863                                       QualType &DeclRefType) {
16864    // Check whether we've already captured it.
16865   if (CSI->CaptureMap.count(Var)) {
16866     // If we found a capture, any subcaptures are nested.
16867     SubCapturesAreNested = true;
16868
16869     // Retrieve the capture type for this variable.
16870     CaptureType = CSI->getCapture(Var).getCaptureType();
16871
16872     // Compute the type of an expression that refers to this variable.
16873     DeclRefType = CaptureType.getNonReferenceType();
16874
16875     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16876     // are mutable in the sense that user can change their value - they are
16877     // private instances of the captured declarations.
16878     const Capture &Cap = CSI->getCapture(Var);
16879     if (Cap.isCopyCapture() &&
16880         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16881         !(isa<CapturedRegionScopeInfo>(CSI) &&
16882           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16883       DeclRefType.addConst();
16884     return true;
16885   }
16886   return false;
16887 }
16888
16889 // Only block literals, captured statements, and lambda expressions can
16890 // capture; other scopes don't work.
16891 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16892                                  SourceLocation Loc,
16893                                  const bool Diagnose, Sema &S) {
16894   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16895     return getLambdaAwareParentOfDeclContext(DC);
16896   else if (Var->hasLocalStorage()) {
16897     if (Diagnose)
16898        diagnoseUncapturableValueReference(S, Loc, Var, DC);
16899   }
16900   return nullptr;
16901 }
16902
16903 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16904 // certain types of variables (unnamed, variably modified types etc.)
16905 // so check for eligibility.
16906 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16907                                  SourceLocation Loc,
16908                                  const bool Diagnose, Sema &S) {
16909
16910   bool IsBlock = isa<BlockScopeInfo>(CSI);
16911   bool IsLambda = isa<LambdaScopeInfo>(CSI);
16912
16913   // Lambdas are not allowed to capture unnamed variables
16914   // (e.g. anonymous unions).
16915   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16916   // assuming that's the intent.
16917   if (IsLambda && !Var->getDeclName()) {
16918     if (Diagnose) {
16919       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16920       S.Diag(Var->getLocation(), diag::note_declared_at);
16921     }
16922     return false;
16923   }
16924
16925   // Prohibit variably-modified types in blocks; they're difficult to deal with.
16926   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16927     if (Diagnose) {
16928       S.Diag(Loc, diag::err_ref_vm_type);
16929       S.Diag(Var->getLocation(), diag::note_previous_decl)
16930         << Var->getDeclName();
16931     }
16932     return false;
16933   }
16934   // Prohibit structs with flexible array members too.
16935   // We cannot capture what is in the tail end of the struct.
16936   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16937     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16938       if (Diagnose) {
16939         if (IsBlock)
16940           S.Diag(Loc, diag::err_ref_flexarray_type);
16941         else
16942           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16943             << Var->getDeclName();
16944         S.Diag(Var->getLocation(), diag::note_previous_decl)
16945           << Var->getDeclName();
16946       }
16947       return false;
16948     }
16949   }
16950   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16951   // Lambdas and captured statements are not allowed to capture __block
16952   // variables; they don't support the expected semantics.
16953   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16954     if (Diagnose) {
16955       S.Diag(Loc, diag::err_capture_block_variable)
16956         << Var->getDeclName() << !IsLambda;
16957       S.Diag(Var->getLocation(), diag::note_previous_decl)
16958         << Var->getDeclName();
16959     }
16960     return false;
16961   }
16962   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16963   if (S.getLangOpts().OpenCL && IsBlock &&
16964       Var->getType()->isBlockPointerType()) {
16965     if (Diagnose)
16966       S.Diag(Loc, diag::err_opencl_block_ref_block);
16967     return false;
16968   }
16969
16970   return true;
16971 }
16972
16973 // Returns true if the capture by block was successful.
16974 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16975                                  SourceLocation Loc,
16976                                  const bool BuildAndDiagnose,
16977                                  QualType &CaptureType,
16978                                  QualType &DeclRefType,
16979                                  const bool Nested,
16980                                  Sema &S, bool Invalid) {
16981   bool ByRef = false;
16982
16983   // Blocks are not allowed to capture arrays, excepting OpenCL.
16984   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16985   // (decayed to pointers).
16986   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16987     if (BuildAndDiagnose) {
16988       S.Diag(Loc, diag::err_ref_array_type);
16989       S.Diag(Var->getLocation(), diag::note_previous_decl)
16990       << Var->getDeclName();
16991       Invalid = true;
16992     } else {
16993       return false;
16994     }
16995   }
16996
16997   // Forbid the block-capture of autoreleasing variables.
16998   if (!Invalid &&
16999       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17000     if (BuildAndDiagnose) {
17001       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17002         << /*block*/ 0;
17003       S.Diag(Var->getLocation(), diag::note_previous_decl)
17004         << Var->getDeclName();
17005       Invalid = true;
17006     } else {
17007       return false;
17008     }
17009   }
17010
17011   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17012   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17013     QualType PointeeTy = PT->getPointeeType();
17014
17015     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17016         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17017         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17018       if (BuildAndDiagnose) {
17019         SourceLocation VarLoc = Var->getLocation();
17020         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17021         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17022       }
17023     }
17024   }
17025
17026   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17027   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17028       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17029     // Block capture by reference does not change the capture or
17030     // declaration reference types.
17031     ByRef = true;
17032   } else {
17033     // Block capture by copy introduces 'const'.
17034     CaptureType = CaptureType.getNonReferenceType().withConst();
17035     DeclRefType = CaptureType;
17036   }
17037
17038   // Actually capture the variable.
17039   if (BuildAndDiagnose)
17040     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17041                     CaptureType, Invalid);
17042
17043   return !Invalid;
17044 }
17045
17046
17047 /// Capture the given variable in the captured region.
17048 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17049                                     VarDecl *Var,
17050                                     SourceLocation Loc,
17051                                     const bool BuildAndDiagnose,
17052                                     QualType &CaptureType,
17053                                     QualType &DeclRefType,
17054                                     const bool RefersToCapturedVariable,
17055                                     Sema &S, bool Invalid) {
17056   // By default, capture variables by reference.
17057   bool ByRef = true;
17058   // Using an LValue reference type is consistent with Lambdas (see below).
17059   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17060     if (S.isOpenMPCapturedDecl(Var)) {
17061       bool HasConst = DeclRefType.isConstQualified();
17062       DeclRefType = DeclRefType.getUnqualifiedType();
17063       // Don't lose diagnostics about assignments to const.
17064       if (HasConst)
17065         DeclRefType.addConst();
17066     }
17067     // Do not capture firstprivates in tasks.
17068     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17069         OMPC_unknown)
17070       return true;
17071     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17072                                     RSI->OpenMPCaptureLevel);
17073   }
17074
17075   if (ByRef)
17076     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17077   else
17078     CaptureType = DeclRefType;
17079
17080   // Actually capture the variable.
17081   if (BuildAndDiagnose)
17082     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17083                     Loc, SourceLocation(), CaptureType, Invalid);
17084
17085   return !Invalid;
17086 }
17087
17088 /// Capture the given variable in the lambda.
17089 static bool captureInLambda(LambdaScopeInfo *LSI,
17090                             VarDecl *Var,
17091                             SourceLocation Loc,
17092                             const bool BuildAndDiagnose,
17093                             QualType &CaptureType,
17094                             QualType &DeclRefType,
17095                             const bool RefersToCapturedVariable,
17096                             const Sema::TryCaptureKind Kind,
17097                             SourceLocation EllipsisLoc,
17098                             const bool IsTopScope,
17099                             Sema &S, bool Invalid) {
17100   // Determine whether we are capturing by reference or by value.
17101   bool ByRef = false;
17102   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17103     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17104   } else {
17105     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17106   }
17107
17108   // Compute the type of the field that will capture this variable.
17109   if (ByRef) {
17110     // C++11 [expr.prim.lambda]p15:
17111     //   An entity is captured by reference if it is implicitly or
17112     //   explicitly captured but not captured by copy. It is
17113     //   unspecified whether additional unnamed non-static data
17114     //   members are declared in the closure type for entities
17115     //   captured by reference.
17116     //
17117     // FIXME: It is not clear whether we want to build an lvalue reference
17118     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17119     // to do the former, while EDG does the latter. Core issue 1249 will
17120     // clarify, but for now we follow GCC because it's a more permissive and
17121     // easily defensible position.
17122     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17123   } else {
17124     // C++11 [expr.prim.lambda]p14:
17125     //   For each entity captured by copy, an unnamed non-static
17126     //   data member is declared in the closure type. The
17127     //   declaration order of these members is unspecified. The type
17128     //   of such a data member is the type of the corresponding
17129     //   captured entity if the entity is not a reference to an
17130     //   object, or the referenced type otherwise. [Note: If the
17131     //   captured entity is a reference to a function, the
17132     //   corresponding data member is also a reference to a
17133     //   function. - end note ]
17134     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17135       if (!RefType->getPointeeType()->isFunctionType())
17136         CaptureType = RefType->getPointeeType();
17137     }
17138
17139     // Forbid the lambda copy-capture of autoreleasing variables.
17140     if (!Invalid &&
17141         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17142       if (BuildAndDiagnose) {
17143         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17144         S.Diag(Var->getLocation(), diag::note_previous_decl)
17145           << Var->getDeclName();
17146         Invalid = true;
17147       } else {
17148         return false;
17149       }
17150     }
17151
17152     // Make sure that by-copy captures are of a complete and non-abstract type.
17153     if (!Invalid && BuildAndDiagnose) {
17154       if (!CaptureType->isDependentType() &&
17155           S.RequireCompleteSizedType(
17156               Loc, CaptureType,
17157               diag::err_capture_of_incomplete_or_sizeless_type,
17158               Var->getDeclName()))
17159         Invalid = true;
17160       else if (S.RequireNonAbstractType(Loc, CaptureType,
17161                                         diag::err_capture_of_abstract_type))
17162         Invalid = true;
17163     }
17164   }
17165
17166   // Compute the type of a reference to this captured variable.
17167   if (ByRef)
17168     DeclRefType = CaptureType.getNonReferenceType();
17169   else {
17170     // C++ [expr.prim.lambda]p5:
17171     //   The closure type for a lambda-expression has a public inline
17172     //   function call operator [...]. This function call operator is
17173     //   declared const (9.3.1) if and only if the lambda-expression's
17174     //   parameter-declaration-clause is not followed by mutable.
17175     DeclRefType = CaptureType.getNonReferenceType();
17176     if (!LSI->Mutable && !CaptureType->isReferenceType())
17177       DeclRefType.addConst();
17178   }
17179
17180   // Add the capture.
17181   if (BuildAndDiagnose)
17182     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17183                     Loc, EllipsisLoc, CaptureType, Invalid);
17184
17185   return !Invalid;
17186 }
17187
17188 bool Sema::tryCaptureVariable(
17189     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17190     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17191     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17192   // An init-capture is notionally from the context surrounding its
17193   // declaration, but its parent DC is the lambda class.
17194   DeclContext *VarDC = Var->getDeclContext();
17195   if (Var->isInitCapture())
17196     VarDC = VarDC->getParent();
17197
17198   DeclContext *DC = CurContext;
17199   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17200       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17201   // We need to sync up the Declaration Context with the
17202   // FunctionScopeIndexToStopAt
17203   if (FunctionScopeIndexToStopAt) {
17204     unsigned FSIndex = FunctionScopes.size() - 1;
17205     while (FSIndex != MaxFunctionScopesIndex) {
17206       DC = getLambdaAwareParentOfDeclContext(DC);
17207       --FSIndex;
17208     }
17209   }
17210
17211
17212   // If the variable is declared in the current context, there is no need to
17213   // capture it.
17214   if (VarDC == DC) return true;
17215
17216   // Capture global variables if it is required to use private copy of this
17217   // variable.
17218   bool IsGlobal = !Var->hasLocalStorage();
17219   if (IsGlobal &&
17220       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17221                                                 MaxFunctionScopesIndex)))
17222     return true;
17223   Var = Var->getCanonicalDecl();
17224
17225   // Walk up the stack to determine whether we can capture the variable,
17226   // performing the "simple" checks that don't depend on type. We stop when
17227   // we've either hit the declared scope of the variable or find an existing
17228   // capture of that variable.  We start from the innermost capturing-entity
17229   // (the DC) and ensure that all intervening capturing-entities
17230   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17231   // declcontext can either capture the variable or have already captured
17232   // the variable.
17233   CaptureType = Var->getType();
17234   DeclRefType = CaptureType.getNonReferenceType();
17235   bool Nested = false;
17236   bool Explicit = (Kind != TryCapture_Implicit);
17237   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17238   do {
17239     // Only block literals, captured statements, and lambda expressions can
17240     // capture; other scopes don't work.
17241     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17242                                                               ExprLoc,
17243                                                               BuildAndDiagnose,
17244                                                               *this);
17245     // We need to check for the parent *first* because, if we *have*
17246     // private-captured a global variable, we need to recursively capture it in
17247     // intermediate blocks, lambdas, etc.
17248     if (!ParentDC) {
17249       if (IsGlobal) {
17250         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17251         break;
17252       }
17253       return true;
17254     }
17255
17256     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17257     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17258
17259
17260     // Check whether we've already captured it.
17261     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17262                                              DeclRefType)) {
17263       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17264       break;
17265     }
17266     // If we are instantiating a generic lambda call operator body,
17267     // we do not want to capture new variables.  What was captured
17268     // during either a lambdas transformation or initial parsing
17269     // should be used.
17270     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17271       if (BuildAndDiagnose) {
17272         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17273         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17274           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17275           Diag(Var->getLocation(), diag::note_previous_decl)
17276              << Var->getDeclName();
17277           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17278         } else
17279           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17280       }
17281       return true;
17282     }
17283
17284     // Try to capture variable-length arrays types.
17285     if (Var->getType()->isVariablyModifiedType()) {
17286       // We're going to walk down into the type and look for VLA
17287       // expressions.
17288       QualType QTy = Var->getType();
17289       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17290         QTy = PVD->getOriginalType();
17291       captureVariablyModifiedType(Context, QTy, CSI);
17292     }
17293
17294     if (getLangOpts().OpenMP) {
17295       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17296         // OpenMP private variables should not be captured in outer scope, so
17297         // just break here. Similarly, global variables that are captured in a
17298         // target region should not be captured outside the scope of the region.
17299         if (RSI->CapRegionKind == CR_OpenMP) {
17300           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17301               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17302           // If the variable is private (i.e. not captured) and has variably
17303           // modified type, we still need to capture the type for correct
17304           // codegen in all regions, associated with the construct. Currently,
17305           // it is captured in the innermost captured region only.
17306           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17307               Var->getType()->isVariablyModifiedType()) {
17308             QualType QTy = Var->getType();
17309             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17310               QTy = PVD->getOriginalType();
17311             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17312                  I < E; ++I) {
17313               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17314                   FunctionScopes[FunctionScopesIndex - I]);
17315               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17316                      "Wrong number of captured regions associated with the "
17317                      "OpenMP construct.");
17318               captureVariablyModifiedType(Context, QTy, OuterRSI);
17319             }
17320           }
17321           bool IsTargetCap =
17322               IsOpenMPPrivateDecl != OMPC_private &&
17323               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17324                                          RSI->OpenMPCaptureLevel);
17325           // Do not capture global if it is not privatized in outer regions.
17326           bool IsGlobalCap =
17327               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17328                                                      RSI->OpenMPCaptureLevel);
17329
17330           // When we detect target captures we are looking from inside the
17331           // target region, therefore we need to propagate the capture from the
17332           // enclosing region. Therefore, the capture is not initially nested.
17333           if (IsTargetCap)
17334             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17335
17336           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17337               (IsGlobal && !IsGlobalCap)) {
17338             Nested = !IsTargetCap;
17339             DeclRefType = DeclRefType.getUnqualifiedType();
17340             CaptureType = Context.getLValueReferenceType(DeclRefType);
17341             break;
17342           }
17343         }
17344       }
17345     }
17346     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17347       // No capture-default, and this is not an explicit capture
17348       // so cannot capture this variable.
17349       if (BuildAndDiagnose) {
17350         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17351         Diag(Var->getLocation(), diag::note_previous_decl)
17352           << Var->getDeclName();
17353         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17354           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17355                diag::note_lambda_decl);
17356         // FIXME: If we error out because an outer lambda can not implicitly
17357         // capture a variable that an inner lambda explicitly captures, we
17358         // should have the inner lambda do the explicit capture - because
17359         // it makes for cleaner diagnostics later.  This would purely be done
17360         // so that the diagnostic does not misleadingly claim that a variable
17361         // can not be captured by a lambda implicitly even though it is captured
17362         // explicitly.  Suggestion:
17363         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17364         //    at the function head
17365         //  - cache the StartingDeclContext - this must be a lambda
17366         //  - captureInLambda in the innermost lambda the variable.
17367       }
17368       return true;
17369     }
17370
17371     FunctionScopesIndex--;
17372     DC = ParentDC;
17373     Explicit = false;
17374   } while (!VarDC->Equals(DC));
17375
17376   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17377   // computing the type of the capture at each step, checking type-specific
17378   // requirements, and adding captures if requested.
17379   // If the variable had already been captured previously, we start capturing
17380   // at the lambda nested within that one.
17381   bool Invalid = false;
17382   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17383        ++I) {
17384     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17385
17386     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17387     // certain types of variables (unnamed, variably modified types etc.)
17388     // so check for eligibility.
17389     if (!Invalid)
17390       Invalid =
17391           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17392
17393     // After encountering an error, if we're actually supposed to capture, keep
17394     // capturing in nested contexts to suppress any follow-on diagnostics.
17395     if (Invalid && !BuildAndDiagnose)
17396       return true;
17397
17398     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17399       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17400                                DeclRefType, Nested, *this, Invalid);
17401       Nested = true;
17402     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17403       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17404                                          CaptureType, DeclRefType, Nested,
17405                                          *this, Invalid);
17406       Nested = true;
17407     } else {
17408       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17409       Invalid =
17410           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17411                            DeclRefType, Nested, Kind, EllipsisLoc,
17412                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17413       Nested = true;
17414     }
17415
17416     if (Invalid && !BuildAndDiagnose)
17417       return true;
17418   }
17419   return Invalid;
17420 }
17421
17422 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17423                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17424   QualType CaptureType;
17425   QualType DeclRefType;
17426   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17427                             /*BuildAndDiagnose=*/true, CaptureType,
17428                             DeclRefType, nullptr);
17429 }
17430
17431 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17432   QualType CaptureType;
17433   QualType DeclRefType;
17434   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17435                              /*BuildAndDiagnose=*/false, CaptureType,
17436                              DeclRefType, nullptr);
17437 }
17438
17439 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17440   QualType CaptureType;
17441   QualType DeclRefType;
17442
17443   // Determine whether we can capture this variable.
17444   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17445                          /*BuildAndDiagnose=*/false, CaptureType,
17446                          DeclRefType, nullptr))
17447     return QualType();
17448
17449   return DeclRefType;
17450 }
17451
17452 namespace {
17453 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17454 // The produced TemplateArgumentListInfo* points to data stored within this
17455 // object, so should only be used in contexts where the pointer will not be
17456 // used after the CopiedTemplateArgs object is destroyed.
17457 class CopiedTemplateArgs {
17458   bool HasArgs;
17459   TemplateArgumentListInfo TemplateArgStorage;
17460 public:
17461   template<typename RefExpr>
17462   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17463     if (HasArgs)
17464       E->copyTemplateArgumentsInto(TemplateArgStorage);
17465   }
17466   operator TemplateArgumentListInfo*()
17467 #ifdef __has_cpp_attribute
17468 #if __has_cpp_attribute(clang::lifetimebound)
17469   [[clang::lifetimebound]]
17470 #endif
17471 #endif
17472   {
17473     return HasArgs ? &TemplateArgStorage : nullptr;
17474   }
17475 };
17476 }
17477
17478 /// Walk the set of potential results of an expression and mark them all as
17479 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17480 ///
17481 /// \return A new expression if we found any potential results, ExprEmpty() if
17482 ///         not, and ExprError() if we diagnosed an error.
17483 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17484                                                       NonOdrUseReason NOUR) {
17485   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17486   // an object that satisfies the requirements for appearing in a
17487   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17488   // is immediately applied."  This function handles the lvalue-to-rvalue
17489   // conversion part.
17490   //
17491   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17492   // transform it into the relevant kind of non-odr-use node and rebuild the
17493   // tree of nodes leading to it.
17494   //
17495   // This is a mini-TreeTransform that only transforms a restricted subset of
17496   // nodes (and only certain operands of them).
17497
17498   // Rebuild a subexpression.
17499   auto Rebuild = [&](Expr *Sub) {
17500     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17501   };
17502
17503   // Check whether a potential result satisfies the requirements of NOUR.
17504   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17505     // Any entity other than a VarDecl is always odr-used whenever it's named
17506     // in a potentially-evaluated expression.
17507     auto *VD = dyn_cast<VarDecl>(D);
17508     if (!VD)
17509       return true;
17510
17511     // C++2a [basic.def.odr]p4:
17512     //   A variable x whose name appears as a potentially-evalauted expression
17513     //   e is odr-used by e unless
17514     //   -- x is a reference that is usable in constant expressions, or
17515     //   -- x is a variable of non-reference type that is usable in constant
17516     //      expressions and has no mutable subobjects, and e is an element of
17517     //      the set of potential results of an expression of
17518     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17519     //      conversion is applied, or
17520     //   -- x is a variable of non-reference type, and e is an element of the
17521     //      set of potential results of a discarded-value expression to which
17522     //      the lvalue-to-rvalue conversion is not applied
17523     //
17524     // We check the first bullet and the "potentially-evaluated" condition in
17525     // BuildDeclRefExpr. We check the type requirements in the second bullet
17526     // in CheckLValueToRValueConversionOperand below.
17527     switch (NOUR) {
17528     case NOUR_None:
17529     case NOUR_Unevaluated:
17530       llvm_unreachable("unexpected non-odr-use-reason");
17531
17532     case NOUR_Constant:
17533       // Constant references were handled when they were built.
17534       if (VD->getType()->isReferenceType())
17535         return true;
17536       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17537         if (RD->hasMutableFields())
17538           return true;
17539       if (!VD->isUsableInConstantExpressions(S.Context))
17540         return true;
17541       break;
17542
17543     case NOUR_Discarded:
17544       if (VD->getType()->isReferenceType())
17545         return true;
17546       break;
17547     }
17548     return false;
17549   };
17550
17551   // Mark that this expression does not constitute an odr-use.
17552   auto MarkNotOdrUsed = [&] {
17553     S.MaybeODRUseExprs.remove(E);
17554     if (LambdaScopeInfo *LSI = S.getCurLambda())
17555       LSI->markVariableExprAsNonODRUsed(E);
17556   };
17557
17558   // C++2a [basic.def.odr]p2:
17559   //   The set of potential results of an expression e is defined as follows:
17560   switch (E->getStmtClass()) {
17561   //   -- If e is an id-expression, ...
17562   case Expr::DeclRefExprClass: {
17563     auto *DRE = cast<DeclRefExpr>(E);
17564     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17565       break;
17566
17567     // Rebuild as a non-odr-use DeclRefExpr.
17568     MarkNotOdrUsed();
17569     return DeclRefExpr::Create(
17570         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17571         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17572         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17573         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17574   }
17575
17576   case Expr::FunctionParmPackExprClass: {
17577     auto *FPPE = cast<FunctionParmPackExpr>(E);
17578     // If any of the declarations in the pack is odr-used, then the expression
17579     // as a whole constitutes an odr-use.
17580     for (VarDecl *D : *FPPE)
17581       if (IsPotentialResultOdrUsed(D))
17582         return ExprEmpty();
17583
17584     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17585     // nothing cares about whether we marked this as an odr-use, but it might
17586     // be useful for non-compiler tools.
17587     MarkNotOdrUsed();
17588     break;
17589   }
17590
17591   //   -- If e is a subscripting operation with an array operand...
17592   case Expr::ArraySubscriptExprClass: {
17593     auto *ASE = cast<ArraySubscriptExpr>(E);
17594     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17595     if (!OldBase->getType()->isArrayType())
17596       break;
17597     ExprResult Base = Rebuild(OldBase);
17598     if (!Base.isUsable())
17599       return Base;
17600     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17601     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17602     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17603     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17604                                      ASE->getRBracketLoc());
17605   }
17606
17607   case Expr::MemberExprClass: {
17608     auto *ME = cast<MemberExpr>(E);
17609     // -- If e is a class member access expression [...] naming a non-static
17610     //    data member...
17611     if (isa<FieldDecl>(ME->getMemberDecl())) {
17612       ExprResult Base = Rebuild(ME->getBase());
17613       if (!Base.isUsable())
17614         return Base;
17615       return MemberExpr::Create(
17616           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17617           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17618           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17619           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17620           ME->getObjectKind(), ME->isNonOdrUse());
17621     }
17622
17623     if (ME->getMemberDecl()->isCXXInstanceMember())
17624       break;
17625
17626     // -- If e is a class member access expression naming a static data member,
17627     //    ...
17628     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17629       break;
17630
17631     // Rebuild as a non-odr-use MemberExpr.
17632     MarkNotOdrUsed();
17633     return MemberExpr::Create(
17634         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17635         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17636         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17637         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17638     return ExprEmpty();
17639   }
17640
17641   case Expr::BinaryOperatorClass: {
17642     auto *BO = cast<BinaryOperator>(E);
17643     Expr *LHS = BO->getLHS();
17644     Expr *RHS = BO->getRHS();
17645     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17646     if (BO->getOpcode() == BO_PtrMemD) {
17647       ExprResult Sub = Rebuild(LHS);
17648       if (!Sub.isUsable())
17649         return Sub;
17650       LHS = Sub.get();
17651     //   -- If e is a comma expression, ...
17652     } else if (BO->getOpcode() == BO_Comma) {
17653       ExprResult Sub = Rebuild(RHS);
17654       if (!Sub.isUsable())
17655         return Sub;
17656       RHS = Sub.get();
17657     } else {
17658       break;
17659     }
17660     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17661                         LHS, RHS);
17662   }
17663
17664   //   -- If e has the form (e1)...
17665   case Expr::ParenExprClass: {
17666     auto *PE = cast<ParenExpr>(E);
17667     ExprResult Sub = Rebuild(PE->getSubExpr());
17668     if (!Sub.isUsable())
17669       return Sub;
17670     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17671   }
17672
17673   //   -- If e is a glvalue conditional expression, ...
17674   // We don't apply this to a binary conditional operator. FIXME: Should we?
17675   case Expr::ConditionalOperatorClass: {
17676     auto *CO = cast<ConditionalOperator>(E);
17677     ExprResult LHS = Rebuild(CO->getLHS());
17678     if (LHS.isInvalid())
17679       return ExprError();
17680     ExprResult RHS = Rebuild(CO->getRHS());
17681     if (RHS.isInvalid())
17682       return ExprError();
17683     if (!LHS.isUsable() && !RHS.isUsable())
17684       return ExprEmpty();
17685     if (!LHS.isUsable())
17686       LHS = CO->getLHS();
17687     if (!RHS.isUsable())
17688       RHS = CO->getRHS();
17689     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17690                                 CO->getCond(), LHS.get(), RHS.get());
17691   }
17692
17693   // [Clang extension]
17694   //   -- If e has the form __extension__ e1...
17695   case Expr::UnaryOperatorClass: {
17696     auto *UO = cast<UnaryOperator>(E);
17697     if (UO->getOpcode() != UO_Extension)
17698       break;
17699     ExprResult Sub = Rebuild(UO->getSubExpr());
17700     if (!Sub.isUsable())
17701       return Sub;
17702     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17703                           Sub.get());
17704   }
17705
17706   // [Clang extension]
17707   //   -- If e has the form _Generic(...), the set of potential results is the
17708   //      union of the sets of potential results of the associated expressions.
17709   case Expr::GenericSelectionExprClass: {
17710     auto *GSE = cast<GenericSelectionExpr>(E);
17711
17712     SmallVector<Expr *, 4> AssocExprs;
17713     bool AnyChanged = false;
17714     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17715       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17716       if (AssocExpr.isInvalid())
17717         return ExprError();
17718       if (AssocExpr.isUsable()) {
17719         AssocExprs.push_back(AssocExpr.get());
17720         AnyChanged = true;
17721       } else {
17722         AssocExprs.push_back(OrigAssocExpr);
17723       }
17724     }
17725
17726     return AnyChanged ? S.CreateGenericSelectionExpr(
17727                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
17728                             GSE->getRParenLoc(), GSE->getControllingExpr(),
17729                             GSE->getAssocTypeSourceInfos(), AssocExprs)
17730                       : ExprEmpty();
17731   }
17732
17733   // [Clang extension]
17734   //   -- If e has the form __builtin_choose_expr(...), the set of potential
17735   //      results is the union of the sets of potential results of the
17736   //      second and third subexpressions.
17737   case Expr::ChooseExprClass: {
17738     auto *CE = cast<ChooseExpr>(E);
17739
17740     ExprResult LHS = Rebuild(CE->getLHS());
17741     if (LHS.isInvalid())
17742       return ExprError();
17743
17744     ExprResult RHS = Rebuild(CE->getLHS());
17745     if (RHS.isInvalid())
17746       return ExprError();
17747
17748     if (!LHS.get() && !RHS.get())
17749       return ExprEmpty();
17750     if (!LHS.isUsable())
17751       LHS = CE->getLHS();
17752     if (!RHS.isUsable())
17753       RHS = CE->getRHS();
17754
17755     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17756                              RHS.get(), CE->getRParenLoc());
17757   }
17758
17759   // Step through non-syntactic nodes.
17760   case Expr::ConstantExprClass: {
17761     auto *CE = cast<ConstantExpr>(E);
17762     ExprResult Sub = Rebuild(CE->getSubExpr());
17763     if (!Sub.isUsable())
17764       return Sub;
17765     return ConstantExpr::Create(S.Context, Sub.get());
17766   }
17767
17768   // We could mostly rely on the recursive rebuilding to rebuild implicit
17769   // casts, but not at the top level, so rebuild them here.
17770   case Expr::ImplicitCastExprClass: {
17771     auto *ICE = cast<ImplicitCastExpr>(E);
17772     // Only step through the narrow set of cast kinds we expect to encounter.
17773     // Anything else suggests we've left the region in which potential results
17774     // can be found.
17775     switch (ICE->getCastKind()) {
17776     case CK_NoOp:
17777     case CK_DerivedToBase:
17778     case CK_UncheckedDerivedToBase: {
17779       ExprResult Sub = Rebuild(ICE->getSubExpr());
17780       if (!Sub.isUsable())
17781         return Sub;
17782       CXXCastPath Path(ICE->path());
17783       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17784                                  ICE->getValueKind(), &Path);
17785     }
17786
17787     default:
17788       break;
17789     }
17790     break;
17791   }
17792
17793   default:
17794     break;
17795   }
17796
17797   // Can't traverse through this node. Nothing to do.
17798   return ExprEmpty();
17799 }
17800
17801 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17802   // Check whether the operand is or contains an object of non-trivial C union
17803   // type.
17804   if (E->getType().isVolatileQualified() &&
17805       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17806        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17807     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17808                           Sema::NTCUC_LValueToRValueVolatile,
17809                           NTCUK_Destruct|NTCUK_Copy);
17810
17811   // C++2a [basic.def.odr]p4:
17812   //   [...] an expression of non-volatile-qualified non-class type to which
17813   //   the lvalue-to-rvalue conversion is applied [...]
17814   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17815     return E;
17816
17817   ExprResult Result =
17818       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17819   if (Result.isInvalid())
17820     return ExprError();
17821   return Result.get() ? Result : E;
17822 }
17823
17824 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17825   Res = CorrectDelayedTyposInExpr(Res);
17826
17827   if (!Res.isUsable())
17828     return Res;
17829
17830   // If a constant-expression is a reference to a variable where we delay
17831   // deciding whether it is an odr-use, just assume we will apply the
17832   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
17833   // (a non-type template argument), we have special handling anyway.
17834   return CheckLValueToRValueConversionOperand(Res.get());
17835 }
17836
17837 void Sema::CleanupVarDeclMarking() {
17838   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17839   // call.
17840   MaybeODRUseExprSet LocalMaybeODRUseExprs;
17841   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17842
17843   for (Expr *E : LocalMaybeODRUseExprs) {
17844     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17845       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17846                          DRE->getLocation(), *this);
17847     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17848       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17849                          *this);
17850     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17851       for (VarDecl *VD : *FP)
17852         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17853     } else {
17854       llvm_unreachable("Unexpected expression");
17855     }
17856   }
17857
17858   assert(MaybeODRUseExprs.empty() &&
17859          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17860 }
17861
17862 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17863                                     VarDecl *Var, Expr *E) {
17864   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17865           isa<FunctionParmPackExpr>(E)) &&
17866          "Invalid Expr argument to DoMarkVarDeclReferenced");
17867   Var->setReferenced();
17868
17869   if (Var->isInvalidDecl())
17870     return;
17871
17872   auto *MSI = Var->getMemberSpecializationInfo();
17873   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17874                                        : Var->getTemplateSpecializationKind();
17875
17876   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17877   bool UsableInConstantExpr =
17878       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17879
17880   // C++20 [expr.const]p12:
17881   //   A variable [...] is needed for constant evaluation if it is [...] a
17882   //   variable whose name appears as a potentially constant evaluated
17883   //   expression that is either a contexpr variable or is of non-volatile
17884   //   const-qualified integral type or of reference type
17885   bool NeededForConstantEvaluation =
17886       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17887
17888   bool NeedDefinition =
17889       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17890
17891   VarTemplateSpecializationDecl *VarSpec =
17892       dyn_cast<VarTemplateSpecializationDecl>(Var);
17893   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17894          "Can't instantiate a partial template specialization.");
17895
17896   // If this might be a member specialization of a static data member, check
17897   // the specialization is visible. We already did the checks for variable
17898   // template specializations when we created them.
17899   if (NeedDefinition && TSK != TSK_Undeclared &&
17900       !isa<VarTemplateSpecializationDecl>(Var))
17901     SemaRef.checkSpecializationVisibility(Loc, Var);
17902
17903   // Perform implicit instantiation of static data members, static data member
17904   // templates of class templates, and variable template specializations. Delay
17905   // instantiations of variable templates, except for those that could be used
17906   // in a constant expression.
17907   if (NeedDefinition && isTemplateInstantiation(TSK)) {
17908     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17909     // instantiation declaration if a variable is usable in a constant
17910     // expression (among other cases).
17911     bool TryInstantiating =
17912         TSK == TSK_ImplicitInstantiation ||
17913         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17914
17915     if (TryInstantiating) {
17916       SourceLocation PointOfInstantiation =
17917           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17918       bool FirstInstantiation = PointOfInstantiation.isInvalid();
17919       if (FirstInstantiation) {
17920         PointOfInstantiation = Loc;
17921         if (MSI)
17922           MSI->setPointOfInstantiation(PointOfInstantiation);
17923         else
17924           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17925       }
17926
17927       bool InstantiationDependent = false;
17928       bool IsNonDependent =
17929           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17930                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17931                   : true;
17932
17933       // Do not instantiate specializations that are still type-dependent.
17934       if (IsNonDependent) {
17935         if (UsableInConstantExpr) {
17936           // Do not defer instantiations of variables that could be used in a
17937           // constant expression.
17938           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17939             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17940           });
17941         } else if (FirstInstantiation ||
17942                    isa<VarTemplateSpecializationDecl>(Var)) {
17943           // FIXME: For a specialization of a variable template, we don't
17944           // distinguish between "declaration and type implicitly instantiated"
17945           // and "implicit instantiation of definition requested", so we have
17946           // no direct way to avoid enqueueing the pending instantiation
17947           // multiple times.
17948           SemaRef.PendingInstantiations
17949               .push_back(std::make_pair(Var, PointOfInstantiation));
17950         }
17951       }
17952     }
17953   }
17954
17955   // C++2a [basic.def.odr]p4:
17956   //   A variable x whose name appears as a potentially-evaluated expression e
17957   //   is odr-used by e unless
17958   //   -- x is a reference that is usable in constant expressions
17959   //   -- x is a variable of non-reference type that is usable in constant
17960   //      expressions and has no mutable subobjects [FIXME], and e is an
17961   //      element of the set of potential results of an expression of
17962   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17963   //      conversion is applied
17964   //   -- x is a variable of non-reference type, and e is an element of the set
17965   //      of potential results of a discarded-value expression to which the
17966   //      lvalue-to-rvalue conversion is not applied [FIXME]
17967   //
17968   // We check the first part of the second bullet here, and
17969   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17970   // FIXME: To get the third bullet right, we need to delay this even for
17971   // variables that are not usable in constant expressions.
17972
17973   // If we already know this isn't an odr-use, there's nothing more to do.
17974   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17975     if (DRE->isNonOdrUse())
17976       return;
17977   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17978     if (ME->isNonOdrUse())
17979       return;
17980
17981   switch (OdrUse) {
17982   case OdrUseContext::None:
17983     assert((!E || isa<FunctionParmPackExpr>(E)) &&
17984            "missing non-odr-use marking for unevaluated decl ref");
17985     break;
17986
17987   case OdrUseContext::FormallyOdrUsed:
17988     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17989     // behavior.
17990     break;
17991
17992   case OdrUseContext::Used:
17993     // If we might later find that this expression isn't actually an odr-use,
17994     // delay the marking.
17995     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17996       SemaRef.MaybeODRUseExprs.insert(E);
17997     else
17998       MarkVarDeclODRUsed(Var, Loc, SemaRef);
17999     break;
18000
18001   case OdrUseContext::Dependent:
18002     // If this is a dependent context, we don't need to mark variables as
18003     // odr-used, but we may still need to track them for lambda capture.
18004     // FIXME: Do we also need to do this inside dependent typeid expressions
18005     // (which are modeled as unevaluated at this point)?
18006     const bool RefersToEnclosingScope =
18007         (SemaRef.CurContext != Var->getDeclContext() &&
18008          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18009     if (RefersToEnclosingScope) {
18010       LambdaScopeInfo *const LSI =
18011           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18012       if (LSI && (!LSI->CallOperator ||
18013                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18014         // If a variable could potentially be odr-used, defer marking it so
18015         // until we finish analyzing the full expression for any
18016         // lvalue-to-rvalue
18017         // or discarded value conversions that would obviate odr-use.
18018         // Add it to the list of potential captures that will be analyzed
18019         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18020         // unless the variable is a reference that was initialized by a constant
18021         // expression (this will never need to be captured or odr-used).
18022         //
18023         // FIXME: We can simplify this a lot after implementing P0588R1.
18024         assert(E && "Capture variable should be used in an expression.");
18025         if (!Var->getType()->isReferenceType() ||
18026             !Var->isUsableInConstantExpressions(SemaRef.Context))
18027           LSI->addPotentialCapture(E->IgnoreParens());
18028       }
18029     }
18030     break;
18031   }
18032 }
18033
18034 /// Mark a variable referenced, and check whether it is odr-used
18035 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18036 /// used directly for normal expressions referring to VarDecl.
18037 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18038   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18039 }
18040
18041 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18042                                Decl *D, Expr *E, bool MightBeOdrUse) {
18043   if (SemaRef.isInOpenMPDeclareTargetContext())
18044     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18045
18046   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18047     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18048     return;
18049   }
18050
18051   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18052
18053   // If this is a call to a method via a cast, also mark the method in the
18054   // derived class used in case codegen can devirtualize the call.
18055   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18056   if (!ME)
18057     return;
18058   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18059   if (!MD)
18060     return;
18061   // Only attempt to devirtualize if this is truly a virtual call.
18062   bool IsVirtualCall = MD->isVirtual() &&
18063                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18064   if (!IsVirtualCall)
18065     return;
18066
18067   // If it's possible to devirtualize the call, mark the called function
18068   // referenced.
18069   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18070       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18071   if (DM)
18072     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18073 }
18074
18075 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18076 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18077   // TODO: update this with DR# once a defect report is filed.
18078   // C++11 defect. The address of a pure member should not be an ODR use, even
18079   // if it's a qualified reference.
18080   bool OdrUse = true;
18081   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18082     if (Method->isVirtual() &&
18083         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18084       OdrUse = false;
18085
18086   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18087     if (!isConstantEvaluated() && FD->isConsteval() &&
18088         !RebuildingImmediateInvocation)
18089       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18090   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18091 }
18092
18093 /// Perform reference-marking and odr-use handling for a MemberExpr.
18094 void Sema::MarkMemberReferenced(MemberExpr *E) {
18095   // C++11 [basic.def.odr]p2:
18096   //   A non-overloaded function whose name appears as a potentially-evaluated
18097   //   expression or a member of a set of candidate functions, if selected by
18098   //   overload resolution when referred to from a potentially-evaluated
18099   //   expression, is odr-used, unless it is a pure virtual function and its
18100   //   name is not explicitly qualified.
18101   bool MightBeOdrUse = true;
18102   if (E->performsVirtualDispatch(getLangOpts())) {
18103     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18104       if (Method->isPure())
18105         MightBeOdrUse = false;
18106   }
18107   SourceLocation Loc =
18108       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18109   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18110 }
18111
18112 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18113 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18114   for (VarDecl *VD : *E)
18115     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18116 }
18117
18118 /// Perform marking for a reference to an arbitrary declaration.  It
18119 /// marks the declaration referenced, and performs odr-use checking for
18120 /// functions and variables. This method should not be used when building a
18121 /// normal expression which refers to a variable.
18122 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18123                                  bool MightBeOdrUse) {
18124   if (MightBeOdrUse) {
18125     if (auto *VD = dyn_cast<VarDecl>(D)) {
18126       MarkVariableReferenced(Loc, VD);
18127       return;
18128     }
18129   }
18130   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18131     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18132     return;
18133   }
18134   D->setReferenced();
18135 }
18136
18137 namespace {
18138   // Mark all of the declarations used by a type as referenced.
18139   // FIXME: Not fully implemented yet! We need to have a better understanding
18140   // of when we're entering a context we should not recurse into.
18141   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18142   // TreeTransforms rebuilding the type in a new context. Rather than
18143   // duplicating the TreeTransform logic, we should consider reusing it here.
18144   // Currently that causes problems when rebuilding LambdaExprs.
18145   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18146     Sema &S;
18147     SourceLocation Loc;
18148
18149   public:
18150     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18151
18152     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18153
18154     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18155   };
18156 }
18157
18158 bool MarkReferencedDecls::TraverseTemplateArgument(
18159     const TemplateArgument &Arg) {
18160   {
18161     // A non-type template argument is a constant-evaluated context.
18162     EnterExpressionEvaluationContext Evaluated(
18163         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18164     if (Arg.getKind() == TemplateArgument::Declaration) {
18165       if (Decl *D = Arg.getAsDecl())
18166         S.MarkAnyDeclReferenced(Loc, D, true);
18167     } else if (Arg.getKind() == TemplateArgument::Expression) {
18168       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18169     }
18170   }
18171
18172   return Inherited::TraverseTemplateArgument(Arg);
18173 }
18174
18175 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18176   MarkReferencedDecls Marker(*this, Loc);
18177   Marker.TraverseType(T);
18178 }
18179
18180 namespace {
18181 /// Helper class that marks all of the declarations referenced by
18182 /// potentially-evaluated subexpressions as "referenced".
18183 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18184 public:
18185   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18186   bool SkipLocalVariables;
18187
18188   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18189       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18190
18191   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18192     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18193   }
18194
18195   void VisitDeclRefExpr(DeclRefExpr *E) {
18196     // If we were asked not to visit local variables, don't.
18197     if (SkipLocalVariables) {
18198       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18199         if (VD->hasLocalStorage())
18200           return;
18201     }
18202     S.MarkDeclRefReferenced(E);
18203   }
18204
18205   void VisitMemberExpr(MemberExpr *E) {
18206     S.MarkMemberReferenced(E);
18207     Visit(E->getBase());
18208   }
18209 };
18210 } // namespace
18211
18212 /// Mark any declarations that appear within this expression or any
18213 /// potentially-evaluated subexpressions as "referenced".
18214 ///
18215 /// \param SkipLocalVariables If true, don't mark local variables as
18216 /// 'referenced'.
18217 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18218                                             bool SkipLocalVariables) {
18219   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18220 }
18221
18222 /// Emit a diagnostic that describes an effect on the run-time behavior
18223 /// of the program being compiled.
18224 ///
18225 /// This routine emits the given diagnostic when the code currently being
18226 /// type-checked is "potentially evaluated", meaning that there is a
18227 /// possibility that the code will actually be executable. Code in sizeof()
18228 /// expressions, code used only during overload resolution, etc., are not
18229 /// potentially evaluated. This routine will suppress such diagnostics or,
18230 /// in the absolutely nutty case of potentially potentially evaluated
18231 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18232 /// later.
18233 ///
18234 /// This routine should be used for all diagnostics that describe the run-time
18235 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18236 /// Failure to do so will likely result in spurious diagnostics or failures
18237 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18238 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18239                                const PartialDiagnostic &PD) {
18240   switch (ExprEvalContexts.back().Context) {
18241   case ExpressionEvaluationContext::Unevaluated:
18242   case ExpressionEvaluationContext::UnevaluatedList:
18243   case ExpressionEvaluationContext::UnevaluatedAbstract:
18244   case ExpressionEvaluationContext::DiscardedStatement:
18245     // The argument will never be evaluated, so don't complain.
18246     break;
18247
18248   case ExpressionEvaluationContext::ConstantEvaluated:
18249     // Relevant diagnostics should be produced by constant evaluation.
18250     break;
18251
18252   case ExpressionEvaluationContext::PotentiallyEvaluated:
18253   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18254     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18255       FunctionScopes.back()->PossiblyUnreachableDiags.
18256         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18257       return true;
18258     }
18259
18260     // The initializer of a constexpr variable or of the first declaration of a
18261     // static data member is not syntactically a constant evaluated constant,
18262     // but nonetheless is always required to be a constant expression, so we
18263     // can skip diagnosing.
18264     // FIXME: Using the mangling context here is a hack.
18265     if (auto *VD = dyn_cast_or_null<VarDecl>(
18266             ExprEvalContexts.back().ManglingContextDecl)) {
18267       if (VD->isConstexpr() ||
18268           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18269         break;
18270       // FIXME: For any other kind of variable, we should build a CFG for its
18271       // initializer and check whether the context in question is reachable.
18272     }
18273
18274     Diag(Loc, PD);
18275     return true;
18276   }
18277
18278   return false;
18279 }
18280
18281 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18282                                const PartialDiagnostic &PD) {
18283   return DiagRuntimeBehavior(
18284       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18285 }
18286
18287 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18288                                CallExpr *CE, FunctionDecl *FD) {
18289   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18290     return false;
18291
18292   // If we're inside a decltype's expression, don't check for a valid return
18293   // type or construct temporaries until we know whether this is the last call.
18294   if (ExprEvalContexts.back().ExprContext ==
18295       ExpressionEvaluationContextRecord::EK_Decltype) {
18296     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18297     return false;
18298   }
18299
18300   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18301     FunctionDecl *FD;
18302     CallExpr *CE;
18303
18304   public:
18305     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18306       : FD(FD), CE(CE) { }
18307
18308     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18309       if (!FD) {
18310         S.Diag(Loc, diag::err_call_incomplete_return)
18311           << T << CE->getSourceRange();
18312         return;
18313       }
18314
18315       S.Diag(Loc, diag::err_call_function_incomplete_return)
18316         << CE->getSourceRange() << FD->getDeclName() << T;
18317       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18318           << FD->getDeclName();
18319     }
18320   } Diagnoser(FD, CE);
18321
18322   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18323     return true;
18324
18325   return false;
18326 }
18327
18328 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18329 // will prevent this condition from triggering, which is what we want.
18330 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18331   SourceLocation Loc;
18332
18333   unsigned diagnostic = diag::warn_condition_is_assignment;
18334   bool IsOrAssign = false;
18335
18336   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18337     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18338       return;
18339
18340     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18341
18342     // Greylist some idioms by putting them into a warning subcategory.
18343     if (ObjCMessageExpr *ME
18344           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18345       Selector Sel = ME->getSelector();
18346
18347       // self = [<foo> init...]
18348       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18349         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18350
18351       // <foo> = [<bar> nextObject]
18352       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18353         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18354     }
18355
18356     Loc = Op->getOperatorLoc();
18357   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18358     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18359       return;
18360
18361     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18362     Loc = Op->getOperatorLoc();
18363   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18364     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18365   else {
18366     // Not an assignment.
18367     return;
18368   }
18369
18370   Diag(Loc, diagnostic) << E->getSourceRange();
18371
18372   SourceLocation Open = E->getBeginLoc();
18373   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18374   Diag(Loc, diag::note_condition_assign_silence)
18375         << FixItHint::CreateInsertion(Open, "(")
18376         << FixItHint::CreateInsertion(Close, ")");
18377
18378   if (IsOrAssign)
18379     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18380       << FixItHint::CreateReplacement(Loc, "!=");
18381   else
18382     Diag(Loc, diag::note_condition_assign_to_comparison)
18383       << FixItHint::CreateReplacement(Loc, "==");
18384 }
18385
18386 /// Redundant parentheses over an equality comparison can indicate
18387 /// that the user intended an assignment used as condition.
18388 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18389   // Don't warn if the parens came from a macro.
18390   SourceLocation parenLoc = ParenE->getBeginLoc();
18391   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18392     return;
18393   // Don't warn for dependent expressions.
18394   if (ParenE->isTypeDependent())
18395     return;
18396
18397   Expr *E = ParenE->IgnoreParens();
18398
18399   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18400     if (opE->getOpcode() == BO_EQ &&
18401         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18402                                                            == Expr::MLV_Valid) {
18403       SourceLocation Loc = opE->getOperatorLoc();
18404
18405       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18406       SourceRange ParenERange = ParenE->getSourceRange();
18407       Diag(Loc, diag::note_equality_comparison_silence)
18408         << FixItHint::CreateRemoval(ParenERange.getBegin())
18409         << FixItHint::CreateRemoval(ParenERange.getEnd());
18410       Diag(Loc, diag::note_equality_comparison_to_assign)
18411         << FixItHint::CreateReplacement(Loc, "=");
18412     }
18413 }
18414
18415 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18416                                        bool IsConstexpr) {
18417   DiagnoseAssignmentAsCondition(E);
18418   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18419     DiagnoseEqualityWithExtraParens(parenE);
18420
18421   ExprResult result = CheckPlaceholderExpr(E);
18422   if (result.isInvalid()) return ExprError();
18423   E = result.get();
18424
18425   if (!E->isTypeDependent()) {
18426     if (getLangOpts().CPlusPlus)
18427       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18428
18429     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18430     if (ERes.isInvalid())
18431       return ExprError();
18432     E = ERes.get();
18433
18434     QualType T = E->getType();
18435     if (!T->isScalarType()) { // C99 6.8.4.1p1
18436       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18437         << T << E->getSourceRange();
18438       return ExprError();
18439     }
18440     CheckBoolLikeConversion(E, Loc);
18441   }
18442
18443   return E;
18444 }
18445
18446 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18447                                            Expr *SubExpr, ConditionKind CK) {
18448   // Empty conditions are valid in for-statements.
18449   if (!SubExpr)
18450     return ConditionResult();
18451
18452   ExprResult Cond;
18453   switch (CK) {
18454   case ConditionKind::Boolean:
18455     Cond = CheckBooleanCondition(Loc, SubExpr);
18456     break;
18457
18458   case ConditionKind::ConstexprIf:
18459     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18460     break;
18461
18462   case ConditionKind::Switch:
18463     Cond = CheckSwitchCondition(Loc, SubExpr);
18464     break;
18465   }
18466   if (Cond.isInvalid())
18467     return ConditionError();
18468
18469   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18470   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18471   if (!FullExpr.get())
18472     return ConditionError();
18473
18474   return ConditionResult(*this, nullptr, FullExpr,
18475                          CK == ConditionKind::ConstexprIf);
18476 }
18477
18478 namespace {
18479   /// A visitor for rebuilding a call to an __unknown_any expression
18480   /// to have an appropriate type.
18481   struct RebuildUnknownAnyFunction
18482     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18483
18484     Sema &S;
18485
18486     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18487
18488     ExprResult VisitStmt(Stmt *S) {
18489       llvm_unreachable("unexpected statement!");
18490     }
18491
18492     ExprResult VisitExpr(Expr *E) {
18493       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18494         << E->getSourceRange();
18495       return ExprError();
18496     }
18497
18498     /// Rebuild an expression which simply semantically wraps another
18499     /// expression which it shares the type and value kind of.
18500     template <class T> ExprResult rebuildSugarExpr(T *E) {
18501       ExprResult SubResult = Visit(E->getSubExpr());
18502       if (SubResult.isInvalid()) return ExprError();
18503
18504       Expr *SubExpr = SubResult.get();
18505       E->setSubExpr(SubExpr);
18506       E->setType(SubExpr->getType());
18507       E->setValueKind(SubExpr->getValueKind());
18508       assert(E->getObjectKind() == OK_Ordinary);
18509       return E;
18510     }
18511
18512     ExprResult VisitParenExpr(ParenExpr *E) {
18513       return rebuildSugarExpr(E);
18514     }
18515
18516     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18517       return rebuildSugarExpr(E);
18518     }
18519
18520     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18521       ExprResult SubResult = Visit(E->getSubExpr());
18522       if (SubResult.isInvalid()) return ExprError();
18523
18524       Expr *SubExpr = SubResult.get();
18525       E->setSubExpr(SubExpr);
18526       E->setType(S.Context.getPointerType(SubExpr->getType()));
18527       assert(E->getValueKind() == VK_RValue);
18528       assert(E->getObjectKind() == OK_Ordinary);
18529       return E;
18530     }
18531
18532     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18533       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18534
18535       E->setType(VD->getType());
18536
18537       assert(E->getValueKind() == VK_RValue);
18538       if (S.getLangOpts().CPlusPlus &&
18539           !(isa<CXXMethodDecl>(VD) &&
18540             cast<CXXMethodDecl>(VD)->isInstance()))
18541         E->setValueKind(VK_LValue);
18542
18543       return E;
18544     }
18545
18546     ExprResult VisitMemberExpr(MemberExpr *E) {
18547       return resolveDecl(E, E->getMemberDecl());
18548     }
18549
18550     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18551       return resolveDecl(E, E->getDecl());
18552     }
18553   };
18554 }
18555
18556 /// Given a function expression of unknown-any type, try to rebuild it
18557 /// to have a function type.
18558 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18559   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18560   if (Result.isInvalid()) return ExprError();
18561   return S.DefaultFunctionArrayConversion(Result.get());
18562 }
18563
18564 namespace {
18565   /// A visitor for rebuilding an expression of type __unknown_anytype
18566   /// into one which resolves the type directly on the referring
18567   /// expression.  Strict preservation of the original source
18568   /// structure is not a goal.
18569   struct RebuildUnknownAnyExpr
18570     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18571
18572     Sema &S;
18573
18574     /// The current destination type.
18575     QualType DestType;
18576
18577     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18578       : S(S), DestType(CastType) {}
18579
18580     ExprResult VisitStmt(Stmt *S) {
18581       llvm_unreachable("unexpected statement!");
18582     }
18583
18584     ExprResult VisitExpr(Expr *E) {
18585       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18586         << E->getSourceRange();
18587       return ExprError();
18588     }
18589
18590     ExprResult VisitCallExpr(CallExpr *E);
18591     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18592
18593     /// Rebuild an expression which simply semantically wraps another
18594     /// expression which it shares the type and value kind of.
18595     template <class T> ExprResult rebuildSugarExpr(T *E) {
18596       ExprResult SubResult = Visit(E->getSubExpr());
18597       if (SubResult.isInvalid()) return ExprError();
18598       Expr *SubExpr = SubResult.get();
18599       E->setSubExpr(SubExpr);
18600       E->setType(SubExpr->getType());
18601       E->setValueKind(SubExpr->getValueKind());
18602       assert(E->getObjectKind() == OK_Ordinary);
18603       return E;
18604     }
18605
18606     ExprResult VisitParenExpr(ParenExpr *E) {
18607       return rebuildSugarExpr(E);
18608     }
18609
18610     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18611       return rebuildSugarExpr(E);
18612     }
18613
18614     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18615       const PointerType *Ptr = DestType->getAs<PointerType>();
18616       if (!Ptr) {
18617         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18618           << E->getSourceRange();
18619         return ExprError();
18620       }
18621
18622       if (isa<CallExpr>(E->getSubExpr())) {
18623         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18624           << E->getSourceRange();
18625         return ExprError();
18626       }
18627
18628       assert(E->getValueKind() == VK_RValue);
18629       assert(E->getObjectKind() == OK_Ordinary);
18630       E->setType(DestType);
18631
18632       // Build the sub-expression as if it were an object of the pointee type.
18633       DestType = Ptr->getPointeeType();
18634       ExprResult SubResult = Visit(E->getSubExpr());
18635       if (SubResult.isInvalid()) return ExprError();
18636       E->setSubExpr(SubResult.get());
18637       return E;
18638     }
18639
18640     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18641
18642     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18643
18644     ExprResult VisitMemberExpr(MemberExpr *E) {
18645       return resolveDecl(E, E->getMemberDecl());
18646     }
18647
18648     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18649       return resolveDecl(E, E->getDecl());
18650     }
18651   };
18652 }
18653
18654 /// Rebuilds a call expression which yielded __unknown_anytype.
18655 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18656   Expr *CalleeExpr = E->getCallee();
18657
18658   enum FnKind {
18659     FK_MemberFunction,
18660     FK_FunctionPointer,
18661     FK_BlockPointer
18662   };
18663
18664   FnKind Kind;
18665   QualType CalleeType = CalleeExpr->getType();
18666   if (CalleeType == S.Context.BoundMemberTy) {
18667     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18668     Kind = FK_MemberFunction;
18669     CalleeType = Expr::findBoundMemberType(CalleeExpr);
18670   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18671     CalleeType = Ptr->getPointeeType();
18672     Kind = FK_FunctionPointer;
18673   } else {
18674     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18675     Kind = FK_BlockPointer;
18676   }
18677   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18678
18679   // Verify that this is a legal result type of a function.
18680   if (DestType->isArrayType() || DestType->isFunctionType()) {
18681     unsigned diagID = diag::err_func_returning_array_function;
18682     if (Kind == FK_BlockPointer)
18683       diagID = diag::err_block_returning_array_function;
18684
18685     S.Diag(E->getExprLoc(), diagID)
18686       << DestType->isFunctionType() << DestType;
18687     return ExprError();
18688   }
18689
18690   // Otherwise, go ahead and set DestType as the call's result.
18691   E->setType(DestType.getNonLValueExprType(S.Context));
18692   E->setValueKind(Expr::getValueKindForType(DestType));
18693   assert(E->getObjectKind() == OK_Ordinary);
18694
18695   // Rebuild the function type, replacing the result type with DestType.
18696   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18697   if (Proto) {
18698     // __unknown_anytype(...) is a special case used by the debugger when
18699     // it has no idea what a function's signature is.
18700     //
18701     // We want to build this call essentially under the K&R
18702     // unprototyped rules, but making a FunctionNoProtoType in C++
18703     // would foul up all sorts of assumptions.  However, we cannot
18704     // simply pass all arguments as variadic arguments, nor can we
18705     // portably just call the function under a non-variadic type; see
18706     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18707     // However, it turns out that in practice it is generally safe to
18708     // call a function declared as "A foo(B,C,D);" under the prototype
18709     // "A foo(B,C,D,...);".  The only known exception is with the
18710     // Windows ABI, where any variadic function is implicitly cdecl
18711     // regardless of its normal CC.  Therefore we change the parameter
18712     // types to match the types of the arguments.
18713     //
18714     // This is a hack, but it is far superior to moving the
18715     // corresponding target-specific code from IR-gen to Sema/AST.
18716
18717     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18718     SmallVector<QualType, 8> ArgTypes;
18719     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18720       ArgTypes.reserve(E->getNumArgs());
18721       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18722         Expr *Arg = E->getArg(i);
18723         QualType ArgType = Arg->getType();
18724         if (E->isLValue()) {
18725           ArgType = S.Context.getLValueReferenceType(ArgType);
18726         } else if (E->isXValue()) {
18727           ArgType = S.Context.getRValueReferenceType(ArgType);
18728         }
18729         ArgTypes.push_back(ArgType);
18730       }
18731       ParamTypes = ArgTypes;
18732     }
18733     DestType = S.Context.getFunctionType(DestType, ParamTypes,
18734                                          Proto->getExtProtoInfo());
18735   } else {
18736     DestType = S.Context.getFunctionNoProtoType(DestType,
18737                                                 FnType->getExtInfo());
18738   }
18739
18740   // Rebuild the appropriate pointer-to-function type.
18741   switch (Kind) {
18742   case FK_MemberFunction:
18743     // Nothing to do.
18744     break;
18745
18746   case FK_FunctionPointer:
18747     DestType = S.Context.getPointerType(DestType);
18748     break;
18749
18750   case FK_BlockPointer:
18751     DestType = S.Context.getBlockPointerType(DestType);
18752     break;
18753   }
18754
18755   // Finally, we can recurse.
18756   ExprResult CalleeResult = Visit(CalleeExpr);
18757   if (!CalleeResult.isUsable()) return ExprError();
18758   E->setCallee(CalleeResult.get());
18759
18760   // Bind a temporary if necessary.
18761   return S.MaybeBindToTemporary(E);
18762 }
18763
18764 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18765   // Verify that this is a legal result type of a call.
18766   if (DestType->isArrayType() || DestType->isFunctionType()) {
18767     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18768       << DestType->isFunctionType() << DestType;
18769     return ExprError();
18770   }
18771
18772   // Rewrite the method result type if available.
18773   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18774     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18775     Method->setReturnType(DestType);
18776   }
18777
18778   // Change the type of the message.
18779   E->setType(DestType.getNonReferenceType());
18780   E->setValueKind(Expr::getValueKindForType(DestType));
18781
18782   return S.MaybeBindToTemporary(E);
18783 }
18784
18785 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18786   // The only case we should ever see here is a function-to-pointer decay.
18787   if (E->getCastKind() == CK_FunctionToPointerDecay) {
18788     assert(E->getValueKind() == VK_RValue);
18789     assert(E->getObjectKind() == OK_Ordinary);
18790
18791     E->setType(DestType);
18792
18793     // Rebuild the sub-expression as the pointee (function) type.
18794     DestType = DestType->castAs<PointerType>()->getPointeeType();
18795
18796     ExprResult Result = Visit(E->getSubExpr());
18797     if (!Result.isUsable()) return ExprError();
18798
18799     E->setSubExpr(Result.get());
18800     return E;
18801   } else if (E->getCastKind() == CK_LValueToRValue) {
18802     assert(E->getValueKind() == VK_RValue);
18803     assert(E->getObjectKind() == OK_Ordinary);
18804
18805     assert(isa<BlockPointerType>(E->getType()));
18806
18807     E->setType(DestType);
18808
18809     // The sub-expression has to be a lvalue reference, so rebuild it as such.
18810     DestType = S.Context.getLValueReferenceType(DestType);
18811
18812     ExprResult Result = Visit(E->getSubExpr());
18813     if (!Result.isUsable()) return ExprError();
18814
18815     E->setSubExpr(Result.get());
18816     return E;
18817   } else {
18818     llvm_unreachable("Unhandled cast type!");
18819   }
18820 }
18821
18822 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18823   ExprValueKind ValueKind = VK_LValue;
18824   QualType Type = DestType;
18825
18826   // We know how to make this work for certain kinds of decls:
18827
18828   //  - functions
18829   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18830     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18831       DestType = Ptr->getPointeeType();
18832       ExprResult Result = resolveDecl(E, VD);
18833       if (Result.isInvalid()) return ExprError();
18834       return S.ImpCastExprToType(Result.get(), Type,
18835                                  CK_FunctionToPointerDecay, VK_RValue);
18836     }
18837
18838     if (!Type->isFunctionType()) {
18839       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18840         << VD << E->getSourceRange();
18841       return ExprError();
18842     }
18843     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18844       // We must match the FunctionDecl's type to the hack introduced in
18845       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18846       // type. See the lengthy commentary in that routine.
18847       QualType FDT = FD->getType();
18848       const FunctionType *FnType = FDT->castAs<FunctionType>();
18849       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18850       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18851       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18852         SourceLocation Loc = FD->getLocation();
18853         FunctionDecl *NewFD = FunctionDecl::Create(
18854             S.Context, FD->getDeclContext(), Loc, Loc,
18855             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18856             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18857             /*ConstexprKind*/ CSK_unspecified);
18858
18859         if (FD->getQualifier())
18860           NewFD->setQualifierInfo(FD->getQualifierLoc());
18861
18862         SmallVector<ParmVarDecl*, 16> Params;
18863         for (const auto &AI : FT->param_types()) {
18864           ParmVarDecl *Param =
18865             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18866           Param->setScopeInfo(0, Params.size());
18867           Params.push_back(Param);
18868         }
18869         NewFD->setParams(Params);
18870         DRE->setDecl(NewFD);
18871         VD = DRE->getDecl();
18872       }
18873     }
18874
18875     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18876       if (MD->isInstance()) {
18877         ValueKind = VK_RValue;
18878         Type = S.Context.BoundMemberTy;
18879       }
18880
18881     // Function references aren't l-values in C.
18882     if (!S.getLangOpts().CPlusPlus)
18883       ValueKind = VK_RValue;
18884
18885   //  - variables
18886   } else if (isa<VarDecl>(VD)) {
18887     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18888       Type = RefTy->getPointeeType();
18889     } else if (Type->isFunctionType()) {
18890       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18891         << VD << E->getSourceRange();
18892       return ExprError();
18893     }
18894
18895   //  - nothing else
18896   } else {
18897     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18898       << VD << E->getSourceRange();
18899     return ExprError();
18900   }
18901
18902   // Modifying the declaration like this is friendly to IR-gen but
18903   // also really dangerous.
18904   VD->setType(DestType);
18905   E->setType(Type);
18906   E->setValueKind(ValueKind);
18907   return E;
18908 }
18909
18910 /// Check a cast of an unknown-any type.  We intentionally only
18911 /// trigger this for C-style casts.
18912 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18913                                      Expr *CastExpr, CastKind &CastKind,
18914                                      ExprValueKind &VK, CXXCastPath &Path) {
18915   // The type we're casting to must be either void or complete.
18916   if (!CastType->isVoidType() &&
18917       RequireCompleteType(TypeRange.getBegin(), CastType,
18918                           diag::err_typecheck_cast_to_incomplete))
18919     return ExprError();
18920
18921   // Rewrite the casted expression from scratch.
18922   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18923   if (!result.isUsable()) return ExprError();
18924
18925   CastExpr = result.get();
18926   VK = CastExpr->getValueKind();
18927   CastKind = CK_NoOp;
18928
18929   return CastExpr;
18930 }
18931
18932 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18933   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18934 }
18935
18936 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18937                                     Expr *arg, QualType &paramType) {
18938   // If the syntactic form of the argument is not an explicit cast of
18939   // any sort, just do default argument promotion.
18940   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18941   if (!castArg) {
18942     ExprResult result = DefaultArgumentPromotion(arg);
18943     if (result.isInvalid()) return ExprError();
18944     paramType = result.get()->getType();
18945     return result;
18946   }
18947
18948   // Otherwise, use the type that was written in the explicit cast.
18949   assert(!arg->hasPlaceholderType());
18950   paramType = castArg->getTypeAsWritten();
18951
18952   // Copy-initialize a parameter of that type.
18953   InitializedEntity entity =
18954     InitializedEntity::InitializeParameter(Context, paramType,
18955                                            /*consumed*/ false);
18956   return PerformCopyInitialization(entity, callLoc, arg);
18957 }
18958
18959 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18960   Expr *orig = E;
18961   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18962   while (true) {
18963     E = E->IgnoreParenImpCasts();
18964     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18965       E = call->getCallee();
18966       diagID = diag::err_uncasted_call_of_unknown_any;
18967     } else {
18968       break;
18969     }
18970   }
18971
18972   SourceLocation loc;
18973   NamedDecl *d;
18974   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18975     loc = ref->getLocation();
18976     d = ref->getDecl();
18977   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18978     loc = mem->getMemberLoc();
18979     d = mem->getMemberDecl();
18980   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18981     diagID = diag::err_uncasted_call_of_unknown_any;
18982     loc = msg->getSelectorStartLoc();
18983     d = msg->getMethodDecl();
18984     if (!d) {
18985       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18986         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18987         << orig->getSourceRange();
18988       return ExprError();
18989     }
18990   } else {
18991     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18992       << E->getSourceRange();
18993     return ExprError();
18994   }
18995
18996   S.Diag(loc, diagID) << d << orig->getSourceRange();
18997
18998   // Never recoverable.
18999   return ExprError();
19000 }
19001
19002 /// Check for operands with placeholder types and complain if found.
19003 /// Returns ExprError() if there was an error and no recovery was possible.
19004 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19005   if (!getLangOpts().CPlusPlus) {
19006     // C cannot handle TypoExpr nodes on either side of a binop because it
19007     // doesn't handle dependent types properly, so make sure any TypoExprs have
19008     // been dealt with before checking the operands.
19009     ExprResult Result = CorrectDelayedTyposInExpr(E);
19010     if (!Result.isUsable()) return ExprError();
19011     E = Result.get();
19012   }
19013
19014   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19015   if (!placeholderType) return E;
19016
19017   switch (placeholderType->getKind()) {
19018
19019   // Overloaded expressions.
19020   case BuiltinType::Overload: {
19021     // Try to resolve a single function template specialization.
19022     // This is obligatory.
19023     ExprResult Result = E;
19024     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19025       return Result;
19026
19027     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19028     // leaves Result unchanged on failure.
19029     Result = E;
19030     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19031       return Result;
19032
19033     // If that failed, try to recover with a call.
19034     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19035                          /*complain*/ true);
19036     return Result;
19037   }
19038
19039   // Bound member functions.
19040   case BuiltinType::BoundMember: {
19041     ExprResult result = E;
19042     const Expr *BME = E->IgnoreParens();
19043     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19044     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19045     if (isa<CXXPseudoDestructorExpr>(BME)) {
19046       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19047     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19048       if (ME->getMemberNameInfo().getName().getNameKind() ==
19049           DeclarationName::CXXDestructorName)
19050         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19051     }
19052     tryToRecoverWithCall(result, PD,
19053                          /*complain*/ true);
19054     return result;
19055   }
19056
19057   // ARC unbridged casts.
19058   case BuiltinType::ARCUnbridgedCast: {
19059     Expr *realCast = stripARCUnbridgedCast(E);
19060     diagnoseARCUnbridgedCast(realCast);
19061     return realCast;
19062   }
19063
19064   // Expressions of unknown type.
19065   case BuiltinType::UnknownAny:
19066     return diagnoseUnknownAnyExpr(*this, E);
19067
19068   // Pseudo-objects.
19069   case BuiltinType::PseudoObject:
19070     return checkPseudoObjectRValue(E);
19071
19072   case BuiltinType::BuiltinFn: {
19073     // Accept __noop without parens by implicitly converting it to a call expr.
19074     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19075     if (DRE) {
19076       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19077       if (FD->getBuiltinID() == Builtin::BI__noop) {
19078         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19079                               CK_BuiltinFnToFnPtr)
19080                 .get();
19081         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19082                                 VK_RValue, SourceLocation());
19083       }
19084     }
19085
19086     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19087     return ExprError();
19088   }
19089
19090   case BuiltinType::IncompleteMatrixIdx:
19091     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19092              ->getRowIdx()
19093              ->getBeginLoc(),
19094          diag::err_matrix_incomplete_index);
19095     return ExprError();
19096
19097   // Expressions of unknown type.
19098   case BuiltinType::OMPArraySection:
19099     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19100     return ExprError();
19101
19102   // Expressions of unknown type.
19103   case BuiltinType::OMPArrayShaping:
19104     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19105
19106   case BuiltinType::OMPIterator:
19107     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19108
19109   // Everything else should be impossible.
19110 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19111   case BuiltinType::Id:
19112 #include "clang/Basic/OpenCLImageTypes.def"
19113 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19114   case BuiltinType::Id:
19115 #include "clang/Basic/OpenCLExtensionTypes.def"
19116 #define SVE_TYPE(Name, Id, SingletonId) \
19117   case BuiltinType::Id:
19118 #include "clang/Basic/AArch64SVEACLETypes.def"
19119 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19120 #define PLACEHOLDER_TYPE(Id, SingletonId)
19121 #include "clang/AST/BuiltinTypes.def"
19122     break;
19123   }
19124
19125   llvm_unreachable("invalid placeholder type!");
19126 }
19127
19128 bool Sema::CheckCaseExpression(Expr *E) {
19129   if (E->isTypeDependent())
19130     return true;
19131   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19132     return E->getType()->isIntegralOrEnumerationType();
19133   return false;
19134 }
19135
19136 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19137 ExprResult
19138 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19139   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19140          "Unknown Objective-C Boolean value!");
19141   QualType BoolT = Context.ObjCBuiltinBoolTy;
19142   if (!Context.getBOOLDecl()) {
19143     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19144                         Sema::LookupOrdinaryName);
19145     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19146       NamedDecl *ND = Result.getFoundDecl();
19147       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19148         Context.setBOOLDecl(TD);
19149     }
19150   }
19151   if (Context.getBOOLDecl())
19152     BoolT = Context.getBOOLType();
19153   return new (Context)
19154       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19155 }
19156
19157 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19158     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19159     SourceLocation RParen) {
19160
19161   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19162
19163   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19164     return Spec.getPlatform() == Platform;
19165   });
19166
19167   VersionTuple Version;
19168   if (Spec != AvailSpecs.end())
19169     Version = Spec->getVersion();
19170
19171   // The use of `@available` in the enclosing function should be analyzed to
19172   // warn when it's used inappropriately (i.e. not if(@available)).
19173   if (getCurFunctionOrMethodDecl())
19174     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19175   else if (getCurBlock() || getCurLambda())
19176     getCurFunction()->HasPotentialAvailabilityViolations = true;
19177
19178   return new (Context)
19179       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19180 }
19181
19182 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19183                                     ArrayRef<Expr *> SubExprs, QualType T) {
19184   if (!Context.getLangOpts().RecoveryAST)
19185     return ExprError();
19186
19187   if (isSFINAEContext())
19188     return ExprError();
19189
19190   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19191     // We don't know the concrete type, fallback to dependent type.
19192     T = Context.DependentTy;
19193   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19194 }