1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/FixedPoint.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68 
69     // See if this is an aligned allocation/deallocation function that is
70     // unavailable.
71     if (TreatUnavailableAsInvalid &&
72         isUnavailableAlignedAllocationFunction(*FD))
73       return false;
74   }
75 
76   // See if this function is unavailable.
77   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
78       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
79     return false;
80 
81   return true;
82 }
83 
84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
85   // Warn if this is used but marked unused.
86   if (const auto *A = D->getAttr<UnusedAttr>()) {
87     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
88     // should diagnose them.
89     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
90         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
91       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
92       if (DC && !DC->hasAttr<UnusedAttr>())
93         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
94     }
95   }
96 }
97 
98 /// Emit a note explaining that this function is deleted.
99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
100   assert(Decl->isDeleted());
101 
102   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
103 
104   if (Method && Method->isDeleted() && Method->isDefaulted()) {
105     // If the method was explicitly defaulted, point at that declaration.
106     if (!Method->isImplicit())
107       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108 
109     // Try to diagnose why this special member function was implicitly
110     // deleted. This might fail, if that reason no longer applies.
111     CXXSpecialMember CSM = getSpecialMember(Method);
112     if (CSM != CXXInvalid)
113       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
114 
115     return;
116   }
117 
118   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119   if (Ctor && Ctor->isInheritingConstructor())
120     return NoteDeletedInheritingConstructor(Ctor);
121 
122   Diag(Decl->getLocation(), diag::note_availability_specified_here)
123     << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129   for (auto I : D->redecls()) {
130     if (I->getStorageClass() != SC_None)
131       return true;
132   }
133   return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145                                                       const NamedDecl *D,
146                                                       SourceLocation Loc) {
147   // This is disabled under C++; there are too many ways for this to fire in
148   // contexts where the warning is a false positive, or where it is technically
149   // correct but benign.
150   if (S.getLangOpts().CPlusPlus)
151     return;
152 
153   // Check if this is an inlined function or method.
154   FunctionDecl *Current = S.getCurFunctionDecl();
155   if (!Current)
156     return;
157   if (!Current->isInlined())
158     return;
159   if (!Current->isExternallyVisible())
160     return;
161 
162   // Check if the decl has internal linkage.
163   if (D->getFormalLinkage() != InternalLinkage)
164     return;
165 
166   // Downgrade from ExtWarn to Extension if
167   //  (1) the supposedly external inline function is in the main file,
168   //      and probably won't be included anywhere else.
169   //  (2) the thing we're referencing is a pure function.
170   //  (3) the thing we're referencing is another inline function.
171   // This last can give us false negatives, but it's better than warning on
172   // wrappers for simple C library functions.
173   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175   if (!DowngradeWarning && UsedFn)
176     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179                                : diag::ext_internal_in_extern_inline)
180     << /*IsVar=*/!UsedFn << D;
181 
182   S.MaybeSuggestAddingStaticToDecl(Current);
183 
184   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185       << D;
186 }
187 
188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189   const FunctionDecl *First = Cur->getFirstDecl();
190 
191   // Suggest "static" on the function, if possible.
192   if (!hasAnyExplicitStorageClass(First)) {
193     SourceLocation DeclBegin = First->getSourceRange().getBegin();
194     Diag(DeclBegin, diag::note_convert_inline_to_static)
195       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196   }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212                              const ObjCInterfaceDecl *UnknownObjCClass,
213                              bool ObjCPropertyAccess,
214                              bool AvoidPartialAvailabilityChecks,
215                              ObjCInterfaceDecl *ClassReceiver) {
216   SourceLocation Loc = Locs.front();
217   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218     // If there were any diagnostics suppressed by template argument deduction,
219     // emit them now.
220     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221     if (Pos != SuppressedDiagnostics.end()) {
222       for (const PartialDiagnosticAt &Suppressed : Pos->second)
223         Diag(Suppressed.first, Suppressed.second);
224 
225       // Clear out the list of suppressed diagnostics, so that we don't emit
226       // them again for this specialization. However, we don't obsolete this
227       // entry from the table, because we want to avoid ever emitting these
228       // diagnostics again.
229       Pos->second.clear();
230     }
231 
232     // C++ [basic.start.main]p3:
233     //   The function 'main' shall not be used within a program.
234     if (cast<FunctionDecl>(D)->isMain())
235       Diag(Loc, diag::ext_main_used);
236 
237     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238   }
239 
240   // See if this is an auto-typed variable whose initializer we are parsing.
241   if (ParsingInitForAutoVars.count(D)) {
242     if (isa<BindingDecl>(D)) {
243       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244         << D->getDeclName();
245     } else {
246       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247         << D->getDeclName() << cast<VarDecl>(D)->getType();
248     }
249     return true;
250   }
251 
252   // See if this is a deleted function.
253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254     if (FD->isDeleted()) {
255       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256       if (Ctor && Ctor->isInheritingConstructor())
257         Diag(Loc, diag::err_deleted_inherited_ctor_use)
258             << Ctor->getParent()
259             << Ctor->getInheritedConstructor().getConstructor()->getParent();
260       else
261         Diag(Loc, diag::err_deleted_function_use);
262       NoteDeletedFunction(FD);
263       return true;
264     }
265 
266     // If the function has a deduced return type, and we can't deduce it,
267     // then we can't use it either.
268     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
269         DeduceReturnType(FD, Loc))
270       return true;
271 
272     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
273       return true;
274   }
275 
276   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
277     // Lambdas are only default-constructible or assignable in C++2a onwards.
278     if (MD->getParent()->isLambda() &&
279         ((isa<CXXConstructorDecl>(MD) &&
280           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
281          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
282       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
283         << !isa<CXXConstructorDecl>(MD);
284     }
285   }
286 
287   auto getReferencedObjCProp = [](const NamedDecl *D) ->
288                                       const ObjCPropertyDecl * {
289     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
290       return MD->findPropertyDecl();
291     return nullptr;
292   };
293   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
294     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
295       return true;
296   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
297       return true;
298   }
299 
300   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
301   // Only the variables omp_in and omp_out are allowed in the combiner.
302   // Only the variables omp_priv and omp_orig are allowed in the
303   // initializer-clause.
304   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
305   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
306       isa<VarDecl>(D)) {
307     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
308         << getCurFunction()->HasOMPDeclareReductionCombiner;
309     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
310     return true;
311   }
312 
313   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
314   //  List-items in map clauses on this construct may only refer to the declared
315   //  variable var and entities that could be referenced by a procedure defined
316   //  at the same location
317   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
318   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
319       isa<VarDecl>(D)) {
320     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
321         << DMD->getVarName().getAsString();
322     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
323     return true;
324   }
325 
326   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
327                              AvoidPartialAvailabilityChecks, ClassReceiver);
328 
329   DiagnoseUnusedOfDecl(*this, D, Loc);
330 
331   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
332 
333   return false;
334 }
335 
336 /// Retrieve the message suffix that should be added to a
337 /// diagnostic complaining about the given function being deleted or
338 /// unavailable.
339 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
340   std::string Message;
341   if (FD->getAvailability(&Message))
342     return ": " + Message;
343 
344   return std::string();
345 }
346 
347 /// DiagnoseSentinelCalls - This routine checks whether a call or
348 /// message-send is to a declaration with the sentinel attribute, and
349 /// if so, it checks that the requirements of the sentinel are
350 /// satisfied.
351 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
352                                  ArrayRef<Expr *> Args) {
353   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
354   if (!attr)
355     return;
356 
357   // The number of formal parameters of the declaration.
358   unsigned numFormalParams;
359 
360   // The kind of declaration.  This is also an index into a %select in
361   // the diagnostic.
362   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
363 
364   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
365     numFormalParams = MD->param_size();
366     calleeType = CT_Method;
367   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
368     numFormalParams = FD->param_size();
369     calleeType = CT_Function;
370   } else if (isa<VarDecl>(D)) {
371     QualType type = cast<ValueDecl>(D)->getType();
372     const FunctionType *fn = nullptr;
373     if (const PointerType *ptr = type->getAs<PointerType>()) {
374       fn = ptr->getPointeeType()->getAs<FunctionType>();
375       if (!fn) return;
376       calleeType = CT_Function;
377     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
378       fn = ptr->getPointeeType()->castAs<FunctionType>();
379       calleeType = CT_Block;
380     } else {
381       return;
382     }
383 
384     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
385       numFormalParams = proto->getNumParams();
386     } else {
387       numFormalParams = 0;
388     }
389   } else {
390     return;
391   }
392 
393   // "nullPos" is the number of formal parameters at the end which
394   // effectively count as part of the variadic arguments.  This is
395   // useful if you would prefer to not have *any* formal parameters,
396   // but the language forces you to have at least one.
397   unsigned nullPos = attr->getNullPos();
398   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
399   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
400 
401   // The number of arguments which should follow the sentinel.
402   unsigned numArgsAfterSentinel = attr->getSentinel();
403 
404   // If there aren't enough arguments for all the formal parameters,
405   // the sentinel, and the args after the sentinel, complain.
406   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
407     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
408     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
409     return;
410   }
411 
412   // Otherwise, find the sentinel expression.
413   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
414   if (!sentinelExpr) return;
415   if (sentinelExpr->isValueDependent()) return;
416   if (Context.isSentinelNullExpr(sentinelExpr)) return;
417 
418   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
419   // or 'NULL' if those are actually defined in the context.  Only use
420   // 'nil' for ObjC methods, where it's much more likely that the
421   // variadic arguments form a list of object pointers.
422   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
423   std::string NullValue;
424   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
425     NullValue = "nil";
426   else if (getLangOpts().CPlusPlus11)
427     NullValue = "nullptr";
428   else if (PP.isMacroDefined("NULL"))
429     NullValue = "NULL";
430   else
431     NullValue = "(void*) 0";
432 
433   if (MissingNilLoc.isInvalid())
434     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
435   else
436     Diag(MissingNilLoc, diag::warn_missing_sentinel)
437       << int(calleeType)
438       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
439   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
440 }
441 
442 SourceRange Sema::getExprRange(Expr *E) const {
443   return E ? E->getSourceRange() : SourceRange();
444 }
445 
446 //===----------------------------------------------------------------------===//
447 //  Standard Promotions and Conversions
448 //===----------------------------------------------------------------------===//
449 
450 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
451 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
452   // Handle any placeholder expressions which made it here.
453   if (E->getType()->isPlaceholderType()) {
454     ExprResult result = CheckPlaceholderExpr(E);
455     if (result.isInvalid()) return ExprError();
456     E = result.get();
457   }
458 
459   QualType Ty = E->getType();
460   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
461 
462   if (Ty->isFunctionType()) {
463     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
464       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
465         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
466           return ExprError();
467 
468     E = ImpCastExprToType(E, Context.getPointerType(Ty),
469                           CK_FunctionToPointerDecay).get();
470   } else if (Ty->isArrayType()) {
471     // In C90 mode, arrays only promote to pointers if the array expression is
472     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
473     // type 'array of type' is converted to an expression that has type 'pointer
474     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
475     // that has type 'array of type' ...".  The relevant change is "an lvalue"
476     // (C90) to "an expression" (C99).
477     //
478     // C++ 4.2p1:
479     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
480     // T" can be converted to an rvalue of type "pointer to T".
481     //
482     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
483       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
484                             CK_ArrayToPointerDecay).get();
485   }
486   return E;
487 }
488 
489 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
490   // Check to see if we are dereferencing a null pointer.  If so,
491   // and if not volatile-qualified, this is undefined behavior that the
492   // optimizer will delete, so warn about it.  People sometimes try to use this
493   // to get a deterministic trap and are surprised by clang's behavior.  This
494   // only handles the pattern "*null", which is a very syntactic check.
495   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
496     if (UO->getOpcode() == UO_Deref &&
497         UO->getSubExpr()->IgnoreParenCasts()->
498           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
499         !UO->getType().isVolatileQualified()) {
500     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
501                           S.PDiag(diag::warn_indirection_through_null)
502                             << UO->getSubExpr()->getSourceRange());
503     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
504                         S.PDiag(diag::note_indirection_through_null));
505   }
506 }
507 
508 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
509                                     SourceLocation AssignLoc,
510                                     const Expr* RHS) {
511   const ObjCIvarDecl *IV = OIRE->getDecl();
512   if (!IV)
513     return;
514 
515   DeclarationName MemberName = IV->getDeclName();
516   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
517   if (!Member || !Member->isStr("isa"))
518     return;
519 
520   const Expr *Base = OIRE->getBase();
521   QualType BaseType = Base->getType();
522   if (OIRE->isArrow())
523     BaseType = BaseType->getPointeeType();
524   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
525     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
526       ObjCInterfaceDecl *ClassDeclared = nullptr;
527       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
528       if (!ClassDeclared->getSuperClass()
529           && (*ClassDeclared->ivar_begin()) == IV) {
530         if (RHS) {
531           NamedDecl *ObjectSetClass =
532             S.LookupSingleName(S.TUScope,
533                                &S.Context.Idents.get("object_setClass"),
534                                SourceLocation(), S.LookupOrdinaryName);
535           if (ObjectSetClass) {
536             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
537             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
538                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
539                                               "object_setClass(")
540                 << FixItHint::CreateReplacement(
541                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
542                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
543           }
544           else
545             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
546         } else {
547           NamedDecl *ObjectGetClass =
548             S.LookupSingleName(S.TUScope,
549                                &S.Context.Idents.get("object_getClass"),
550                                SourceLocation(), S.LookupOrdinaryName);
551           if (ObjectGetClass)
552             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
553                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
554                                               "object_getClass(")
555                 << FixItHint::CreateReplacement(
556                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
557           else
558             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
559         }
560         S.Diag(IV->getLocation(), diag::note_ivar_decl);
561       }
562     }
563 }
564 
565 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
566   // Handle any placeholder expressions which made it here.
567   if (E->getType()->isPlaceholderType()) {
568     ExprResult result = CheckPlaceholderExpr(E);
569     if (result.isInvalid()) return ExprError();
570     E = result.get();
571   }
572 
573   // C++ [conv.lval]p1:
574   //   A glvalue of a non-function, non-array type T can be
575   //   converted to a prvalue.
576   if (!E->isGLValue()) return E;
577 
578   QualType T = E->getType();
579   assert(!T.isNull() && "r-value conversion on typeless expression?");
580 
581   // We don't want to throw lvalue-to-rvalue casts on top of
582   // expressions of certain types in C++.
583   if (getLangOpts().CPlusPlus &&
584       (E->getType() == Context.OverloadTy ||
585        T->isDependentType() ||
586        T->isRecordType()))
587     return E;
588 
589   // The C standard is actually really unclear on this point, and
590   // DR106 tells us what the result should be but not why.  It's
591   // generally best to say that void types just doesn't undergo
592   // lvalue-to-rvalue at all.  Note that expressions of unqualified
593   // 'void' type are never l-values, but qualified void can be.
594   if (T->isVoidType())
595     return E;
596 
597   // OpenCL usually rejects direct accesses to values of 'half' type.
598   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
599       T->isHalfType()) {
600     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
601       << 0 << T;
602     return ExprError();
603   }
604 
605   CheckForNullPointerDereference(*this, E);
606   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
607     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
608                                      &Context.Idents.get("object_getClass"),
609                                      SourceLocation(), LookupOrdinaryName);
610     if (ObjectGetClass)
611       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
612           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
613           << FixItHint::CreateReplacement(
614                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
615     else
616       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
617   }
618   else if (const ObjCIvarRefExpr *OIRE =
619             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
620     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
621 
622   // C++ [conv.lval]p1:
623   //   [...] If T is a non-class type, the type of the prvalue is the
624   //   cv-unqualified version of T. Otherwise, the type of the
625   //   rvalue is T.
626   //
627   // C99 6.3.2.1p2:
628   //   If the lvalue has qualified type, the value has the unqualified
629   //   version of the type of the lvalue; otherwise, the value has the
630   //   type of the lvalue.
631   if (T.hasQualifiers())
632     T = T.getUnqualifiedType();
633 
634   // Under the MS ABI, lock down the inheritance model now.
635   if (T->isMemberPointerType() &&
636       Context.getTargetInfo().getCXXABI().isMicrosoft())
637     (void)isCompleteType(E->getExprLoc(), T);
638 
639   UpdateMarkingForLValueToRValue(E);
640 
641   // Loading a __weak object implicitly retains the value, so we need a cleanup to
642   // balance that.
643   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
644     Cleanup.setExprNeedsCleanups(true);
645 
646   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
647                                             nullptr, VK_RValue);
648 
649   // C11 6.3.2.1p2:
650   //   ... if the lvalue has atomic type, the value has the non-atomic version
651   //   of the type of the lvalue ...
652   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
653     T = Atomic->getValueType().getUnqualifiedType();
654     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
655                                    nullptr, VK_RValue);
656   }
657 
658   return Res;
659 }
660 
661 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
662   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
663   if (Res.isInvalid())
664     return ExprError();
665   Res = DefaultLvalueConversion(Res.get());
666   if (Res.isInvalid())
667     return ExprError();
668   return Res;
669 }
670 
671 /// CallExprUnaryConversions - a special case of an unary conversion
672 /// performed on a function designator of a call expression.
673 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
674   QualType Ty = E->getType();
675   ExprResult Res = E;
676   // Only do implicit cast for a function type, but not for a pointer
677   // to function type.
678   if (Ty->isFunctionType()) {
679     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
680                             CK_FunctionToPointerDecay).get();
681     if (Res.isInvalid())
682       return ExprError();
683   }
684   Res = DefaultLvalueConversion(Res.get());
685   if (Res.isInvalid())
686     return ExprError();
687   return Res.get();
688 }
689 
690 /// UsualUnaryConversions - Performs various conversions that are common to most
691 /// operators (C99 6.3). The conversions of array and function types are
692 /// sometimes suppressed. For example, the array->pointer conversion doesn't
693 /// apply if the array is an argument to the sizeof or address (&) operators.
694 /// In these instances, this routine should *not* be called.
695 ExprResult Sema::UsualUnaryConversions(Expr *E) {
696   // First, convert to an r-value.
697   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
698   if (Res.isInvalid())
699     return ExprError();
700   E = Res.get();
701 
702   QualType Ty = E->getType();
703   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
704 
705   // Half FP have to be promoted to float unless it is natively supported
706   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
707     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
708 
709   // Try to perform integral promotions if the object has a theoretically
710   // promotable type.
711   if (Ty->isIntegralOrUnscopedEnumerationType()) {
712     // C99 6.3.1.1p2:
713     //
714     //   The following may be used in an expression wherever an int or
715     //   unsigned int may be used:
716     //     - an object or expression with an integer type whose integer
717     //       conversion rank is less than or equal to the rank of int
718     //       and unsigned int.
719     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
720     //
721     //   If an int can represent all values of the original type, the
722     //   value is converted to an int; otherwise, it is converted to an
723     //   unsigned int. These are called the integer promotions. All
724     //   other types are unchanged by the integer promotions.
725 
726     QualType PTy = Context.isPromotableBitField(E);
727     if (!PTy.isNull()) {
728       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
729       return E;
730     }
731     if (Ty->isPromotableIntegerType()) {
732       QualType PT = Context.getPromotedIntegerType(Ty);
733       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
734       return E;
735     }
736   }
737   return E;
738 }
739 
740 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
741 /// do not have a prototype. Arguments that have type float or __fp16
742 /// are promoted to double. All other argument types are converted by
743 /// UsualUnaryConversions().
744 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
745   QualType Ty = E->getType();
746   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
747 
748   ExprResult Res = UsualUnaryConversions(E);
749   if (Res.isInvalid())
750     return ExprError();
751   E = Res.get();
752 
753   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
754   // promote to double.
755   // Note that default argument promotion applies only to float (and
756   // half/fp16); it does not apply to _Float16.
757   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
758   if (BTy && (BTy->getKind() == BuiltinType::Half ||
759               BTy->getKind() == BuiltinType::Float)) {
760     if (getLangOpts().OpenCL &&
761         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
762         if (BTy->getKind() == BuiltinType::Half) {
763             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
764         }
765     } else {
766       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
767     }
768   }
769 
770   // C++ performs lvalue-to-rvalue conversion as a default argument
771   // promotion, even on class types, but note:
772   //   C++11 [conv.lval]p2:
773   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
774   //     operand or a subexpression thereof the value contained in the
775   //     referenced object is not accessed. Otherwise, if the glvalue
776   //     has a class type, the conversion copy-initializes a temporary
777   //     of type T from the glvalue and the result of the conversion
778   //     is a prvalue for the temporary.
779   // FIXME: add some way to gate this entire thing for correctness in
780   // potentially potentially evaluated contexts.
781   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
782     ExprResult Temp = PerformCopyInitialization(
783                        InitializedEntity::InitializeTemporary(E->getType()),
784                                                 E->getExprLoc(), E);
785     if (Temp.isInvalid())
786       return ExprError();
787     E = Temp.get();
788   }
789 
790   return E;
791 }
792 
793 /// Determine the degree of POD-ness for an expression.
794 /// Incomplete types are considered POD, since this check can be performed
795 /// when we're in an unevaluated context.
796 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
797   if (Ty->isIncompleteType()) {
798     // C++11 [expr.call]p7:
799     //   After these conversions, if the argument does not have arithmetic,
800     //   enumeration, pointer, pointer to member, or class type, the program
801     //   is ill-formed.
802     //
803     // Since we've already performed array-to-pointer and function-to-pointer
804     // decay, the only such type in C++ is cv void. This also handles
805     // initializer lists as variadic arguments.
806     if (Ty->isVoidType())
807       return VAK_Invalid;
808 
809     if (Ty->isObjCObjectType())
810       return VAK_Invalid;
811     return VAK_Valid;
812   }
813 
814   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
815     return VAK_Invalid;
816 
817   if (Ty.isCXX98PODType(Context))
818     return VAK_Valid;
819 
820   // C++11 [expr.call]p7:
821   //   Passing a potentially-evaluated argument of class type (Clause 9)
822   //   having a non-trivial copy constructor, a non-trivial move constructor,
823   //   or a non-trivial destructor, with no corresponding parameter,
824   //   is conditionally-supported with implementation-defined semantics.
825   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
826     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
827       if (!Record->hasNonTrivialCopyConstructor() &&
828           !Record->hasNonTrivialMoveConstructor() &&
829           !Record->hasNonTrivialDestructor())
830         return VAK_ValidInCXX11;
831 
832   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
833     return VAK_Valid;
834 
835   if (Ty->isObjCObjectType())
836     return VAK_Invalid;
837 
838   if (getLangOpts().MSVCCompat)
839     return VAK_MSVCUndefined;
840 
841   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
842   // permitted to reject them. We should consider doing so.
843   return VAK_Undefined;
844 }
845 
846 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
847   // Don't allow one to pass an Objective-C interface to a vararg.
848   const QualType &Ty = E->getType();
849   VarArgKind VAK = isValidVarArgType(Ty);
850 
851   // Complain about passing non-POD types through varargs.
852   switch (VAK) {
853   case VAK_ValidInCXX11:
854     DiagRuntimeBehavior(
855         E->getBeginLoc(), nullptr,
856         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
857     LLVM_FALLTHROUGH;
858   case VAK_Valid:
859     if (Ty->isRecordType()) {
860       // This is unlikely to be what the user intended. If the class has a
861       // 'c_str' member function, the user probably meant to call that.
862       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
863                           PDiag(diag::warn_pass_class_arg_to_vararg)
864                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
865     }
866     break;
867 
868   case VAK_Undefined:
869   case VAK_MSVCUndefined:
870     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
871                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
872                             << getLangOpts().CPlusPlus11 << Ty << CT);
873     break;
874 
875   case VAK_Invalid:
876     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
877       Diag(E->getBeginLoc(),
878            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
879           << Ty << CT;
880     else if (Ty->isObjCObjectType())
881       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
882                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
883                               << Ty << CT);
884     else
885       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
886           << isa<InitListExpr>(E) << Ty << CT;
887     break;
888   }
889 }
890 
891 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
892 /// will create a trap if the resulting type is not a POD type.
893 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
894                                                   FunctionDecl *FDecl) {
895   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
896     // Strip the unbridged-cast placeholder expression off, if applicable.
897     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
898         (CT == VariadicMethod ||
899          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
900       E = stripARCUnbridgedCast(E);
901 
902     // Otherwise, do normal placeholder checking.
903     } else {
904       ExprResult ExprRes = CheckPlaceholderExpr(E);
905       if (ExprRes.isInvalid())
906         return ExprError();
907       E = ExprRes.get();
908     }
909   }
910 
911   ExprResult ExprRes = DefaultArgumentPromotion(E);
912   if (ExprRes.isInvalid())
913     return ExprError();
914   E = ExprRes.get();
915 
916   // Diagnostics regarding non-POD argument types are
917   // emitted along with format string checking in Sema::CheckFunctionCall().
918   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
919     // Turn this into a trap.
920     CXXScopeSpec SS;
921     SourceLocation TemplateKWLoc;
922     UnqualifiedId Name;
923     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
924                        E->getBeginLoc());
925     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
926                                           Name, true, false);
927     if (TrapFn.isInvalid())
928       return ExprError();
929 
930     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
931                                     None, E->getEndLoc());
932     if (Call.isInvalid())
933       return ExprError();
934 
935     ExprResult Comma =
936         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
937     if (Comma.isInvalid())
938       return ExprError();
939     return Comma.get();
940   }
941 
942   if (!getLangOpts().CPlusPlus &&
943       RequireCompleteType(E->getExprLoc(), E->getType(),
944                           diag::err_call_incomplete_argument))
945     return ExprError();
946 
947   return E;
948 }
949 
950 /// Converts an integer to complex float type.  Helper function of
951 /// UsualArithmeticConversions()
952 ///
953 /// \return false if the integer expression is an integer type and is
954 /// successfully converted to the complex type.
955 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
956                                                   ExprResult &ComplexExpr,
957                                                   QualType IntTy,
958                                                   QualType ComplexTy,
959                                                   bool SkipCast) {
960   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
961   if (SkipCast) return false;
962   if (IntTy->isIntegerType()) {
963     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
964     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
965     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
966                                   CK_FloatingRealToComplex);
967   } else {
968     assert(IntTy->isComplexIntegerType());
969     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
970                                   CK_IntegralComplexToFloatingComplex);
971   }
972   return false;
973 }
974 
975 /// Handle arithmetic conversion with complex types.  Helper function of
976 /// UsualArithmeticConversions()
977 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
978                                              ExprResult &RHS, QualType LHSType,
979                                              QualType RHSType,
980                                              bool IsCompAssign) {
981   // if we have an integer operand, the result is the complex type.
982   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
983                                              /*skipCast*/false))
984     return LHSType;
985   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
986                                              /*skipCast*/IsCompAssign))
987     return RHSType;
988 
989   // This handles complex/complex, complex/float, or float/complex.
990   // When both operands are complex, the shorter operand is converted to the
991   // type of the longer, and that is the type of the result. This corresponds
992   // to what is done when combining two real floating-point operands.
993   // The fun begins when size promotion occur across type domains.
994   // From H&S 6.3.4: When one operand is complex and the other is a real
995   // floating-point type, the less precise type is converted, within it's
996   // real or complex domain, to the precision of the other type. For example,
997   // when combining a "long double" with a "double _Complex", the
998   // "double _Complex" is promoted to "long double _Complex".
999 
1000   // Compute the rank of the two types, regardless of whether they are complex.
1001   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1002 
1003   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1004   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1005   QualType LHSElementType =
1006       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1007   QualType RHSElementType =
1008       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1009 
1010   QualType ResultType = S.Context.getComplexType(LHSElementType);
1011   if (Order < 0) {
1012     // Promote the precision of the LHS if not an assignment.
1013     ResultType = S.Context.getComplexType(RHSElementType);
1014     if (!IsCompAssign) {
1015       if (LHSComplexType)
1016         LHS =
1017             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1018       else
1019         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1020     }
1021   } else if (Order > 0) {
1022     // Promote the precision of the RHS.
1023     if (RHSComplexType)
1024       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1025     else
1026       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1027   }
1028   return ResultType;
1029 }
1030 
1031 /// Handle arithmetic conversion from integer to float.  Helper function
1032 /// of UsualArithmeticConversions()
1033 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1034                                            ExprResult &IntExpr,
1035                                            QualType FloatTy, QualType IntTy,
1036                                            bool ConvertFloat, bool ConvertInt) {
1037   if (IntTy->isIntegerType()) {
1038     if (ConvertInt)
1039       // Convert intExpr to the lhs floating point type.
1040       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1041                                     CK_IntegralToFloating);
1042     return FloatTy;
1043   }
1044 
1045   // Convert both sides to the appropriate complex float.
1046   assert(IntTy->isComplexIntegerType());
1047   QualType result = S.Context.getComplexType(FloatTy);
1048 
1049   // _Complex int -> _Complex float
1050   if (ConvertInt)
1051     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1052                                   CK_IntegralComplexToFloatingComplex);
1053 
1054   // float -> _Complex float
1055   if (ConvertFloat)
1056     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1057                                     CK_FloatingRealToComplex);
1058 
1059   return result;
1060 }
1061 
1062 /// Handle arithmethic conversion with floating point types.  Helper
1063 /// function of UsualArithmeticConversions()
1064 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1065                                       ExprResult &RHS, QualType LHSType,
1066                                       QualType RHSType, bool IsCompAssign) {
1067   bool LHSFloat = LHSType->isRealFloatingType();
1068   bool RHSFloat = RHSType->isRealFloatingType();
1069 
1070   // If we have two real floating types, convert the smaller operand
1071   // to the bigger result.
1072   if (LHSFloat && RHSFloat) {
1073     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1074     if (order > 0) {
1075       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1076       return LHSType;
1077     }
1078 
1079     assert(order < 0 && "illegal float comparison");
1080     if (!IsCompAssign)
1081       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1082     return RHSType;
1083   }
1084 
1085   if (LHSFloat) {
1086     // Half FP has to be promoted to float unless it is natively supported
1087     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1088       LHSType = S.Context.FloatTy;
1089 
1090     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1091                                       /*convertFloat=*/!IsCompAssign,
1092                                       /*convertInt=*/ true);
1093   }
1094   assert(RHSFloat);
1095   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1096                                     /*convertInt=*/ true,
1097                                     /*convertFloat=*/!IsCompAssign);
1098 }
1099 
1100 /// Diagnose attempts to convert between __float128 and long double if
1101 /// there is no support for such conversion. Helper function of
1102 /// UsualArithmeticConversions().
1103 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1104                                       QualType RHSType) {
1105   /*  No issue converting if at least one of the types is not a floating point
1106       type or the two types have the same rank.
1107   */
1108   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1109       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1110     return false;
1111 
1112   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1113          "The remaining types must be floating point types.");
1114 
1115   auto *LHSComplex = LHSType->getAs<ComplexType>();
1116   auto *RHSComplex = RHSType->getAs<ComplexType>();
1117 
1118   QualType LHSElemType = LHSComplex ?
1119     LHSComplex->getElementType() : LHSType;
1120   QualType RHSElemType = RHSComplex ?
1121     RHSComplex->getElementType() : RHSType;
1122 
1123   // No issue if the two types have the same representation
1124   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1125       &S.Context.getFloatTypeSemantics(RHSElemType))
1126     return false;
1127 
1128   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1129                                 RHSElemType == S.Context.LongDoubleTy);
1130   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1131                             RHSElemType == S.Context.Float128Ty);
1132 
1133   // We've handled the situation where __float128 and long double have the same
1134   // representation. We allow all conversions for all possible long double types
1135   // except PPC's double double.
1136   return Float128AndLongDouble &&
1137     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1138      &llvm::APFloat::PPCDoubleDouble());
1139 }
1140 
1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1142 
1143 namespace {
1144 /// These helper callbacks are placed in an anonymous namespace to
1145 /// permit their use as function template parameters.
1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1147   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1148 }
1149 
1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1151   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1152                              CK_IntegralComplexCast);
1153 }
1154 }
1155 
1156 /// Handle integer arithmetic conversions.  Helper function of
1157 /// UsualArithmeticConversions()
1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1160                                         ExprResult &RHS, QualType LHSType,
1161                                         QualType RHSType, bool IsCompAssign) {
1162   // The rules for this case are in C99 6.3.1.8
1163   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1164   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1165   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1166   if (LHSSigned == RHSSigned) {
1167     // Same signedness; use the higher-ranked type
1168     if (order >= 0) {
1169       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1170       return LHSType;
1171     } else if (!IsCompAssign)
1172       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1173     return RHSType;
1174   } else if (order != (LHSSigned ? 1 : -1)) {
1175     // The unsigned type has greater than or equal rank to the
1176     // signed type, so use the unsigned type
1177     if (RHSSigned) {
1178       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1179       return LHSType;
1180     } else if (!IsCompAssign)
1181       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1182     return RHSType;
1183   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1184     // The two types are different widths; if we are here, that
1185     // means the signed type is larger than the unsigned type, so
1186     // use the signed type.
1187     if (LHSSigned) {
1188       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1189       return LHSType;
1190     } else if (!IsCompAssign)
1191       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1192     return RHSType;
1193   } else {
1194     // The signed type is higher-ranked than the unsigned type,
1195     // but isn't actually any bigger (like unsigned int and long
1196     // on most 32-bit systems).  Use the unsigned type corresponding
1197     // to the signed type.
1198     QualType result =
1199       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1200     RHS = (*doRHSCast)(S, RHS.get(), result);
1201     if (!IsCompAssign)
1202       LHS = (*doLHSCast)(S, LHS.get(), result);
1203     return result;
1204   }
1205 }
1206 
1207 /// Handle conversions with GCC complex int extension.  Helper function
1208 /// of UsualArithmeticConversions()
1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1210                                            ExprResult &RHS, QualType LHSType,
1211                                            QualType RHSType,
1212                                            bool IsCompAssign) {
1213   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1214   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1215 
1216   if (LHSComplexInt && RHSComplexInt) {
1217     QualType LHSEltType = LHSComplexInt->getElementType();
1218     QualType RHSEltType = RHSComplexInt->getElementType();
1219     QualType ScalarType =
1220       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1221         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1222 
1223     return S.Context.getComplexType(ScalarType);
1224   }
1225 
1226   if (LHSComplexInt) {
1227     QualType LHSEltType = LHSComplexInt->getElementType();
1228     QualType ScalarType =
1229       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1230         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1231     QualType ComplexType = S.Context.getComplexType(ScalarType);
1232     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1233                               CK_IntegralRealToComplex);
1234 
1235     return ComplexType;
1236   }
1237 
1238   assert(RHSComplexInt);
1239 
1240   QualType RHSEltType = RHSComplexInt->getElementType();
1241   QualType ScalarType =
1242     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1243       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1244   QualType ComplexType = S.Context.getComplexType(ScalarType);
1245 
1246   if (!IsCompAssign)
1247     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1248                               CK_IntegralRealToComplex);
1249   return ComplexType;
1250 }
1251 
1252 /// Return the rank of a given fixed point or integer type. The value itself
1253 /// doesn't matter, but the values must be increasing with proper increasing
1254 /// rank as described in N1169 4.1.1.
1255 static unsigned GetFixedPointRank(QualType Ty) {
1256   const auto *BTy = Ty->getAs<BuiltinType>();
1257   assert(BTy && "Expected a builtin type.");
1258 
1259   switch (BTy->getKind()) {
1260   case BuiltinType::ShortFract:
1261   case BuiltinType::UShortFract:
1262   case BuiltinType::SatShortFract:
1263   case BuiltinType::SatUShortFract:
1264     return 1;
1265   case BuiltinType::Fract:
1266   case BuiltinType::UFract:
1267   case BuiltinType::SatFract:
1268   case BuiltinType::SatUFract:
1269     return 2;
1270   case BuiltinType::LongFract:
1271   case BuiltinType::ULongFract:
1272   case BuiltinType::SatLongFract:
1273   case BuiltinType::SatULongFract:
1274     return 3;
1275   case BuiltinType::ShortAccum:
1276   case BuiltinType::UShortAccum:
1277   case BuiltinType::SatShortAccum:
1278   case BuiltinType::SatUShortAccum:
1279     return 4;
1280   case BuiltinType::Accum:
1281   case BuiltinType::UAccum:
1282   case BuiltinType::SatAccum:
1283   case BuiltinType::SatUAccum:
1284     return 5;
1285   case BuiltinType::LongAccum:
1286   case BuiltinType::ULongAccum:
1287   case BuiltinType::SatLongAccum:
1288   case BuiltinType::SatULongAccum:
1289     return 6;
1290   default:
1291     if (BTy->isInteger())
1292       return 0;
1293     llvm_unreachable("Unexpected fixed point or integer type");
1294   }
1295 }
1296 
1297 /// handleFixedPointConversion - Fixed point operations between fixed
1298 /// point types and integers or other fixed point types do not fall under
1299 /// usual arithmetic conversion since these conversions could result in loss
1300 /// of precsision (N1169 4.1.4). These operations should be calculated with
1301 /// the full precision of their result type (N1169 4.1.6.2.1).
1302 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1303                                            QualType RHSTy) {
1304   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1305          "Expected at least one of the operands to be a fixed point type");
1306   assert((LHSTy->isFixedPointOrIntegerType() ||
1307           RHSTy->isFixedPointOrIntegerType()) &&
1308          "Special fixed point arithmetic operation conversions are only "
1309          "applied to ints or other fixed point types");
1310 
1311   // If one operand has signed fixed-point type and the other operand has
1312   // unsigned fixed-point type, then the unsigned fixed-point operand is
1313   // converted to its corresponding signed fixed-point type and the resulting
1314   // type is the type of the converted operand.
1315   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1316     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1317   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1318     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1319 
1320   // The result type is the type with the highest rank, whereby a fixed-point
1321   // conversion rank is always greater than an integer conversion rank; if the
1322   // type of either of the operands is a saturating fixedpoint type, the result
1323   // type shall be the saturating fixed-point type corresponding to the type
1324   // with the highest rank; the resulting value is converted (taking into
1325   // account rounding and overflow) to the precision of the resulting type.
1326   // Same ranks between signed and unsigned types are resolved earlier, so both
1327   // types are either signed or both unsigned at this point.
1328   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1329   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1330 
1331   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1332 
1333   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1334     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1335 
1336   return ResultTy;
1337 }
1338 
1339 /// UsualArithmeticConversions - Performs various conversions that are common to
1340 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1341 /// routine returns the first non-arithmetic type found. The client is
1342 /// responsible for emitting appropriate error diagnostics.
1343 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1344                                           bool IsCompAssign) {
1345   if (!IsCompAssign) {
1346     LHS = UsualUnaryConversions(LHS.get());
1347     if (LHS.isInvalid())
1348       return QualType();
1349   }
1350 
1351   RHS = UsualUnaryConversions(RHS.get());
1352   if (RHS.isInvalid())
1353     return QualType();
1354 
1355   // For conversion purposes, we ignore any qualifiers.
1356   // For example, "const float" and "float" are equivalent.
1357   QualType LHSType =
1358     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1359   QualType RHSType =
1360     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1361 
1362   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1363   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1364     LHSType = AtomicLHS->getValueType();
1365 
1366   // If both types are identical, no conversion is needed.
1367   if (LHSType == RHSType)
1368     return LHSType;
1369 
1370   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1371   // The caller can deal with this (e.g. pointer + int).
1372   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1373     return QualType();
1374 
1375   // Apply unary and bitfield promotions to the LHS's type.
1376   QualType LHSUnpromotedType = LHSType;
1377   if (LHSType->isPromotableIntegerType())
1378     LHSType = Context.getPromotedIntegerType(LHSType);
1379   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1380   if (!LHSBitfieldPromoteTy.isNull())
1381     LHSType = LHSBitfieldPromoteTy;
1382   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1383     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1384 
1385   // If both types are identical, no conversion is needed.
1386   if (LHSType == RHSType)
1387     return LHSType;
1388 
1389   // At this point, we have two different arithmetic types.
1390 
1391   // Diagnose attempts to convert between __float128 and long double where
1392   // such conversions currently can't be handled.
1393   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1394     return QualType();
1395 
1396   // Handle complex types first (C99 6.3.1.8p1).
1397   if (LHSType->isComplexType() || RHSType->isComplexType())
1398     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1399                                         IsCompAssign);
1400 
1401   // Now handle "real" floating types (i.e. float, double, long double).
1402   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1403     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1404                                  IsCompAssign);
1405 
1406   // Handle GCC complex int extension.
1407   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1408     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1409                                       IsCompAssign);
1410 
1411   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1412     return handleFixedPointConversion(*this, LHSType, RHSType);
1413 
1414   // Finally, we have two differing integer types.
1415   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1416            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1417 }
1418 
1419 //===----------------------------------------------------------------------===//
1420 //  Semantic Analysis for various Expression Types
1421 //===----------------------------------------------------------------------===//
1422 
1423 
1424 ExprResult
1425 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1426                                 SourceLocation DefaultLoc,
1427                                 SourceLocation RParenLoc,
1428                                 Expr *ControllingExpr,
1429                                 ArrayRef<ParsedType> ArgTypes,
1430                                 ArrayRef<Expr *> ArgExprs) {
1431   unsigned NumAssocs = ArgTypes.size();
1432   assert(NumAssocs == ArgExprs.size());
1433 
1434   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1435   for (unsigned i = 0; i < NumAssocs; ++i) {
1436     if (ArgTypes[i])
1437       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1438     else
1439       Types[i] = nullptr;
1440   }
1441 
1442   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1443                                              ControllingExpr,
1444                                              llvm::makeArrayRef(Types, NumAssocs),
1445                                              ArgExprs);
1446   delete [] Types;
1447   return ER;
1448 }
1449 
1450 ExprResult
1451 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1452                                  SourceLocation DefaultLoc,
1453                                  SourceLocation RParenLoc,
1454                                  Expr *ControllingExpr,
1455                                  ArrayRef<TypeSourceInfo *> Types,
1456                                  ArrayRef<Expr *> Exprs) {
1457   unsigned NumAssocs = Types.size();
1458   assert(NumAssocs == Exprs.size());
1459 
1460   // Decay and strip qualifiers for the controlling expression type, and handle
1461   // placeholder type replacement. See committee discussion from WG14 DR423.
1462   {
1463     EnterExpressionEvaluationContext Unevaluated(
1464         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1465     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1466     if (R.isInvalid())
1467       return ExprError();
1468     ControllingExpr = R.get();
1469   }
1470 
1471   // The controlling expression is an unevaluated operand, so side effects are
1472   // likely unintended.
1473   if (!inTemplateInstantiation() &&
1474       ControllingExpr->HasSideEffects(Context, false))
1475     Diag(ControllingExpr->getExprLoc(),
1476          diag::warn_side_effects_unevaluated_context);
1477 
1478   bool TypeErrorFound = false,
1479        IsResultDependent = ControllingExpr->isTypeDependent(),
1480        ContainsUnexpandedParameterPack
1481          = ControllingExpr->containsUnexpandedParameterPack();
1482 
1483   for (unsigned i = 0; i < NumAssocs; ++i) {
1484     if (Exprs[i]->containsUnexpandedParameterPack())
1485       ContainsUnexpandedParameterPack = true;
1486 
1487     if (Types[i]) {
1488       if (Types[i]->getType()->containsUnexpandedParameterPack())
1489         ContainsUnexpandedParameterPack = true;
1490 
1491       if (Types[i]->getType()->isDependentType()) {
1492         IsResultDependent = true;
1493       } else {
1494         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1495         // complete object type other than a variably modified type."
1496         unsigned D = 0;
1497         if (Types[i]->getType()->isIncompleteType())
1498           D = diag::err_assoc_type_incomplete;
1499         else if (!Types[i]->getType()->isObjectType())
1500           D = diag::err_assoc_type_nonobject;
1501         else if (Types[i]->getType()->isVariablyModifiedType())
1502           D = diag::err_assoc_type_variably_modified;
1503 
1504         if (D != 0) {
1505           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1506             << Types[i]->getTypeLoc().getSourceRange()
1507             << Types[i]->getType();
1508           TypeErrorFound = true;
1509         }
1510 
1511         // C11 6.5.1.1p2 "No two generic associations in the same generic
1512         // selection shall specify compatible types."
1513         for (unsigned j = i+1; j < NumAssocs; ++j)
1514           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1515               Context.typesAreCompatible(Types[i]->getType(),
1516                                          Types[j]->getType())) {
1517             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1518                  diag::err_assoc_compatible_types)
1519               << Types[j]->getTypeLoc().getSourceRange()
1520               << Types[j]->getType()
1521               << Types[i]->getType();
1522             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1523                  diag::note_compat_assoc)
1524               << Types[i]->getTypeLoc().getSourceRange()
1525               << Types[i]->getType();
1526             TypeErrorFound = true;
1527           }
1528       }
1529     }
1530   }
1531   if (TypeErrorFound)
1532     return ExprError();
1533 
1534   // If we determined that the generic selection is result-dependent, don't
1535   // try to compute the result expression.
1536   if (IsResultDependent)
1537     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1538                                         Exprs, DefaultLoc, RParenLoc,
1539                                         ContainsUnexpandedParameterPack);
1540 
1541   SmallVector<unsigned, 1> CompatIndices;
1542   unsigned DefaultIndex = -1U;
1543   for (unsigned i = 0; i < NumAssocs; ++i) {
1544     if (!Types[i])
1545       DefaultIndex = i;
1546     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1547                                         Types[i]->getType()))
1548       CompatIndices.push_back(i);
1549   }
1550 
1551   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1552   // type compatible with at most one of the types named in its generic
1553   // association list."
1554   if (CompatIndices.size() > 1) {
1555     // We strip parens here because the controlling expression is typically
1556     // parenthesized in macro definitions.
1557     ControllingExpr = ControllingExpr->IgnoreParens();
1558     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1559         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1560         << (unsigned)CompatIndices.size();
1561     for (unsigned I : CompatIndices) {
1562       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1563            diag::note_compat_assoc)
1564         << Types[I]->getTypeLoc().getSourceRange()
1565         << Types[I]->getType();
1566     }
1567     return ExprError();
1568   }
1569 
1570   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1571   // its controlling expression shall have type compatible with exactly one of
1572   // the types named in its generic association list."
1573   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1574     // We strip parens here because the controlling expression is typically
1575     // parenthesized in macro definitions.
1576     ControllingExpr = ControllingExpr->IgnoreParens();
1577     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1578         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1579     return ExprError();
1580   }
1581 
1582   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1583   // type name that is compatible with the type of the controlling expression,
1584   // then the result expression of the generic selection is the expression
1585   // in that generic association. Otherwise, the result expression of the
1586   // generic selection is the expression in the default generic association."
1587   unsigned ResultIndex =
1588     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1589 
1590   return GenericSelectionExpr::Create(
1591       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1592       ContainsUnexpandedParameterPack, ResultIndex);
1593 }
1594 
1595 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1596 /// location of the token and the offset of the ud-suffix within it.
1597 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1598                                      unsigned Offset) {
1599   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1600                                         S.getLangOpts());
1601 }
1602 
1603 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1604 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1605 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1606                                                  IdentifierInfo *UDSuffix,
1607                                                  SourceLocation UDSuffixLoc,
1608                                                  ArrayRef<Expr*> Args,
1609                                                  SourceLocation LitEndLoc) {
1610   assert(Args.size() <= 2 && "too many arguments for literal operator");
1611 
1612   QualType ArgTy[2];
1613   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1614     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1615     if (ArgTy[ArgIdx]->isArrayType())
1616       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1617   }
1618 
1619   DeclarationName OpName =
1620     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1621   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1622   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1623 
1624   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1625   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1626                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1627                               /*AllowStringTemplate*/ false,
1628                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1629     return ExprError();
1630 
1631   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1632 }
1633 
1634 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1635 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1636 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1637 /// multiple tokens.  However, the common case is that StringToks points to one
1638 /// string.
1639 ///
1640 ExprResult
1641 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1642   assert(!StringToks.empty() && "Must have at least one string!");
1643 
1644   StringLiteralParser Literal(StringToks, PP);
1645   if (Literal.hadError)
1646     return ExprError();
1647 
1648   SmallVector<SourceLocation, 4> StringTokLocs;
1649   for (const Token &Tok : StringToks)
1650     StringTokLocs.push_back(Tok.getLocation());
1651 
1652   QualType CharTy = Context.CharTy;
1653   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1654   if (Literal.isWide()) {
1655     CharTy = Context.getWideCharType();
1656     Kind = StringLiteral::Wide;
1657   } else if (Literal.isUTF8()) {
1658     if (getLangOpts().Char8)
1659       CharTy = Context.Char8Ty;
1660     Kind = StringLiteral::UTF8;
1661   } else if (Literal.isUTF16()) {
1662     CharTy = Context.Char16Ty;
1663     Kind = StringLiteral::UTF16;
1664   } else if (Literal.isUTF32()) {
1665     CharTy = Context.Char32Ty;
1666     Kind = StringLiteral::UTF32;
1667   } else if (Literal.isPascal()) {
1668     CharTy = Context.UnsignedCharTy;
1669   }
1670 
1671   // Warn on initializing an array of char from a u8 string literal; this
1672   // becomes ill-formed in C++2a.
1673   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1674       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1675     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1676 
1677     // Create removals for all 'u8' prefixes in the string literal(s). This
1678     // ensures C++2a compatibility (but may change the program behavior when
1679     // built by non-Clang compilers for which the execution character set is
1680     // not always UTF-8).
1681     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1682     SourceLocation RemovalDiagLoc;
1683     for (const Token &Tok : StringToks) {
1684       if (Tok.getKind() == tok::utf8_string_literal) {
1685         if (RemovalDiagLoc.isInvalid())
1686           RemovalDiagLoc = Tok.getLocation();
1687         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1688             Tok.getLocation(),
1689             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1690                                            getSourceManager(), getLangOpts())));
1691       }
1692     }
1693     Diag(RemovalDiagLoc, RemovalDiag);
1694   }
1695 
1696 
1697   QualType CharTyConst = CharTy;
1698   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1699   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1700     CharTyConst.addConst();
1701 
1702   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1703 
1704   // Get an array type for the string, according to C99 6.4.5.  This includes
1705   // the nul terminator character as well as the string length for pascal
1706   // strings.
1707   QualType StrTy = Context.getConstantArrayType(
1708       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1709       ArrayType::Normal, 0);
1710 
1711   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1712   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1713                                              Kind, Literal.Pascal, StrTy,
1714                                              &StringTokLocs[0],
1715                                              StringTokLocs.size());
1716   if (Literal.getUDSuffix().empty())
1717     return Lit;
1718 
1719   // We're building a user-defined literal.
1720   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1721   SourceLocation UDSuffixLoc =
1722     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1723                    Literal.getUDSuffixOffset());
1724 
1725   // Make sure we're allowed user-defined literals here.
1726   if (!UDLScope)
1727     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1728 
1729   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1730   //   operator "" X (str, len)
1731   QualType SizeType = Context.getSizeType();
1732 
1733   DeclarationName OpName =
1734     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1735   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1736   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1737 
1738   QualType ArgTy[] = {
1739     Context.getArrayDecayedType(StrTy), SizeType
1740   };
1741 
1742   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1743   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1744                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1745                                 /*AllowStringTemplate*/ true,
1746                                 /*DiagnoseMissing*/ true)) {
1747 
1748   case LOLR_Cooked: {
1749     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1750     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1751                                                     StringTokLocs[0]);
1752     Expr *Args[] = { Lit, LenArg };
1753 
1754     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1755   }
1756 
1757   case LOLR_StringTemplate: {
1758     TemplateArgumentListInfo ExplicitArgs;
1759 
1760     unsigned CharBits = Context.getIntWidth(CharTy);
1761     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1762     llvm::APSInt Value(CharBits, CharIsUnsigned);
1763 
1764     TemplateArgument TypeArg(CharTy);
1765     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1766     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1767 
1768     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1769       Value = Lit->getCodeUnit(I);
1770       TemplateArgument Arg(Context, Value, CharTy);
1771       TemplateArgumentLocInfo ArgInfo;
1772       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1773     }
1774     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1775                                     &ExplicitArgs);
1776   }
1777   case LOLR_Raw:
1778   case LOLR_Template:
1779   case LOLR_ErrorNoDiagnostic:
1780     llvm_unreachable("unexpected literal operator lookup result");
1781   case LOLR_Error:
1782     return ExprError();
1783   }
1784   llvm_unreachable("unexpected literal operator lookup result");
1785 }
1786 
1787 ExprResult
1788 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1789                        SourceLocation Loc,
1790                        const CXXScopeSpec *SS) {
1791   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1792   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1793 }
1794 
1795 /// BuildDeclRefExpr - Build an expression that references a
1796 /// declaration that does not require a closure capture.
1797 ExprResult
1798 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1799                        const DeclarationNameInfo &NameInfo,
1800                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1801                        const TemplateArgumentListInfo *TemplateArgs) {
1802   bool RefersToCapturedVariable =
1803       isa<VarDecl>(D) &&
1804       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1805 
1806   DeclRefExpr *E;
1807   if (isa<VarTemplateSpecializationDecl>(D)) {
1808     VarTemplateSpecializationDecl *VarSpec =
1809         cast<VarTemplateSpecializationDecl>(D);
1810 
1811     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1812                                         : NestedNameSpecifierLoc(),
1813                             VarSpec->getTemplateKeywordLoc(), D,
1814                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1815                             FoundD, TemplateArgs);
1816   } else {
1817     assert(!TemplateArgs && "No template arguments for non-variable"
1818                             " template specialization references");
1819     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1820                                         : NestedNameSpecifierLoc(),
1821                             SourceLocation(), D, RefersToCapturedVariable,
1822                             NameInfo, Ty, VK, FoundD);
1823   }
1824 
1825   MarkDeclRefReferenced(E);
1826 
1827   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1828       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1829       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1830     getCurFunction()->recordUseOfWeak(E);
1831 
1832   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1833   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1834     FD = IFD->getAnonField();
1835   if (FD) {
1836     UnusedPrivateFields.remove(FD);
1837     // Just in case we're building an illegal pointer-to-member.
1838     if (FD->isBitField())
1839       E->setObjectKind(OK_BitField);
1840   }
1841 
1842   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1843   // designates a bit-field.
1844   if (auto *BD = dyn_cast<BindingDecl>(D))
1845     if (auto *BE = BD->getBinding())
1846       E->setObjectKind(BE->getObjectKind());
1847 
1848   return E;
1849 }
1850 
1851 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1852 /// possibly a list of template arguments.
1853 ///
1854 /// If this produces template arguments, it is permitted to call
1855 /// DecomposeTemplateName.
1856 ///
1857 /// This actually loses a lot of source location information for
1858 /// non-standard name kinds; we should consider preserving that in
1859 /// some way.
1860 void
1861 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1862                              TemplateArgumentListInfo &Buffer,
1863                              DeclarationNameInfo &NameInfo,
1864                              const TemplateArgumentListInfo *&TemplateArgs) {
1865   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1866     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1867     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1868 
1869     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1870                                        Id.TemplateId->NumArgs);
1871     translateTemplateArguments(TemplateArgsPtr, Buffer);
1872 
1873     TemplateName TName = Id.TemplateId->Template.get();
1874     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1875     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1876     TemplateArgs = &Buffer;
1877   } else {
1878     NameInfo = GetNameFromUnqualifiedId(Id);
1879     TemplateArgs = nullptr;
1880   }
1881 }
1882 
1883 static void emitEmptyLookupTypoDiagnostic(
1884     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1885     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1886     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1887   DeclContext *Ctx =
1888       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1889   if (!TC) {
1890     // Emit a special diagnostic for failed member lookups.
1891     // FIXME: computing the declaration context might fail here (?)
1892     if (Ctx)
1893       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1894                                                  << SS.getRange();
1895     else
1896       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1897     return;
1898   }
1899 
1900   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1901   bool DroppedSpecifier =
1902       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1903   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1904                         ? diag::note_implicit_param_decl
1905                         : diag::note_previous_decl;
1906   if (!Ctx)
1907     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1908                          SemaRef.PDiag(NoteID));
1909   else
1910     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1911                                  << Typo << Ctx << DroppedSpecifier
1912                                  << SS.getRange(),
1913                          SemaRef.PDiag(NoteID));
1914 }
1915 
1916 /// Diagnose an empty lookup.
1917 ///
1918 /// \return false if new lookup candidates were found
1919 bool
1920 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1921                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1922                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1923                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1924   DeclarationName Name = R.getLookupName();
1925 
1926   unsigned diagnostic = diag::err_undeclared_var_use;
1927   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1928   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1929       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1930       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1931     diagnostic = diag::err_undeclared_use;
1932     diagnostic_suggest = diag::err_undeclared_use_suggest;
1933   }
1934 
1935   // If the original lookup was an unqualified lookup, fake an
1936   // unqualified lookup.  This is useful when (for example) the
1937   // original lookup would not have found something because it was a
1938   // dependent name.
1939   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1940   while (DC) {
1941     if (isa<CXXRecordDecl>(DC)) {
1942       LookupQualifiedName(R, DC);
1943 
1944       if (!R.empty()) {
1945         // Don't give errors about ambiguities in this lookup.
1946         R.suppressDiagnostics();
1947 
1948         // During a default argument instantiation the CurContext points
1949         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1950         // function parameter list, hence add an explicit check.
1951         bool isDefaultArgument =
1952             !CodeSynthesisContexts.empty() &&
1953             CodeSynthesisContexts.back().Kind ==
1954                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1955         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1956         bool isInstance = CurMethod &&
1957                           CurMethod->isInstance() &&
1958                           DC == CurMethod->getParent() && !isDefaultArgument;
1959 
1960         // Give a code modification hint to insert 'this->'.
1961         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1962         // Actually quite difficult!
1963         if (getLangOpts().MSVCCompat)
1964           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1965         if (isInstance) {
1966           Diag(R.getNameLoc(), diagnostic) << Name
1967             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1968           CheckCXXThisCapture(R.getNameLoc());
1969         } else {
1970           Diag(R.getNameLoc(), diagnostic) << Name;
1971         }
1972 
1973         // Do we really want to note all of these?
1974         for (NamedDecl *D : R)
1975           Diag(D->getLocation(), diag::note_dependent_var_use);
1976 
1977         // Return true if we are inside a default argument instantiation
1978         // and the found name refers to an instance member function, otherwise
1979         // the function calling DiagnoseEmptyLookup will try to create an
1980         // implicit member call and this is wrong for default argument.
1981         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1982           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1983           return true;
1984         }
1985 
1986         // Tell the callee to try to recover.
1987         return false;
1988       }
1989 
1990       R.clear();
1991     }
1992 
1993     // In Microsoft mode, if we are performing lookup from within a friend
1994     // function definition declared at class scope then we must set
1995     // DC to the lexical parent to be able to search into the parent
1996     // class.
1997     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1998         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1999         DC->getLexicalParent()->isRecord())
2000       DC = DC->getLexicalParent();
2001     else
2002       DC = DC->getParent();
2003   }
2004 
2005   // We didn't find anything, so try to correct for a typo.
2006   TypoCorrection Corrected;
2007   if (S && Out) {
2008     SourceLocation TypoLoc = R.getNameLoc();
2009     assert(!ExplicitTemplateArgs &&
2010            "Diagnosing an empty lookup with explicit template args!");
2011     *Out = CorrectTypoDelayed(
2012         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
2013         [=](const TypoCorrection &TC) {
2014           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2015                                         diagnostic, diagnostic_suggest);
2016         },
2017         nullptr, CTK_ErrorRecovery);
2018     if (*Out)
2019       return true;
2020   } else if (S && (Corrected =
2021                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
2022                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
2023     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2024     bool DroppedSpecifier =
2025         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2026     R.setLookupName(Corrected.getCorrection());
2027 
2028     bool AcceptableWithRecovery = false;
2029     bool AcceptableWithoutRecovery = false;
2030     NamedDecl *ND = Corrected.getFoundDecl();
2031     if (ND) {
2032       if (Corrected.isOverloaded()) {
2033         OverloadCandidateSet OCS(R.getNameLoc(),
2034                                  OverloadCandidateSet::CSK_Normal);
2035         OverloadCandidateSet::iterator Best;
2036         for (NamedDecl *CD : Corrected) {
2037           if (FunctionTemplateDecl *FTD =
2038                    dyn_cast<FunctionTemplateDecl>(CD))
2039             AddTemplateOverloadCandidate(
2040                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2041                 Args, OCS);
2042           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2043             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2044               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2045                                    Args, OCS);
2046         }
2047         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2048         case OR_Success:
2049           ND = Best->FoundDecl;
2050           Corrected.setCorrectionDecl(ND);
2051           break;
2052         default:
2053           // FIXME: Arbitrarily pick the first declaration for the note.
2054           Corrected.setCorrectionDecl(ND);
2055           break;
2056         }
2057       }
2058       R.addDecl(ND);
2059       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2060         CXXRecordDecl *Record = nullptr;
2061         if (Corrected.getCorrectionSpecifier()) {
2062           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2063           Record = Ty->getAsCXXRecordDecl();
2064         }
2065         if (!Record)
2066           Record = cast<CXXRecordDecl>(
2067               ND->getDeclContext()->getRedeclContext());
2068         R.setNamingClass(Record);
2069       }
2070 
2071       auto *UnderlyingND = ND->getUnderlyingDecl();
2072       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2073                                isa<FunctionTemplateDecl>(UnderlyingND);
2074       // FIXME: If we ended up with a typo for a type name or
2075       // Objective-C class name, we're in trouble because the parser
2076       // is in the wrong place to recover. Suggest the typo
2077       // correction, but don't make it a fix-it since we're not going
2078       // to recover well anyway.
2079       AcceptableWithoutRecovery =
2080           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2081     } else {
2082       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2083       // because we aren't able to recover.
2084       AcceptableWithoutRecovery = true;
2085     }
2086 
2087     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2088       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2089                             ? diag::note_implicit_param_decl
2090                             : diag::note_previous_decl;
2091       if (SS.isEmpty())
2092         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2093                      PDiag(NoteID), AcceptableWithRecovery);
2094       else
2095         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2096                                   << Name << computeDeclContext(SS, false)
2097                                   << DroppedSpecifier << SS.getRange(),
2098                      PDiag(NoteID), AcceptableWithRecovery);
2099 
2100       // Tell the callee whether to try to recover.
2101       return !AcceptableWithRecovery;
2102     }
2103   }
2104   R.clear();
2105 
2106   // Emit a special diagnostic for failed member lookups.
2107   // FIXME: computing the declaration context might fail here (?)
2108   if (!SS.isEmpty()) {
2109     Diag(R.getNameLoc(), diag::err_no_member)
2110       << Name << computeDeclContext(SS, false)
2111       << SS.getRange();
2112     return true;
2113   }
2114 
2115   // Give up, we can't recover.
2116   Diag(R.getNameLoc(), diagnostic) << Name;
2117   return true;
2118 }
2119 
2120 /// In Microsoft mode, if we are inside a template class whose parent class has
2121 /// dependent base classes, and we can't resolve an unqualified identifier, then
2122 /// assume the identifier is a member of a dependent base class.  We can only
2123 /// recover successfully in static methods, instance methods, and other contexts
2124 /// where 'this' is available.  This doesn't precisely match MSVC's
2125 /// instantiation model, but it's close enough.
2126 static Expr *
2127 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2128                                DeclarationNameInfo &NameInfo,
2129                                SourceLocation TemplateKWLoc,
2130                                const TemplateArgumentListInfo *TemplateArgs) {
2131   // Only try to recover from lookup into dependent bases in static methods or
2132   // contexts where 'this' is available.
2133   QualType ThisType = S.getCurrentThisType();
2134   const CXXRecordDecl *RD = nullptr;
2135   if (!ThisType.isNull())
2136     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2137   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2138     RD = MD->getParent();
2139   if (!RD || !RD->hasAnyDependentBases())
2140     return nullptr;
2141 
2142   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2143   // is available, suggest inserting 'this->' as a fixit.
2144   SourceLocation Loc = NameInfo.getLoc();
2145   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2146   DB << NameInfo.getName() << RD;
2147 
2148   if (!ThisType.isNull()) {
2149     DB << FixItHint::CreateInsertion(Loc, "this->");
2150     return CXXDependentScopeMemberExpr::Create(
2151         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2152         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2153         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2154   }
2155 
2156   // Synthesize a fake NNS that points to the derived class.  This will
2157   // perform name lookup during template instantiation.
2158   CXXScopeSpec SS;
2159   auto *NNS =
2160       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2161   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2162   return DependentScopeDeclRefExpr::Create(
2163       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2164       TemplateArgs);
2165 }
2166 
2167 ExprResult
2168 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2169                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2170                         bool HasTrailingLParen, bool IsAddressOfOperand,
2171                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2172                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2173   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2174          "cannot be direct & operand and have a trailing lparen");
2175   if (SS.isInvalid())
2176     return ExprError();
2177 
2178   TemplateArgumentListInfo TemplateArgsBuffer;
2179 
2180   // Decompose the UnqualifiedId into the following data.
2181   DeclarationNameInfo NameInfo;
2182   const TemplateArgumentListInfo *TemplateArgs;
2183   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2184 
2185   DeclarationName Name = NameInfo.getName();
2186   IdentifierInfo *II = Name.getAsIdentifierInfo();
2187   SourceLocation NameLoc = NameInfo.getLoc();
2188 
2189   if (II && II->isEditorPlaceholder()) {
2190     // FIXME: When typed placeholders are supported we can create a typed
2191     // placeholder expression node.
2192     return ExprError();
2193   }
2194 
2195   // C++ [temp.dep.expr]p3:
2196   //   An id-expression is type-dependent if it contains:
2197   //     -- an identifier that was declared with a dependent type,
2198   //        (note: handled after lookup)
2199   //     -- a template-id that is dependent,
2200   //        (note: handled in BuildTemplateIdExpr)
2201   //     -- a conversion-function-id that specifies a dependent type,
2202   //     -- a nested-name-specifier that contains a class-name that
2203   //        names a dependent type.
2204   // Determine whether this is a member of an unknown specialization;
2205   // we need to handle these differently.
2206   bool DependentID = false;
2207   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2208       Name.getCXXNameType()->isDependentType()) {
2209     DependentID = true;
2210   } else if (SS.isSet()) {
2211     if (DeclContext *DC = computeDeclContext(SS, false)) {
2212       if (RequireCompleteDeclContext(SS, DC))
2213         return ExprError();
2214     } else {
2215       DependentID = true;
2216     }
2217   }
2218 
2219   if (DependentID)
2220     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2221                                       IsAddressOfOperand, TemplateArgs);
2222 
2223   // Perform the required lookup.
2224   LookupResult R(*this, NameInfo,
2225                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2226                      ? LookupObjCImplicitSelfParam
2227                      : LookupOrdinaryName);
2228   if (TemplateKWLoc.isValid() || TemplateArgs) {
2229     // Lookup the template name again to correctly establish the context in
2230     // which it was found. This is really unfortunate as we already did the
2231     // lookup to determine that it was a template name in the first place. If
2232     // this becomes a performance hit, we can work harder to preserve those
2233     // results until we get here but it's likely not worth it.
2234     bool MemberOfUnknownSpecialization;
2235     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2236                            MemberOfUnknownSpecialization, TemplateKWLoc))
2237       return ExprError();
2238 
2239     if (MemberOfUnknownSpecialization ||
2240         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2241       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2242                                         IsAddressOfOperand, TemplateArgs);
2243   } else {
2244     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2245     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2246 
2247     // If the result might be in a dependent base class, this is a dependent
2248     // id-expression.
2249     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2250       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2251                                         IsAddressOfOperand, TemplateArgs);
2252 
2253     // If this reference is in an Objective-C method, then we need to do
2254     // some special Objective-C lookup, too.
2255     if (IvarLookupFollowUp) {
2256       ExprResult E(LookupInObjCMethod(R, S, II, true));
2257       if (E.isInvalid())
2258         return ExprError();
2259 
2260       if (Expr *Ex = E.getAs<Expr>())
2261         return Ex;
2262     }
2263   }
2264 
2265   if (R.isAmbiguous())
2266     return ExprError();
2267 
2268   // This could be an implicitly declared function reference (legal in C90,
2269   // extension in C99, forbidden in C++).
2270   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2271     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2272     if (D) R.addDecl(D);
2273   }
2274 
2275   // Determine whether this name might be a candidate for
2276   // argument-dependent lookup.
2277   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2278 
2279   if (R.empty() && !ADL) {
2280     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2281       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2282                                                    TemplateKWLoc, TemplateArgs))
2283         return E;
2284     }
2285 
2286     // Don't diagnose an empty lookup for inline assembly.
2287     if (IsInlineAsmIdentifier)
2288       return ExprError();
2289 
2290     // If this name wasn't predeclared and if this is not a function
2291     // call, diagnose the problem.
2292     TypoExpr *TE = nullptr;
2293     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2294         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2295     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2296     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2297            "Typo correction callback misconfigured");
2298     if (CCC) {
2299       // Make sure the callback knows what the typo being diagnosed is.
2300       CCC->setTypoName(II);
2301       if (SS.isValid())
2302         CCC->setTypoNNS(SS.getScopeRep());
2303     }
2304     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2305     // a template name, but we happen to have always already looked up the name
2306     // before we get here if it must be a template name.
2307     if (DiagnoseEmptyLookup(S, SS, R,
2308                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2309                             nullptr, None, &TE)) {
2310       if (TE && KeywordReplacement) {
2311         auto &State = getTypoExprState(TE);
2312         auto BestTC = State.Consumer->getNextCorrection();
2313         if (BestTC.isKeyword()) {
2314           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2315           if (State.DiagHandler)
2316             State.DiagHandler(BestTC);
2317           KeywordReplacement->startToken();
2318           KeywordReplacement->setKind(II->getTokenID());
2319           KeywordReplacement->setIdentifierInfo(II);
2320           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2321           // Clean up the state associated with the TypoExpr, since it has
2322           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2323           clearDelayedTypo(TE);
2324           // Signal that a correction to a keyword was performed by returning a
2325           // valid-but-null ExprResult.
2326           return (Expr*)nullptr;
2327         }
2328         State.Consumer->resetCorrectionStream();
2329       }
2330       return TE ? TE : ExprError();
2331     }
2332 
2333     assert(!R.empty() &&
2334            "DiagnoseEmptyLookup returned false but added no results");
2335 
2336     // If we found an Objective-C instance variable, let
2337     // LookupInObjCMethod build the appropriate expression to
2338     // reference the ivar.
2339     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2340       R.clear();
2341       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2342       // In a hopelessly buggy code, Objective-C instance variable
2343       // lookup fails and no expression will be built to reference it.
2344       if (!E.isInvalid() && !E.get())
2345         return ExprError();
2346       return E;
2347     }
2348   }
2349 
2350   // This is guaranteed from this point on.
2351   assert(!R.empty() || ADL);
2352 
2353   // Check whether this might be a C++ implicit instance member access.
2354   // C++ [class.mfct.non-static]p3:
2355   //   When an id-expression that is not part of a class member access
2356   //   syntax and not used to form a pointer to member is used in the
2357   //   body of a non-static member function of class X, if name lookup
2358   //   resolves the name in the id-expression to a non-static non-type
2359   //   member of some class C, the id-expression is transformed into a
2360   //   class member access expression using (*this) as the
2361   //   postfix-expression to the left of the . operator.
2362   //
2363   // But we don't actually need to do this for '&' operands if R
2364   // resolved to a function or overloaded function set, because the
2365   // expression is ill-formed if it actually works out to be a
2366   // non-static member function:
2367   //
2368   // C++ [expr.ref]p4:
2369   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2370   //   [t]he expression can be used only as the left-hand operand of a
2371   //   member function call.
2372   //
2373   // There are other safeguards against such uses, but it's important
2374   // to get this right here so that we don't end up making a
2375   // spuriously dependent expression if we're inside a dependent
2376   // instance method.
2377   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2378     bool MightBeImplicitMember;
2379     if (!IsAddressOfOperand)
2380       MightBeImplicitMember = true;
2381     else if (!SS.isEmpty())
2382       MightBeImplicitMember = false;
2383     else if (R.isOverloadedResult())
2384       MightBeImplicitMember = false;
2385     else if (R.isUnresolvableResult())
2386       MightBeImplicitMember = true;
2387     else
2388       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2389                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2390                               isa<MSPropertyDecl>(R.getFoundDecl());
2391 
2392     if (MightBeImplicitMember)
2393       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2394                                              R, TemplateArgs, S);
2395   }
2396 
2397   if (TemplateArgs || TemplateKWLoc.isValid()) {
2398 
2399     // In C++1y, if this is a variable template id, then check it
2400     // in BuildTemplateIdExpr().
2401     // The single lookup result must be a variable template declaration.
2402     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2403         Id.TemplateId->Kind == TNK_Var_template) {
2404       assert(R.getAsSingle<VarTemplateDecl>() &&
2405              "There should only be one declaration found.");
2406     }
2407 
2408     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2409   }
2410 
2411   return BuildDeclarationNameExpr(SS, R, ADL);
2412 }
2413 
2414 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2415 /// declaration name, generally during template instantiation.
2416 /// There's a large number of things which don't need to be done along
2417 /// this path.
2418 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2419     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2420     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2421   DeclContext *DC = computeDeclContext(SS, false);
2422   if (!DC)
2423     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2424                                      NameInfo, /*TemplateArgs=*/nullptr);
2425 
2426   if (RequireCompleteDeclContext(SS, DC))
2427     return ExprError();
2428 
2429   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2430   LookupQualifiedName(R, DC);
2431 
2432   if (R.isAmbiguous())
2433     return ExprError();
2434 
2435   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2436     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2437                                      NameInfo, /*TemplateArgs=*/nullptr);
2438 
2439   if (R.empty()) {
2440     Diag(NameInfo.getLoc(), diag::err_no_member)
2441       << NameInfo.getName() << DC << SS.getRange();
2442     return ExprError();
2443   }
2444 
2445   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2446     // Diagnose a missing typename if this resolved unambiguously to a type in
2447     // a dependent context.  If we can recover with a type, downgrade this to
2448     // a warning in Microsoft compatibility mode.
2449     unsigned DiagID = diag::err_typename_missing;
2450     if (RecoveryTSI && getLangOpts().MSVCCompat)
2451       DiagID = diag::ext_typename_missing;
2452     SourceLocation Loc = SS.getBeginLoc();
2453     auto D = Diag(Loc, DiagID);
2454     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2455       << SourceRange(Loc, NameInfo.getEndLoc());
2456 
2457     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2458     // context.
2459     if (!RecoveryTSI)
2460       return ExprError();
2461 
2462     // Only issue the fixit if we're prepared to recover.
2463     D << FixItHint::CreateInsertion(Loc, "typename ");
2464 
2465     // Recover by pretending this was an elaborated type.
2466     QualType Ty = Context.getTypeDeclType(TD);
2467     TypeLocBuilder TLB;
2468     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2469 
2470     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2471     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2472     QTL.setElaboratedKeywordLoc(SourceLocation());
2473     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2474 
2475     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2476 
2477     return ExprEmpty();
2478   }
2479 
2480   // Defend against this resolving to an implicit member access. We usually
2481   // won't get here if this might be a legitimate a class member (we end up in
2482   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2483   // a pointer-to-member or in an unevaluated context in C++11.
2484   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2485     return BuildPossibleImplicitMemberExpr(SS,
2486                                            /*TemplateKWLoc=*/SourceLocation(),
2487                                            R, /*TemplateArgs=*/nullptr, S);
2488 
2489   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2490 }
2491 
2492 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2493 /// detected that we're currently inside an ObjC method.  Perform some
2494 /// additional lookup.
2495 ///
2496 /// Ideally, most of this would be done by lookup, but there's
2497 /// actually quite a lot of extra work involved.
2498 ///
2499 /// Returns a null sentinel to indicate trivial success.
2500 ExprResult
2501 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2502                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2503   SourceLocation Loc = Lookup.getNameLoc();
2504   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2505 
2506   // Check for error condition which is already reported.
2507   if (!CurMethod)
2508     return ExprError();
2509 
2510   // There are two cases to handle here.  1) scoped lookup could have failed,
2511   // in which case we should look for an ivar.  2) scoped lookup could have
2512   // found a decl, but that decl is outside the current instance method (i.e.
2513   // a global variable).  In these two cases, we do a lookup for an ivar with
2514   // this name, if the lookup sucedes, we replace it our current decl.
2515 
2516   // If we're in a class method, we don't normally want to look for
2517   // ivars.  But if we don't find anything else, and there's an
2518   // ivar, that's an error.
2519   bool IsClassMethod = CurMethod->isClassMethod();
2520 
2521   bool LookForIvars;
2522   if (Lookup.empty())
2523     LookForIvars = true;
2524   else if (IsClassMethod)
2525     LookForIvars = false;
2526   else
2527     LookForIvars = (Lookup.isSingleResult() &&
2528                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2529   ObjCInterfaceDecl *IFace = nullptr;
2530   if (LookForIvars) {
2531     IFace = CurMethod->getClassInterface();
2532     ObjCInterfaceDecl *ClassDeclared;
2533     ObjCIvarDecl *IV = nullptr;
2534     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2535       // Diagnose using an ivar in a class method.
2536       if (IsClassMethod)
2537         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2538                          << IV->getDeclName());
2539 
2540       // If we're referencing an invalid decl, just return this as a silent
2541       // error node.  The error diagnostic was already emitted on the decl.
2542       if (IV->isInvalidDecl())
2543         return ExprError();
2544 
2545       // Check if referencing a field with __attribute__((deprecated)).
2546       if (DiagnoseUseOfDecl(IV, Loc))
2547         return ExprError();
2548 
2549       // Diagnose the use of an ivar outside of the declaring class.
2550       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2551           !declaresSameEntity(ClassDeclared, IFace) &&
2552           !getLangOpts().DebuggerSupport)
2553         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2554 
2555       // FIXME: This should use a new expr for a direct reference, don't
2556       // turn this into Self->ivar, just return a BareIVarExpr or something.
2557       IdentifierInfo &II = Context.Idents.get("self");
2558       UnqualifiedId SelfName;
2559       SelfName.setIdentifier(&II, SourceLocation());
2560       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2561       CXXScopeSpec SelfScopeSpec;
2562       SourceLocation TemplateKWLoc;
2563       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2564                                               SelfName, false, false);
2565       if (SelfExpr.isInvalid())
2566         return ExprError();
2567 
2568       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2569       if (SelfExpr.isInvalid())
2570         return ExprError();
2571 
2572       MarkAnyDeclReferenced(Loc, IV, true);
2573 
2574       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2575       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2576           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2577         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2578 
2579       ObjCIvarRefExpr *Result = new (Context)
2580           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2581                           IV->getLocation(), SelfExpr.get(), true, true);
2582 
2583       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2584         if (!isUnevaluatedContext() &&
2585             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2586           getCurFunction()->recordUseOfWeak(Result);
2587       }
2588       if (getLangOpts().ObjCAutoRefCount) {
2589         if (CurContext->isClosure())
2590           Diag(Loc, diag::warn_implicitly_retains_self)
2591             << FixItHint::CreateInsertion(Loc, "self->");
2592       }
2593 
2594       return Result;
2595     }
2596   } else if (CurMethod->isInstanceMethod()) {
2597     // We should warn if a local variable hides an ivar.
2598     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2599       ObjCInterfaceDecl *ClassDeclared;
2600       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2601         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2602             declaresSameEntity(IFace, ClassDeclared))
2603           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2604       }
2605     }
2606   } else if (Lookup.isSingleResult() &&
2607              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2608     // If accessing a stand-alone ivar in a class method, this is an error.
2609     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2610       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2611                        << IV->getDeclName());
2612   }
2613 
2614   if (Lookup.empty() && II && AllowBuiltinCreation) {
2615     // FIXME. Consolidate this with similar code in LookupName.
2616     if (unsigned BuiltinID = II->getBuiltinID()) {
2617       if (!(getLangOpts().CPlusPlus &&
2618             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2619         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2620                                            S, Lookup.isForRedeclaration(),
2621                                            Lookup.getNameLoc());
2622         if (D) Lookup.addDecl(D);
2623       }
2624     }
2625   }
2626   // Sentinel value saying that we didn't do anything special.
2627   return ExprResult((Expr *)nullptr);
2628 }
2629 
2630 /// Cast a base object to a member's actual type.
2631 ///
2632 /// Logically this happens in three phases:
2633 ///
2634 /// * First we cast from the base type to the naming class.
2635 ///   The naming class is the class into which we were looking
2636 ///   when we found the member;  it's the qualifier type if a
2637 ///   qualifier was provided, and otherwise it's the base type.
2638 ///
2639 /// * Next we cast from the naming class to the declaring class.
2640 ///   If the member we found was brought into a class's scope by
2641 ///   a using declaration, this is that class;  otherwise it's
2642 ///   the class declaring the member.
2643 ///
2644 /// * Finally we cast from the declaring class to the "true"
2645 ///   declaring class of the member.  This conversion does not
2646 ///   obey access control.
2647 ExprResult
2648 Sema::PerformObjectMemberConversion(Expr *From,
2649                                     NestedNameSpecifier *Qualifier,
2650                                     NamedDecl *FoundDecl,
2651                                     NamedDecl *Member) {
2652   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2653   if (!RD)
2654     return From;
2655 
2656   QualType DestRecordType;
2657   QualType DestType;
2658   QualType FromRecordType;
2659   QualType FromType = From->getType();
2660   bool PointerConversions = false;
2661   if (isa<FieldDecl>(Member)) {
2662     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2663 
2664     if (FromType->getAs<PointerType>()) {
2665       DestType = Context.getPointerType(DestRecordType);
2666       FromRecordType = FromType->getPointeeType();
2667       PointerConversions = true;
2668     } else {
2669       DestType = DestRecordType;
2670       FromRecordType = FromType;
2671     }
2672   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2673     if (Method->isStatic())
2674       return From;
2675 
2676     DestType = Method->getThisType();
2677     DestRecordType = DestType->getPointeeType();
2678 
2679     if (FromType->getAs<PointerType>()) {
2680       FromRecordType = FromType->getPointeeType();
2681       PointerConversions = true;
2682     } else {
2683       FromRecordType = FromType;
2684       DestType = DestRecordType;
2685     }
2686   } else {
2687     // No conversion necessary.
2688     return From;
2689   }
2690 
2691   if (DestType->isDependentType() || FromType->isDependentType())
2692     return From;
2693 
2694   // If the unqualified types are the same, no conversion is necessary.
2695   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2696     return From;
2697 
2698   SourceRange FromRange = From->getSourceRange();
2699   SourceLocation FromLoc = FromRange.getBegin();
2700 
2701   ExprValueKind VK = From->getValueKind();
2702 
2703   // C++ [class.member.lookup]p8:
2704   //   [...] Ambiguities can often be resolved by qualifying a name with its
2705   //   class name.
2706   //
2707   // If the member was a qualified name and the qualified referred to a
2708   // specific base subobject type, we'll cast to that intermediate type
2709   // first and then to the object in which the member is declared. That allows
2710   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2711   //
2712   //   class Base { public: int x; };
2713   //   class Derived1 : public Base { };
2714   //   class Derived2 : public Base { };
2715   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2716   //
2717   //   void VeryDerived::f() {
2718   //     x = 17; // error: ambiguous base subobjects
2719   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2720   //   }
2721   if (Qualifier && Qualifier->getAsType()) {
2722     QualType QType = QualType(Qualifier->getAsType(), 0);
2723     assert(QType->isRecordType() && "lookup done with non-record type");
2724 
2725     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2726 
2727     // In C++98, the qualifier type doesn't actually have to be a base
2728     // type of the object type, in which case we just ignore it.
2729     // Otherwise build the appropriate casts.
2730     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2731       CXXCastPath BasePath;
2732       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2733                                        FromLoc, FromRange, &BasePath))
2734         return ExprError();
2735 
2736       if (PointerConversions)
2737         QType = Context.getPointerType(QType);
2738       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2739                                VK, &BasePath).get();
2740 
2741       FromType = QType;
2742       FromRecordType = QRecordType;
2743 
2744       // If the qualifier type was the same as the destination type,
2745       // we're done.
2746       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2747         return From;
2748     }
2749   }
2750 
2751   bool IgnoreAccess = false;
2752 
2753   // If we actually found the member through a using declaration, cast
2754   // down to the using declaration's type.
2755   //
2756   // Pointer equality is fine here because only one declaration of a
2757   // class ever has member declarations.
2758   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2759     assert(isa<UsingShadowDecl>(FoundDecl));
2760     QualType URecordType = Context.getTypeDeclType(
2761                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2762 
2763     // We only need to do this if the naming-class to declaring-class
2764     // conversion is non-trivial.
2765     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2766       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2767       CXXCastPath BasePath;
2768       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2769                                        FromLoc, FromRange, &BasePath))
2770         return ExprError();
2771 
2772       QualType UType = URecordType;
2773       if (PointerConversions)
2774         UType = Context.getPointerType(UType);
2775       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2776                                VK, &BasePath).get();
2777       FromType = UType;
2778       FromRecordType = URecordType;
2779     }
2780 
2781     // We don't do access control for the conversion from the
2782     // declaring class to the true declaring class.
2783     IgnoreAccess = true;
2784   }
2785 
2786   CXXCastPath BasePath;
2787   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2788                                    FromLoc, FromRange, &BasePath,
2789                                    IgnoreAccess))
2790     return ExprError();
2791 
2792   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2793                            VK, &BasePath);
2794 }
2795 
2796 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2797                                       const LookupResult &R,
2798                                       bool HasTrailingLParen) {
2799   // Only when used directly as the postfix-expression of a call.
2800   if (!HasTrailingLParen)
2801     return false;
2802 
2803   // Never if a scope specifier was provided.
2804   if (SS.isSet())
2805     return false;
2806 
2807   // Only in C++ or ObjC++.
2808   if (!getLangOpts().CPlusPlus)
2809     return false;
2810 
2811   // Turn off ADL when we find certain kinds of declarations during
2812   // normal lookup:
2813   for (NamedDecl *D : R) {
2814     // C++0x [basic.lookup.argdep]p3:
2815     //     -- a declaration of a class member
2816     // Since using decls preserve this property, we check this on the
2817     // original decl.
2818     if (D->isCXXClassMember())
2819       return false;
2820 
2821     // C++0x [basic.lookup.argdep]p3:
2822     //     -- a block-scope function declaration that is not a
2823     //        using-declaration
2824     // NOTE: we also trigger this for function templates (in fact, we
2825     // don't check the decl type at all, since all other decl types
2826     // turn off ADL anyway).
2827     if (isa<UsingShadowDecl>(D))
2828       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2829     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2830       return false;
2831 
2832     // C++0x [basic.lookup.argdep]p3:
2833     //     -- a declaration that is neither a function or a function
2834     //        template
2835     // And also for builtin functions.
2836     if (isa<FunctionDecl>(D)) {
2837       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2838 
2839       // But also builtin functions.
2840       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2841         return false;
2842     } else if (!isa<FunctionTemplateDecl>(D))
2843       return false;
2844   }
2845 
2846   return true;
2847 }
2848 
2849 
2850 /// Diagnoses obvious problems with the use of the given declaration
2851 /// as an expression.  This is only actually called for lookups that
2852 /// were not overloaded, and it doesn't promise that the declaration
2853 /// will in fact be used.
2854 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2855   if (D->isInvalidDecl())
2856     return true;
2857 
2858   if (isa<TypedefNameDecl>(D)) {
2859     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2860     return true;
2861   }
2862 
2863   if (isa<ObjCInterfaceDecl>(D)) {
2864     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2865     return true;
2866   }
2867 
2868   if (isa<NamespaceDecl>(D)) {
2869     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2870     return true;
2871   }
2872 
2873   return false;
2874 }
2875 
2876 // Certain multiversion types should be treated as overloaded even when there is
2877 // only one result.
2878 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2879   assert(R.isSingleResult() && "Expected only a single result");
2880   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2881   return FD &&
2882          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2883 }
2884 
2885 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2886                                           LookupResult &R, bool NeedsADL,
2887                                           bool AcceptInvalidDecl) {
2888   // If this is a single, fully-resolved result and we don't need ADL,
2889   // just build an ordinary singleton decl ref.
2890   if (!NeedsADL && R.isSingleResult() &&
2891       !R.getAsSingle<FunctionTemplateDecl>() &&
2892       !ShouldLookupResultBeMultiVersionOverload(R))
2893     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2894                                     R.getRepresentativeDecl(), nullptr,
2895                                     AcceptInvalidDecl);
2896 
2897   // We only need to check the declaration if there's exactly one
2898   // result, because in the overloaded case the results can only be
2899   // functions and function templates.
2900   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2901       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2902     return ExprError();
2903 
2904   // Otherwise, just build an unresolved lookup expression.  Suppress
2905   // any lookup-related diagnostics; we'll hash these out later, when
2906   // we've picked a target.
2907   R.suppressDiagnostics();
2908 
2909   UnresolvedLookupExpr *ULE
2910     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2911                                    SS.getWithLocInContext(Context),
2912                                    R.getLookupNameInfo(),
2913                                    NeedsADL, R.isOverloadedResult(),
2914                                    R.begin(), R.end());
2915 
2916   return ULE;
2917 }
2918 
2919 static void
2920 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2921                                    ValueDecl *var, DeclContext *DC);
2922 
2923 /// Complete semantic analysis for a reference to the given declaration.
2924 ExprResult Sema::BuildDeclarationNameExpr(
2925     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2926     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2927     bool AcceptInvalidDecl) {
2928   assert(D && "Cannot refer to a NULL declaration");
2929   assert(!isa<FunctionTemplateDecl>(D) &&
2930          "Cannot refer unambiguously to a function template");
2931 
2932   SourceLocation Loc = NameInfo.getLoc();
2933   if (CheckDeclInExpr(*this, Loc, D))
2934     return ExprError();
2935 
2936   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2937     // Specifically diagnose references to class templates that are missing
2938     // a template argument list.
2939     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2940     return ExprError();
2941   }
2942 
2943   // Make sure that we're referring to a value.
2944   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2945   if (!VD) {
2946     Diag(Loc, diag::err_ref_non_value)
2947       << D << SS.getRange();
2948     Diag(D->getLocation(), diag::note_declared_at);
2949     return ExprError();
2950   }
2951 
2952   // Check whether this declaration can be used. Note that we suppress
2953   // this check when we're going to perform argument-dependent lookup
2954   // on this function name, because this might not be the function
2955   // that overload resolution actually selects.
2956   if (DiagnoseUseOfDecl(VD, Loc))
2957     return ExprError();
2958 
2959   // Only create DeclRefExpr's for valid Decl's.
2960   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2961     return ExprError();
2962 
2963   // Handle members of anonymous structs and unions.  If we got here,
2964   // and the reference is to a class member indirect field, then this
2965   // must be the subject of a pointer-to-member expression.
2966   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2967     if (!indirectField->isCXXClassMember())
2968       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2969                                                       indirectField);
2970 
2971   {
2972     QualType type = VD->getType();
2973     if (type.isNull())
2974       return ExprError();
2975     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2976       // C++ [except.spec]p17:
2977       //   An exception-specification is considered to be needed when:
2978       //   - in an expression, the function is the unique lookup result or
2979       //     the selected member of a set of overloaded functions.
2980       ResolveExceptionSpec(Loc, FPT);
2981       type = VD->getType();
2982     }
2983     ExprValueKind valueKind = VK_RValue;
2984 
2985     switch (D->getKind()) {
2986     // Ignore all the non-ValueDecl kinds.
2987 #define ABSTRACT_DECL(kind)
2988 #define VALUE(type, base)
2989 #define DECL(type, base) \
2990     case Decl::type:
2991 #include "clang/AST/DeclNodes.inc"
2992       llvm_unreachable("invalid value decl kind");
2993 
2994     // These shouldn't make it here.
2995     case Decl::ObjCAtDefsField:
2996     case Decl::ObjCIvar:
2997       llvm_unreachable("forming non-member reference to ivar?");
2998 
2999     // Enum constants are always r-values and never references.
3000     // Unresolved using declarations are dependent.
3001     case Decl::EnumConstant:
3002     case Decl::UnresolvedUsingValue:
3003     case Decl::OMPDeclareReduction:
3004     case Decl::OMPDeclareMapper:
3005       valueKind = VK_RValue;
3006       break;
3007 
3008     // Fields and indirect fields that got here must be for
3009     // pointer-to-member expressions; we just call them l-values for
3010     // internal consistency, because this subexpression doesn't really
3011     // exist in the high-level semantics.
3012     case Decl::Field:
3013     case Decl::IndirectField:
3014       assert(getLangOpts().CPlusPlus &&
3015              "building reference to field in C?");
3016 
3017       // These can't have reference type in well-formed programs, but
3018       // for internal consistency we do this anyway.
3019       type = type.getNonReferenceType();
3020       valueKind = VK_LValue;
3021       break;
3022 
3023     // Non-type template parameters are either l-values or r-values
3024     // depending on the type.
3025     case Decl::NonTypeTemplateParm: {
3026       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3027         type = reftype->getPointeeType();
3028         valueKind = VK_LValue; // even if the parameter is an r-value reference
3029         break;
3030       }
3031 
3032       // For non-references, we need to strip qualifiers just in case
3033       // the template parameter was declared as 'const int' or whatever.
3034       valueKind = VK_RValue;
3035       type = type.getUnqualifiedType();
3036       break;
3037     }
3038 
3039     case Decl::Var:
3040     case Decl::VarTemplateSpecialization:
3041     case Decl::VarTemplatePartialSpecialization:
3042     case Decl::Decomposition:
3043     case Decl::OMPCapturedExpr:
3044       // In C, "extern void blah;" is valid and is an r-value.
3045       if (!getLangOpts().CPlusPlus &&
3046           !type.hasQualifiers() &&
3047           type->isVoidType()) {
3048         valueKind = VK_RValue;
3049         break;
3050       }
3051       LLVM_FALLTHROUGH;
3052 
3053     case Decl::ImplicitParam:
3054     case Decl::ParmVar: {
3055       // These are always l-values.
3056       valueKind = VK_LValue;
3057       type = type.getNonReferenceType();
3058 
3059       // FIXME: Does the addition of const really only apply in
3060       // potentially-evaluated contexts? Since the variable isn't actually
3061       // captured in an unevaluated context, it seems that the answer is no.
3062       if (!isUnevaluatedContext()) {
3063         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3064         if (!CapturedType.isNull())
3065           type = CapturedType;
3066       }
3067 
3068       break;
3069     }
3070 
3071     case Decl::Binding: {
3072       // These are always lvalues.
3073       valueKind = VK_LValue;
3074       type = type.getNonReferenceType();
3075       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3076       // decides how that's supposed to work.
3077       auto *BD = cast<BindingDecl>(VD);
3078       if (BD->getDeclContext()->isFunctionOrMethod() &&
3079           BD->getDeclContext() != CurContext)
3080         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3081       break;
3082     }
3083 
3084     case Decl::Function: {
3085       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3086         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3087           type = Context.BuiltinFnTy;
3088           valueKind = VK_RValue;
3089           break;
3090         }
3091       }
3092 
3093       const FunctionType *fty = type->castAs<FunctionType>();
3094 
3095       // If we're referring to a function with an __unknown_anytype
3096       // result type, make the entire expression __unknown_anytype.
3097       if (fty->getReturnType() == Context.UnknownAnyTy) {
3098         type = Context.UnknownAnyTy;
3099         valueKind = VK_RValue;
3100         break;
3101       }
3102 
3103       // Functions are l-values in C++.
3104       if (getLangOpts().CPlusPlus) {
3105         valueKind = VK_LValue;
3106         break;
3107       }
3108 
3109       // C99 DR 316 says that, if a function type comes from a
3110       // function definition (without a prototype), that type is only
3111       // used for checking compatibility. Therefore, when referencing
3112       // the function, we pretend that we don't have the full function
3113       // type.
3114       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3115           isa<FunctionProtoType>(fty))
3116         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3117                                               fty->getExtInfo());
3118 
3119       // Functions are r-values in C.
3120       valueKind = VK_RValue;
3121       break;
3122     }
3123 
3124     case Decl::CXXDeductionGuide:
3125       llvm_unreachable("building reference to deduction guide");
3126 
3127     case Decl::MSProperty:
3128       valueKind = VK_LValue;
3129       break;
3130 
3131     case Decl::CXXMethod:
3132       // If we're referring to a method with an __unknown_anytype
3133       // result type, make the entire expression __unknown_anytype.
3134       // This should only be possible with a type written directly.
3135       if (const FunctionProtoType *proto
3136             = dyn_cast<FunctionProtoType>(VD->getType()))
3137         if (proto->getReturnType() == Context.UnknownAnyTy) {
3138           type = Context.UnknownAnyTy;
3139           valueKind = VK_RValue;
3140           break;
3141         }
3142 
3143       // C++ methods are l-values if static, r-values if non-static.
3144       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3145         valueKind = VK_LValue;
3146         break;
3147       }
3148       LLVM_FALLTHROUGH;
3149 
3150     case Decl::CXXConversion:
3151     case Decl::CXXDestructor:
3152     case Decl::CXXConstructor:
3153       valueKind = VK_RValue;
3154       break;
3155     }
3156 
3157     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3158                             TemplateArgs);
3159   }
3160 }
3161 
3162 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3163                                     SmallString<32> &Target) {
3164   Target.resize(CharByteWidth * (Source.size() + 1));
3165   char *ResultPtr = &Target[0];
3166   const llvm::UTF8 *ErrorPtr;
3167   bool success =
3168       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3169   (void)success;
3170   assert(success);
3171   Target.resize(ResultPtr - &Target[0]);
3172 }
3173 
3174 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3175                                      PredefinedExpr::IdentKind IK) {
3176   // Pick the current block, lambda, captured statement or function.
3177   Decl *currentDecl = nullptr;
3178   if (const BlockScopeInfo *BSI = getCurBlock())
3179     currentDecl = BSI->TheDecl;
3180   else if (const LambdaScopeInfo *LSI = getCurLambda())
3181     currentDecl = LSI->CallOperator;
3182   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3183     currentDecl = CSI->TheCapturedDecl;
3184   else
3185     currentDecl = getCurFunctionOrMethodDecl();
3186 
3187   if (!currentDecl) {
3188     Diag(Loc, diag::ext_predef_outside_function);
3189     currentDecl = Context.getTranslationUnitDecl();
3190   }
3191 
3192   QualType ResTy;
3193   StringLiteral *SL = nullptr;
3194   if (cast<DeclContext>(currentDecl)->isDependentContext())
3195     ResTy = Context.DependentTy;
3196   else {
3197     // Pre-defined identifiers are of type char[x], where x is the length of
3198     // the string.
3199     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3200     unsigned Length = Str.length();
3201 
3202     llvm::APInt LengthI(32, Length + 1);
3203     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3204       ResTy =
3205           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3206       SmallString<32> RawChars;
3207       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3208                               Str, RawChars);
3209       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3210                                            /*IndexTypeQuals*/ 0);
3211       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3212                                  /*Pascal*/ false, ResTy, Loc);
3213     } else {
3214       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3215       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3216                                            /*IndexTypeQuals*/ 0);
3217       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3218                                  /*Pascal*/ false, ResTy, Loc);
3219     }
3220   }
3221 
3222   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3223 }
3224 
3225 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3226   PredefinedExpr::IdentKind IK;
3227 
3228   switch (Kind) {
3229   default: llvm_unreachable("Unknown simple primary expr!");
3230   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3231   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3232   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3233   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3234   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3235   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3236   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3237   }
3238 
3239   return BuildPredefinedExpr(Loc, IK);
3240 }
3241 
3242 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3243   SmallString<16> CharBuffer;
3244   bool Invalid = false;
3245   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3246   if (Invalid)
3247     return ExprError();
3248 
3249   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3250                             PP, Tok.getKind());
3251   if (Literal.hadError())
3252     return ExprError();
3253 
3254   QualType Ty;
3255   if (Literal.isWide())
3256     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3257   else if (Literal.isUTF8() && getLangOpts().Char8)
3258     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3259   else if (Literal.isUTF16())
3260     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3261   else if (Literal.isUTF32())
3262     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3263   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3264     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3265   else
3266     Ty = Context.CharTy;  // 'x' -> char in C++
3267 
3268   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3269   if (Literal.isWide())
3270     Kind = CharacterLiteral::Wide;
3271   else if (Literal.isUTF16())
3272     Kind = CharacterLiteral::UTF16;
3273   else if (Literal.isUTF32())
3274     Kind = CharacterLiteral::UTF32;
3275   else if (Literal.isUTF8())
3276     Kind = CharacterLiteral::UTF8;
3277 
3278   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3279                                              Tok.getLocation());
3280 
3281   if (Literal.getUDSuffix().empty())
3282     return Lit;
3283 
3284   // We're building a user-defined literal.
3285   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3286   SourceLocation UDSuffixLoc =
3287     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3288 
3289   // Make sure we're allowed user-defined literals here.
3290   if (!UDLScope)
3291     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3292 
3293   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3294   //   operator "" X (ch)
3295   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3296                                         Lit, Tok.getLocation());
3297 }
3298 
3299 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3300   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3301   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3302                                 Context.IntTy, Loc);
3303 }
3304 
3305 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3306                                   QualType Ty, SourceLocation Loc) {
3307   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3308 
3309   using llvm::APFloat;
3310   APFloat Val(Format);
3311 
3312   APFloat::opStatus result = Literal.GetFloatValue(Val);
3313 
3314   // Overflow is always an error, but underflow is only an error if
3315   // we underflowed to zero (APFloat reports denormals as underflow).
3316   if ((result & APFloat::opOverflow) ||
3317       ((result & APFloat::opUnderflow) && Val.isZero())) {
3318     unsigned diagnostic;
3319     SmallString<20> buffer;
3320     if (result & APFloat::opOverflow) {
3321       diagnostic = diag::warn_float_overflow;
3322       APFloat::getLargest(Format).toString(buffer);
3323     } else {
3324       diagnostic = diag::warn_float_underflow;
3325       APFloat::getSmallest(Format).toString(buffer);
3326     }
3327 
3328     S.Diag(Loc, diagnostic)
3329       << Ty
3330       << StringRef(buffer.data(), buffer.size());
3331   }
3332 
3333   bool isExact = (result == APFloat::opOK);
3334   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3335 }
3336 
3337 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3338   assert(E && "Invalid expression");
3339 
3340   if (E->isValueDependent())
3341     return false;
3342 
3343   QualType QT = E->getType();
3344   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3345     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3346     return true;
3347   }
3348 
3349   llvm::APSInt ValueAPS;
3350   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3351 
3352   if (R.isInvalid())
3353     return true;
3354 
3355   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3356   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3357     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3358         << ValueAPS.toString(10) << ValueIsPositive;
3359     return true;
3360   }
3361 
3362   return false;
3363 }
3364 
3365 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3366   // Fast path for a single digit (which is quite common).  A single digit
3367   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3368   if (Tok.getLength() == 1) {
3369     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3370     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3371   }
3372 
3373   SmallString<128> SpellingBuffer;
3374   // NumericLiteralParser wants to overread by one character.  Add padding to
3375   // the buffer in case the token is copied to the buffer.  If getSpelling()
3376   // returns a StringRef to the memory buffer, it should have a null char at
3377   // the EOF, so it is also safe.
3378   SpellingBuffer.resize(Tok.getLength() + 1);
3379 
3380   // Get the spelling of the token, which eliminates trigraphs, etc.
3381   bool Invalid = false;
3382   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3383   if (Invalid)
3384     return ExprError();
3385 
3386   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3387   if (Literal.hadError)
3388     return ExprError();
3389 
3390   if (Literal.hasUDSuffix()) {
3391     // We're building a user-defined literal.
3392     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3393     SourceLocation UDSuffixLoc =
3394       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3395 
3396     // Make sure we're allowed user-defined literals here.
3397     if (!UDLScope)
3398       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3399 
3400     QualType CookedTy;
3401     if (Literal.isFloatingLiteral()) {
3402       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3403       // long double, the literal is treated as a call of the form
3404       //   operator "" X (f L)
3405       CookedTy = Context.LongDoubleTy;
3406     } else {
3407       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3408       // unsigned long long, the literal is treated as a call of the form
3409       //   operator "" X (n ULL)
3410       CookedTy = Context.UnsignedLongLongTy;
3411     }
3412 
3413     DeclarationName OpName =
3414       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3415     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3416     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3417 
3418     SourceLocation TokLoc = Tok.getLocation();
3419 
3420     // Perform literal operator lookup to determine if we're building a raw
3421     // literal or a cooked one.
3422     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3423     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3424                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3425                                   /*AllowStringTemplate*/ false,
3426                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3427     case LOLR_ErrorNoDiagnostic:
3428       // Lookup failure for imaginary constants isn't fatal, there's still the
3429       // GNU extension producing _Complex types.
3430       break;
3431     case LOLR_Error:
3432       return ExprError();
3433     case LOLR_Cooked: {
3434       Expr *Lit;
3435       if (Literal.isFloatingLiteral()) {
3436         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3437       } else {
3438         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3439         if (Literal.GetIntegerValue(ResultVal))
3440           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3441               << /* Unsigned */ 1;
3442         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3443                                      Tok.getLocation());
3444       }
3445       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3446     }
3447 
3448     case LOLR_Raw: {
3449       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3450       // literal is treated as a call of the form
3451       //   operator "" X ("n")
3452       unsigned Length = Literal.getUDSuffixOffset();
3453       QualType StrTy = Context.getConstantArrayType(
3454           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3455           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3456       Expr *Lit = StringLiteral::Create(
3457           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3458           /*Pascal*/false, StrTy, &TokLoc, 1);
3459       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3460     }
3461 
3462     case LOLR_Template: {
3463       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3464       // template), L is treated as a call fo the form
3465       //   operator "" X <'c1', 'c2', ... 'ck'>()
3466       // where n is the source character sequence c1 c2 ... ck.
3467       TemplateArgumentListInfo ExplicitArgs;
3468       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3469       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3470       llvm::APSInt Value(CharBits, CharIsUnsigned);
3471       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3472         Value = TokSpelling[I];
3473         TemplateArgument Arg(Context, Value, Context.CharTy);
3474         TemplateArgumentLocInfo ArgInfo;
3475         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3476       }
3477       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3478                                       &ExplicitArgs);
3479     }
3480     case LOLR_StringTemplate:
3481       llvm_unreachable("unexpected literal operator lookup result");
3482     }
3483   }
3484 
3485   Expr *Res;
3486 
3487   if (Literal.isFixedPointLiteral()) {
3488     QualType Ty;
3489 
3490     if (Literal.isAccum) {
3491       if (Literal.isHalf) {
3492         Ty = Context.ShortAccumTy;
3493       } else if (Literal.isLong) {
3494         Ty = Context.LongAccumTy;
3495       } else {
3496         Ty = Context.AccumTy;
3497       }
3498     } else if (Literal.isFract) {
3499       if (Literal.isHalf) {
3500         Ty = Context.ShortFractTy;
3501       } else if (Literal.isLong) {
3502         Ty = Context.LongFractTy;
3503       } else {
3504         Ty = Context.FractTy;
3505       }
3506     }
3507 
3508     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3509 
3510     bool isSigned = !Literal.isUnsigned;
3511     unsigned scale = Context.getFixedPointScale(Ty);
3512     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3513 
3514     llvm::APInt Val(bit_width, 0, isSigned);
3515     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3516     bool ValIsZero = Val.isNullValue() && !Overflowed;
3517 
3518     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3519     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3520       // Clause 6.4.4 - The value of a constant shall be in the range of
3521       // representable values for its type, with exception for constants of a
3522       // fract type with a value of exactly 1; such a constant shall denote
3523       // the maximal value for the type.
3524       --Val;
3525     else if (Val.ugt(MaxVal) || Overflowed)
3526       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3527 
3528     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3529                                               Tok.getLocation(), scale);
3530   } else if (Literal.isFloatingLiteral()) {
3531     QualType Ty;
3532     if (Literal.isHalf){
3533       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3534         Ty = Context.HalfTy;
3535       else {
3536         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3537         return ExprError();
3538       }
3539     } else if (Literal.isFloat)
3540       Ty = Context.FloatTy;
3541     else if (Literal.isLong)
3542       Ty = Context.LongDoubleTy;
3543     else if (Literal.isFloat16)
3544       Ty = Context.Float16Ty;
3545     else if (Literal.isFloat128)
3546       Ty = Context.Float128Ty;
3547     else
3548       Ty = Context.DoubleTy;
3549 
3550     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3551 
3552     if (Ty == Context.DoubleTy) {
3553       if (getLangOpts().SinglePrecisionConstants) {
3554         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3555         if (BTy->getKind() != BuiltinType::Float) {
3556           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3557         }
3558       } else if (getLangOpts().OpenCL &&
3559                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3560         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3561         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3562         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3563       }
3564     }
3565   } else if (!Literal.isIntegerLiteral()) {
3566     return ExprError();
3567   } else {
3568     QualType Ty;
3569 
3570     // 'long long' is a C99 or C++11 feature.
3571     if (!getLangOpts().C99 && Literal.isLongLong) {
3572       if (getLangOpts().CPlusPlus)
3573         Diag(Tok.getLocation(),
3574              getLangOpts().CPlusPlus11 ?
3575              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3576       else
3577         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3578     }
3579 
3580     // Get the value in the widest-possible width.
3581     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3582     llvm::APInt ResultVal(MaxWidth, 0);
3583 
3584     if (Literal.GetIntegerValue(ResultVal)) {
3585       // If this value didn't fit into uintmax_t, error and force to ull.
3586       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3587           << /* Unsigned */ 1;
3588       Ty = Context.UnsignedLongLongTy;
3589       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3590              "long long is not intmax_t?");
3591     } else {
3592       // If this value fits into a ULL, try to figure out what else it fits into
3593       // according to the rules of C99 6.4.4.1p5.
3594 
3595       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3596       // be an unsigned int.
3597       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3598 
3599       // Check from smallest to largest, picking the smallest type we can.
3600       unsigned Width = 0;
3601 
3602       // Microsoft specific integer suffixes are explicitly sized.
3603       if (Literal.MicrosoftInteger) {
3604         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3605           Width = 8;
3606           Ty = Context.CharTy;
3607         } else {
3608           Width = Literal.MicrosoftInteger;
3609           Ty = Context.getIntTypeForBitwidth(Width,
3610                                              /*Signed=*/!Literal.isUnsigned);
3611         }
3612       }
3613 
3614       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3615         // Are int/unsigned possibilities?
3616         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3617 
3618         // Does it fit in a unsigned int?
3619         if (ResultVal.isIntN(IntSize)) {
3620           // Does it fit in a signed int?
3621           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3622             Ty = Context.IntTy;
3623           else if (AllowUnsigned)
3624             Ty = Context.UnsignedIntTy;
3625           Width = IntSize;
3626         }
3627       }
3628 
3629       // Are long/unsigned long possibilities?
3630       if (Ty.isNull() && !Literal.isLongLong) {
3631         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3632 
3633         // Does it fit in a unsigned long?
3634         if (ResultVal.isIntN(LongSize)) {
3635           // Does it fit in a signed long?
3636           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3637             Ty = Context.LongTy;
3638           else if (AllowUnsigned)
3639             Ty = Context.UnsignedLongTy;
3640           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3641           // is compatible.
3642           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3643             const unsigned LongLongSize =
3644                 Context.getTargetInfo().getLongLongWidth();
3645             Diag(Tok.getLocation(),
3646                  getLangOpts().CPlusPlus
3647                      ? Literal.isLong
3648                            ? diag::warn_old_implicitly_unsigned_long_cxx
3649                            : /*C++98 UB*/ diag::
3650                                  ext_old_implicitly_unsigned_long_cxx
3651                      : diag::warn_old_implicitly_unsigned_long)
3652                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3653                                             : /*will be ill-formed*/ 1);
3654             Ty = Context.UnsignedLongTy;
3655           }
3656           Width = LongSize;
3657         }
3658       }
3659 
3660       // Check long long if needed.
3661       if (Ty.isNull()) {
3662         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3663 
3664         // Does it fit in a unsigned long long?
3665         if (ResultVal.isIntN(LongLongSize)) {
3666           // Does it fit in a signed long long?
3667           // To be compatible with MSVC, hex integer literals ending with the
3668           // LL or i64 suffix are always signed in Microsoft mode.
3669           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3670               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3671             Ty = Context.LongLongTy;
3672           else if (AllowUnsigned)
3673             Ty = Context.UnsignedLongLongTy;
3674           Width = LongLongSize;
3675         }
3676       }
3677 
3678       // If we still couldn't decide a type, we probably have something that
3679       // does not fit in a signed long long, but has no U suffix.
3680       if (Ty.isNull()) {
3681         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3682         Ty = Context.UnsignedLongLongTy;
3683         Width = Context.getTargetInfo().getLongLongWidth();
3684       }
3685 
3686       if (ResultVal.getBitWidth() != Width)
3687         ResultVal = ResultVal.trunc(Width);
3688     }
3689     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3690   }
3691 
3692   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3693   if (Literal.isImaginary) {
3694     Res = new (Context) ImaginaryLiteral(Res,
3695                                         Context.getComplexType(Res->getType()));
3696 
3697     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3698   }
3699   return Res;
3700 }
3701 
3702 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3703   assert(E && "ActOnParenExpr() missing expr");
3704   return new (Context) ParenExpr(L, R, E);
3705 }
3706 
3707 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3708                                          SourceLocation Loc,
3709                                          SourceRange ArgRange) {
3710   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3711   // scalar or vector data type argument..."
3712   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3713   // type (C99 6.2.5p18) or void.
3714   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3715     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3716       << T << ArgRange;
3717     return true;
3718   }
3719 
3720   assert((T->isVoidType() || !T->isIncompleteType()) &&
3721          "Scalar types should always be complete");
3722   return false;
3723 }
3724 
3725 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3726                                            SourceLocation Loc,
3727                                            SourceRange ArgRange,
3728                                            UnaryExprOrTypeTrait TraitKind) {
3729   // Invalid types must be hard errors for SFINAE in C++.
3730   if (S.LangOpts.CPlusPlus)
3731     return true;
3732 
3733   // C99 6.5.3.4p1:
3734   if (T->isFunctionType() &&
3735       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3736        TraitKind == UETT_PreferredAlignOf)) {
3737     // sizeof(function)/alignof(function) is allowed as an extension.
3738     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3739       << TraitKind << ArgRange;
3740     return false;
3741   }
3742 
3743   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3744   // this is an error (OpenCL v1.1 s6.3.k)
3745   if (T->isVoidType()) {
3746     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3747                                         : diag::ext_sizeof_alignof_void_type;
3748     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3749     return false;
3750   }
3751 
3752   return true;
3753 }
3754 
3755 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3756                                              SourceLocation Loc,
3757                                              SourceRange ArgRange,
3758                                              UnaryExprOrTypeTrait TraitKind) {
3759   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3760   // runtime doesn't allow it.
3761   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3762     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3763       << T << (TraitKind == UETT_SizeOf)
3764       << ArgRange;
3765     return true;
3766   }
3767 
3768   return false;
3769 }
3770 
3771 /// Check whether E is a pointer from a decayed array type (the decayed
3772 /// pointer type is equal to T) and emit a warning if it is.
3773 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3774                                      Expr *E) {
3775   // Don't warn if the operation changed the type.
3776   if (T != E->getType())
3777     return;
3778 
3779   // Now look for array decays.
3780   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3781   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3782     return;
3783 
3784   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3785                                              << ICE->getType()
3786                                              << ICE->getSubExpr()->getType();
3787 }
3788 
3789 /// Check the constraints on expression operands to unary type expression
3790 /// and type traits.
3791 ///
3792 /// Completes any types necessary and validates the constraints on the operand
3793 /// expression. The logic mostly mirrors the type-based overload, but may modify
3794 /// the expression as it completes the type for that expression through template
3795 /// instantiation, etc.
3796 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3797                                             UnaryExprOrTypeTrait ExprKind) {
3798   QualType ExprTy = E->getType();
3799   assert(!ExprTy->isReferenceType());
3800 
3801   if (ExprKind == UETT_VecStep)
3802     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3803                                         E->getSourceRange());
3804 
3805   // Whitelist some types as extensions
3806   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3807                                       E->getSourceRange(), ExprKind))
3808     return false;
3809 
3810   // 'alignof' applied to an expression only requires the base element type of
3811   // the expression to be complete. 'sizeof' requires the expression's type to
3812   // be complete (and will attempt to complete it if it's an array of unknown
3813   // bound).
3814   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3815     if (RequireCompleteType(E->getExprLoc(),
3816                             Context.getBaseElementType(E->getType()),
3817                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3818                             E->getSourceRange()))
3819       return true;
3820   } else {
3821     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3822                                 ExprKind, E->getSourceRange()))
3823       return true;
3824   }
3825 
3826   // Completing the expression's type may have changed it.
3827   ExprTy = E->getType();
3828   assert(!ExprTy->isReferenceType());
3829 
3830   if (ExprTy->isFunctionType()) {
3831     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3832       << ExprKind << E->getSourceRange();
3833     return true;
3834   }
3835 
3836   // The operand for sizeof and alignof is in an unevaluated expression context,
3837   // so side effects could result in unintended consequences.
3838   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3839        ExprKind == UETT_PreferredAlignOf) &&
3840       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3841     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3842 
3843   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3844                                        E->getSourceRange(), ExprKind))
3845     return true;
3846 
3847   if (ExprKind == UETT_SizeOf) {
3848     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3849       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3850         QualType OType = PVD->getOriginalType();
3851         QualType Type = PVD->getType();
3852         if (Type->isPointerType() && OType->isArrayType()) {
3853           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3854             << Type << OType;
3855           Diag(PVD->getLocation(), diag::note_declared_at);
3856         }
3857       }
3858     }
3859 
3860     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3861     // decays into a pointer and returns an unintended result. This is most
3862     // likely a typo for "sizeof(array) op x".
3863     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3864       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3865                                BO->getLHS());
3866       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3867                                BO->getRHS());
3868     }
3869   }
3870 
3871   return false;
3872 }
3873 
3874 /// Check the constraints on operands to unary expression and type
3875 /// traits.
3876 ///
3877 /// This will complete any types necessary, and validate the various constraints
3878 /// on those operands.
3879 ///
3880 /// The UsualUnaryConversions() function is *not* called by this routine.
3881 /// C99 6.3.2.1p[2-4] all state:
3882 ///   Except when it is the operand of the sizeof operator ...
3883 ///
3884 /// C++ [expr.sizeof]p4
3885 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3886 ///   standard conversions are not applied to the operand of sizeof.
3887 ///
3888 /// This policy is followed for all of the unary trait expressions.
3889 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3890                                             SourceLocation OpLoc,
3891                                             SourceRange ExprRange,
3892                                             UnaryExprOrTypeTrait ExprKind) {
3893   if (ExprType->isDependentType())
3894     return false;
3895 
3896   // C++ [expr.sizeof]p2:
3897   //     When applied to a reference or a reference type, the result
3898   //     is the size of the referenced type.
3899   // C++11 [expr.alignof]p3:
3900   //     When alignof is applied to a reference type, the result
3901   //     shall be the alignment of the referenced type.
3902   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3903     ExprType = Ref->getPointeeType();
3904 
3905   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3906   //   When alignof or _Alignof is applied to an array type, the result
3907   //   is the alignment of the element type.
3908   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3909       ExprKind == UETT_OpenMPRequiredSimdAlign)
3910     ExprType = Context.getBaseElementType(ExprType);
3911 
3912   if (ExprKind == UETT_VecStep)
3913     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3914 
3915   // Whitelist some types as extensions
3916   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3917                                       ExprKind))
3918     return false;
3919 
3920   if (RequireCompleteType(OpLoc, ExprType,
3921                           diag::err_sizeof_alignof_incomplete_type,
3922                           ExprKind, ExprRange))
3923     return true;
3924 
3925   if (ExprType->isFunctionType()) {
3926     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3927       << ExprKind << ExprRange;
3928     return true;
3929   }
3930 
3931   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3932                                        ExprKind))
3933     return true;
3934 
3935   return false;
3936 }
3937 
3938 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3939   E = E->IgnoreParens();
3940 
3941   // Cannot know anything else if the expression is dependent.
3942   if (E->isTypeDependent())
3943     return false;
3944 
3945   if (E->getObjectKind() == OK_BitField) {
3946     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3947        << 1 << E->getSourceRange();
3948     return true;
3949   }
3950 
3951   ValueDecl *D = nullptr;
3952   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3953     D = DRE->getDecl();
3954   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3955     D = ME->getMemberDecl();
3956   }
3957 
3958   // If it's a field, require the containing struct to have a
3959   // complete definition so that we can compute the layout.
3960   //
3961   // This can happen in C++11 onwards, either by naming the member
3962   // in a way that is not transformed into a member access expression
3963   // (in an unevaluated operand, for instance), or by naming the member
3964   // in a trailing-return-type.
3965   //
3966   // For the record, since __alignof__ on expressions is a GCC
3967   // extension, GCC seems to permit this but always gives the
3968   // nonsensical answer 0.
3969   //
3970   // We don't really need the layout here --- we could instead just
3971   // directly check for all the appropriate alignment-lowing
3972   // attributes --- but that would require duplicating a lot of
3973   // logic that just isn't worth duplicating for such a marginal
3974   // use-case.
3975   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3976     // Fast path this check, since we at least know the record has a
3977     // definition if we can find a member of it.
3978     if (!FD->getParent()->isCompleteDefinition()) {
3979       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3980         << E->getSourceRange();
3981       return true;
3982     }
3983 
3984     // Otherwise, if it's a field, and the field doesn't have
3985     // reference type, then it must have a complete type (or be a
3986     // flexible array member, which we explicitly want to
3987     // white-list anyway), which makes the following checks trivial.
3988     if (!FD->getType()->isReferenceType())
3989       return false;
3990   }
3991 
3992   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3993 }
3994 
3995 bool Sema::CheckVecStepExpr(Expr *E) {
3996   E = E->IgnoreParens();
3997 
3998   // Cannot know anything else if the expression is dependent.
3999   if (E->isTypeDependent())
4000     return false;
4001 
4002   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4003 }
4004 
4005 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4006                                         CapturingScopeInfo *CSI) {
4007   assert(T->isVariablyModifiedType());
4008   assert(CSI != nullptr);
4009 
4010   // We're going to walk down into the type and look for VLA expressions.
4011   do {
4012     const Type *Ty = T.getTypePtr();
4013     switch (Ty->getTypeClass()) {
4014 #define TYPE(Class, Base)
4015 #define ABSTRACT_TYPE(Class, Base)
4016 #define NON_CANONICAL_TYPE(Class, Base)
4017 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4018 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4019 #include "clang/AST/TypeNodes.def"
4020       T = QualType();
4021       break;
4022     // These types are never variably-modified.
4023     case Type::Builtin:
4024     case Type::Complex:
4025     case Type::Vector:
4026     case Type::ExtVector:
4027     case Type::Record:
4028     case Type::Enum:
4029     case Type::Elaborated:
4030     case Type::TemplateSpecialization:
4031     case Type::ObjCObject:
4032     case Type::ObjCInterface:
4033     case Type::ObjCObjectPointer:
4034     case Type::ObjCTypeParam:
4035     case Type::Pipe:
4036       llvm_unreachable("type class is never variably-modified!");
4037     case Type::Adjusted:
4038       T = cast<AdjustedType>(Ty)->getOriginalType();
4039       break;
4040     case Type::Decayed:
4041       T = cast<DecayedType>(Ty)->getPointeeType();
4042       break;
4043     case Type::Pointer:
4044       T = cast<PointerType>(Ty)->getPointeeType();
4045       break;
4046     case Type::BlockPointer:
4047       T = cast<BlockPointerType>(Ty)->getPointeeType();
4048       break;
4049     case Type::LValueReference:
4050     case Type::RValueReference:
4051       T = cast<ReferenceType>(Ty)->getPointeeType();
4052       break;
4053     case Type::MemberPointer:
4054       T = cast<MemberPointerType>(Ty)->getPointeeType();
4055       break;
4056     case Type::ConstantArray:
4057     case Type::IncompleteArray:
4058       // Losing element qualification here is fine.
4059       T = cast<ArrayType>(Ty)->getElementType();
4060       break;
4061     case Type::VariableArray: {
4062       // Losing element qualification here is fine.
4063       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4064 
4065       // Unknown size indication requires no size computation.
4066       // Otherwise, evaluate and record it.
4067       if (auto Size = VAT->getSizeExpr()) {
4068         if (!CSI->isVLATypeCaptured(VAT)) {
4069           RecordDecl *CapRecord = nullptr;
4070           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
4071             CapRecord = LSI->Lambda;
4072           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
4073             CapRecord = CRSI->TheRecordDecl;
4074           }
4075           if (CapRecord) {
4076             auto ExprLoc = Size->getExprLoc();
4077             auto SizeType = Context.getSizeType();
4078             // Build the non-static data member.
4079             auto Field =
4080                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
4081                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
4082                                   /*BW*/ nullptr, /*Mutable*/ false,
4083                                   /*InitStyle*/ ICIS_NoInit);
4084             Field->setImplicit(true);
4085             Field->setAccess(AS_private);
4086             Field->setCapturedVLAType(VAT);
4087             CapRecord->addDecl(Field);
4088 
4089             CSI->addVLATypeCapture(ExprLoc, SizeType);
4090           }
4091         }
4092       }
4093       T = VAT->getElementType();
4094       break;
4095     }
4096     case Type::FunctionProto:
4097     case Type::FunctionNoProto:
4098       T = cast<FunctionType>(Ty)->getReturnType();
4099       break;
4100     case Type::Paren:
4101     case Type::TypeOf:
4102     case Type::UnaryTransform:
4103     case Type::Attributed:
4104     case Type::SubstTemplateTypeParm:
4105     case Type::PackExpansion:
4106       // Keep walking after single level desugaring.
4107       T = T.getSingleStepDesugaredType(Context);
4108       break;
4109     case Type::Typedef:
4110       T = cast<TypedefType>(Ty)->desugar();
4111       break;
4112     case Type::Decltype:
4113       T = cast<DecltypeType>(Ty)->desugar();
4114       break;
4115     case Type::Auto:
4116     case Type::DeducedTemplateSpecialization:
4117       T = cast<DeducedType>(Ty)->getDeducedType();
4118       break;
4119     case Type::TypeOfExpr:
4120       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4121       break;
4122     case Type::Atomic:
4123       T = cast<AtomicType>(Ty)->getValueType();
4124       break;
4125     }
4126   } while (!T.isNull() && T->isVariablyModifiedType());
4127 }
4128 
4129 /// Build a sizeof or alignof expression given a type operand.
4130 ExprResult
4131 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4132                                      SourceLocation OpLoc,
4133                                      UnaryExprOrTypeTrait ExprKind,
4134                                      SourceRange R) {
4135   if (!TInfo)
4136     return ExprError();
4137 
4138   QualType T = TInfo->getType();
4139 
4140   if (!T->isDependentType() &&
4141       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4142     return ExprError();
4143 
4144   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4145     if (auto *TT = T->getAs<TypedefType>()) {
4146       for (auto I = FunctionScopes.rbegin(),
4147                 E = std::prev(FunctionScopes.rend());
4148            I != E; ++I) {
4149         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4150         if (CSI == nullptr)
4151           break;
4152         DeclContext *DC = nullptr;
4153         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4154           DC = LSI->CallOperator;
4155         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4156           DC = CRSI->TheCapturedDecl;
4157         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4158           DC = BSI->TheDecl;
4159         if (DC) {
4160           if (DC->containsDecl(TT->getDecl()))
4161             break;
4162           captureVariablyModifiedType(Context, T, CSI);
4163         }
4164       }
4165     }
4166   }
4167 
4168   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4169   return new (Context) UnaryExprOrTypeTraitExpr(
4170       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4171 }
4172 
4173 /// Build a sizeof or alignof expression given an expression
4174 /// operand.
4175 ExprResult
4176 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4177                                      UnaryExprOrTypeTrait ExprKind) {
4178   ExprResult PE = CheckPlaceholderExpr(E);
4179   if (PE.isInvalid())
4180     return ExprError();
4181 
4182   E = PE.get();
4183 
4184   // Verify that the operand is valid.
4185   bool isInvalid = false;
4186   if (E->isTypeDependent()) {
4187     // Delay type-checking for type-dependent expressions.
4188   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4189     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4190   } else if (ExprKind == UETT_VecStep) {
4191     isInvalid = CheckVecStepExpr(E);
4192   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4193       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4194       isInvalid = true;
4195   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4196     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4197     isInvalid = true;
4198   } else {
4199     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4200   }
4201 
4202   if (isInvalid)
4203     return ExprError();
4204 
4205   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4206     PE = TransformToPotentiallyEvaluated(E);
4207     if (PE.isInvalid()) return ExprError();
4208     E = PE.get();
4209   }
4210 
4211   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4212   return new (Context) UnaryExprOrTypeTraitExpr(
4213       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4214 }
4215 
4216 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4217 /// expr and the same for @c alignof and @c __alignof
4218 /// Note that the ArgRange is invalid if isType is false.
4219 ExprResult
4220 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4221                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4222                                     void *TyOrEx, SourceRange ArgRange) {
4223   // If error parsing type, ignore.
4224   if (!TyOrEx) return ExprError();
4225 
4226   if (IsType) {
4227     TypeSourceInfo *TInfo;
4228     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4229     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4230   }
4231 
4232   Expr *ArgEx = (Expr *)TyOrEx;
4233   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4234   return Result;
4235 }
4236 
4237 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4238                                      bool IsReal) {
4239   if (V.get()->isTypeDependent())
4240     return S.Context.DependentTy;
4241 
4242   // _Real and _Imag are only l-values for normal l-values.
4243   if (V.get()->getObjectKind() != OK_Ordinary) {
4244     V = S.DefaultLvalueConversion(V.get());
4245     if (V.isInvalid())
4246       return QualType();
4247   }
4248 
4249   // These operators return the element type of a complex type.
4250   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4251     return CT->getElementType();
4252 
4253   // Otherwise they pass through real integer and floating point types here.
4254   if (V.get()->getType()->isArithmeticType())
4255     return V.get()->getType();
4256 
4257   // Test for placeholders.
4258   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4259   if (PR.isInvalid()) return QualType();
4260   if (PR.get() != V.get()) {
4261     V = PR;
4262     return CheckRealImagOperand(S, V, Loc, IsReal);
4263   }
4264 
4265   // Reject anything else.
4266   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4267     << (IsReal ? "__real" : "__imag");
4268   return QualType();
4269 }
4270 
4271 
4272 
4273 ExprResult
4274 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4275                           tok::TokenKind Kind, Expr *Input) {
4276   UnaryOperatorKind Opc;
4277   switch (Kind) {
4278   default: llvm_unreachable("Unknown unary op!");
4279   case tok::plusplus:   Opc = UO_PostInc; break;
4280   case tok::minusminus: Opc = UO_PostDec; break;
4281   }
4282 
4283   // Since this might is a postfix expression, get rid of ParenListExprs.
4284   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4285   if (Result.isInvalid()) return ExprError();
4286   Input = Result.get();
4287 
4288   return BuildUnaryOp(S, OpLoc, Opc, Input);
4289 }
4290 
4291 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4292 ///
4293 /// \return true on error
4294 static bool checkArithmeticOnObjCPointer(Sema &S,
4295                                          SourceLocation opLoc,
4296                                          Expr *op) {
4297   assert(op->getType()->isObjCObjectPointerType());
4298   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4299       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4300     return false;
4301 
4302   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4303     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4304     << op->getSourceRange();
4305   return true;
4306 }
4307 
4308 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4309   auto *BaseNoParens = Base->IgnoreParens();
4310   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4311     return MSProp->getPropertyDecl()->getType()->isArrayType();
4312   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4313 }
4314 
4315 ExprResult
4316 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4317                               Expr *idx, SourceLocation rbLoc) {
4318   if (base && !base->getType().isNull() &&
4319       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4320     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4321                                     /*Length=*/nullptr, rbLoc);
4322 
4323   // Since this might be a postfix expression, get rid of ParenListExprs.
4324   if (isa<ParenListExpr>(base)) {
4325     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4326     if (result.isInvalid()) return ExprError();
4327     base = result.get();
4328   }
4329 
4330   // Handle any non-overload placeholder types in the base and index
4331   // expressions.  We can't handle overloads here because the other
4332   // operand might be an overloadable type, in which case the overload
4333   // resolution for the operator overload should get the first crack
4334   // at the overload.
4335   bool IsMSPropertySubscript = false;
4336   if (base->getType()->isNonOverloadPlaceholderType()) {
4337     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4338     if (!IsMSPropertySubscript) {
4339       ExprResult result = CheckPlaceholderExpr(base);
4340       if (result.isInvalid())
4341         return ExprError();
4342       base = result.get();
4343     }
4344   }
4345   if (idx->getType()->isNonOverloadPlaceholderType()) {
4346     ExprResult result = CheckPlaceholderExpr(idx);
4347     if (result.isInvalid()) return ExprError();
4348     idx = result.get();
4349   }
4350 
4351   // Build an unanalyzed expression if either operand is type-dependent.
4352   if (getLangOpts().CPlusPlus &&
4353       (base->isTypeDependent() || idx->isTypeDependent())) {
4354     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4355                                             VK_LValue, OK_Ordinary, rbLoc);
4356   }
4357 
4358   // MSDN, property (C++)
4359   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4360   // This attribute can also be used in the declaration of an empty array in a
4361   // class or structure definition. For example:
4362   // __declspec(property(get=GetX, put=PutX)) int x[];
4363   // The above statement indicates that x[] can be used with one or more array
4364   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4365   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4366   if (IsMSPropertySubscript) {
4367     // Build MS property subscript expression if base is MS property reference
4368     // or MS property subscript.
4369     return new (Context) MSPropertySubscriptExpr(
4370         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4371   }
4372 
4373   // Use C++ overloaded-operator rules if either operand has record
4374   // type.  The spec says to do this if either type is *overloadable*,
4375   // but enum types can't declare subscript operators or conversion
4376   // operators, so there's nothing interesting for overload resolution
4377   // to do if there aren't any record types involved.
4378   //
4379   // ObjC pointers have their own subscripting logic that is not tied
4380   // to overload resolution and so should not take this path.
4381   if (getLangOpts().CPlusPlus &&
4382       (base->getType()->isRecordType() ||
4383        (!base->getType()->isObjCObjectPointerType() &&
4384         idx->getType()->isRecordType()))) {
4385     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4386   }
4387 
4388   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4389 
4390   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4391     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4392 
4393   return Res;
4394 }
4395 
4396 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4397   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4398   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4399 
4400   // For expressions like `&(*s).b`, the base is recorded and what should be
4401   // checked.
4402   const MemberExpr *Member = nullptr;
4403   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4404     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4405 
4406   LastRecord.PossibleDerefs.erase(StrippedExpr);
4407 }
4408 
4409 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4410   QualType ResultTy = E->getType();
4411   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4412 
4413   // Bail if the element is an array since it is not memory access.
4414   if (isa<ArrayType>(ResultTy))
4415     return;
4416 
4417   if (ResultTy->hasAttr(attr::NoDeref)) {
4418     LastRecord.PossibleDerefs.insert(E);
4419     return;
4420   }
4421 
4422   // Check if the base type is a pointer to a member access of a struct
4423   // marked with noderef.
4424   const Expr *Base = E->getBase();
4425   QualType BaseTy = Base->getType();
4426   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4427     // Not a pointer access
4428     return;
4429 
4430   const MemberExpr *Member = nullptr;
4431   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4432          Member->isArrow())
4433     Base = Member->getBase();
4434 
4435   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4436     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4437       LastRecord.PossibleDerefs.insert(E);
4438   }
4439 }
4440 
4441 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4442                                           Expr *LowerBound,
4443                                           SourceLocation ColonLoc, Expr *Length,
4444                                           SourceLocation RBLoc) {
4445   if (Base->getType()->isPlaceholderType() &&
4446       !Base->getType()->isSpecificPlaceholderType(
4447           BuiltinType::OMPArraySection)) {
4448     ExprResult Result = CheckPlaceholderExpr(Base);
4449     if (Result.isInvalid())
4450       return ExprError();
4451     Base = Result.get();
4452   }
4453   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4454     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4455     if (Result.isInvalid())
4456       return ExprError();
4457     Result = DefaultLvalueConversion(Result.get());
4458     if (Result.isInvalid())
4459       return ExprError();
4460     LowerBound = Result.get();
4461   }
4462   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4463     ExprResult Result = CheckPlaceholderExpr(Length);
4464     if (Result.isInvalid())
4465       return ExprError();
4466     Result = DefaultLvalueConversion(Result.get());
4467     if (Result.isInvalid())
4468       return ExprError();
4469     Length = Result.get();
4470   }
4471 
4472   // Build an unanalyzed expression if either operand is type-dependent.
4473   if (Base->isTypeDependent() ||
4474       (LowerBound &&
4475        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4476       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4477     return new (Context)
4478         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4479                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4480   }
4481 
4482   // Perform default conversions.
4483   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4484   QualType ResultTy;
4485   if (OriginalTy->isAnyPointerType()) {
4486     ResultTy = OriginalTy->getPointeeType();
4487   } else if (OriginalTy->isArrayType()) {
4488     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4489   } else {
4490     return ExprError(
4491         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4492         << Base->getSourceRange());
4493   }
4494   // C99 6.5.2.1p1
4495   if (LowerBound) {
4496     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4497                                                       LowerBound);
4498     if (Res.isInvalid())
4499       return ExprError(Diag(LowerBound->getExprLoc(),
4500                             diag::err_omp_typecheck_section_not_integer)
4501                        << 0 << LowerBound->getSourceRange());
4502     LowerBound = Res.get();
4503 
4504     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4505         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4506       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4507           << 0 << LowerBound->getSourceRange();
4508   }
4509   if (Length) {
4510     auto Res =
4511         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4512     if (Res.isInvalid())
4513       return ExprError(Diag(Length->getExprLoc(),
4514                             diag::err_omp_typecheck_section_not_integer)
4515                        << 1 << Length->getSourceRange());
4516     Length = Res.get();
4517 
4518     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4519         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4520       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4521           << 1 << Length->getSourceRange();
4522   }
4523 
4524   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4525   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4526   // type. Note that functions are not objects, and that (in C99 parlance)
4527   // incomplete types are not object types.
4528   if (ResultTy->isFunctionType()) {
4529     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4530         << ResultTy << Base->getSourceRange();
4531     return ExprError();
4532   }
4533 
4534   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4535                           diag::err_omp_section_incomplete_type, Base))
4536     return ExprError();
4537 
4538   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4539     Expr::EvalResult Result;
4540     if (LowerBound->EvaluateAsInt(Result, Context)) {
4541       // OpenMP 4.5, [2.4 Array Sections]
4542       // The array section must be a subset of the original array.
4543       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4544       if (LowerBoundValue.isNegative()) {
4545         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4546             << LowerBound->getSourceRange();
4547         return ExprError();
4548       }
4549     }
4550   }
4551 
4552   if (Length) {
4553     Expr::EvalResult Result;
4554     if (Length->EvaluateAsInt(Result, Context)) {
4555       // OpenMP 4.5, [2.4 Array Sections]
4556       // The length must evaluate to non-negative integers.
4557       llvm::APSInt LengthValue = Result.Val.getInt();
4558       if (LengthValue.isNegative()) {
4559         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4560             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4561             << Length->getSourceRange();
4562         return ExprError();
4563       }
4564     }
4565   } else if (ColonLoc.isValid() &&
4566              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4567                                       !OriginalTy->isVariableArrayType()))) {
4568     // OpenMP 4.5, [2.4 Array Sections]
4569     // When the size of the array dimension is not known, the length must be
4570     // specified explicitly.
4571     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4572         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4573     return ExprError();
4574   }
4575 
4576   if (!Base->getType()->isSpecificPlaceholderType(
4577           BuiltinType::OMPArraySection)) {
4578     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4579     if (Result.isInvalid())
4580       return ExprError();
4581     Base = Result.get();
4582   }
4583   return new (Context)
4584       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4585                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4586 }
4587 
4588 ExprResult
4589 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4590                                       Expr *Idx, SourceLocation RLoc) {
4591   Expr *LHSExp = Base;
4592   Expr *RHSExp = Idx;
4593 
4594   ExprValueKind VK = VK_LValue;
4595   ExprObjectKind OK = OK_Ordinary;
4596 
4597   // Per C++ core issue 1213, the result is an xvalue if either operand is
4598   // a non-lvalue array, and an lvalue otherwise.
4599   if (getLangOpts().CPlusPlus11) {
4600     for (auto *Op : {LHSExp, RHSExp}) {
4601       Op = Op->IgnoreImplicit();
4602       if (Op->getType()->isArrayType() && !Op->isLValue())
4603         VK = VK_XValue;
4604     }
4605   }
4606 
4607   // Perform default conversions.
4608   if (!LHSExp->getType()->getAs<VectorType>()) {
4609     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4610     if (Result.isInvalid())
4611       return ExprError();
4612     LHSExp = Result.get();
4613   }
4614   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4615   if (Result.isInvalid())
4616     return ExprError();
4617   RHSExp = Result.get();
4618 
4619   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4620 
4621   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4622   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4623   // in the subscript position. As a result, we need to derive the array base
4624   // and index from the expression types.
4625   Expr *BaseExpr, *IndexExpr;
4626   QualType ResultType;
4627   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4628     BaseExpr = LHSExp;
4629     IndexExpr = RHSExp;
4630     ResultType = Context.DependentTy;
4631   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4632     BaseExpr = LHSExp;
4633     IndexExpr = RHSExp;
4634     ResultType = PTy->getPointeeType();
4635   } else if (const ObjCObjectPointerType *PTy =
4636                LHSTy->getAs<ObjCObjectPointerType>()) {
4637     BaseExpr = LHSExp;
4638     IndexExpr = RHSExp;
4639 
4640     // Use custom logic if this should be the pseudo-object subscript
4641     // expression.
4642     if (!LangOpts.isSubscriptPointerArithmetic())
4643       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4644                                           nullptr);
4645 
4646     ResultType = PTy->getPointeeType();
4647   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4648      // Handle the uncommon case of "123[Ptr]".
4649     BaseExpr = RHSExp;
4650     IndexExpr = LHSExp;
4651     ResultType = PTy->getPointeeType();
4652   } else if (const ObjCObjectPointerType *PTy =
4653                RHSTy->getAs<ObjCObjectPointerType>()) {
4654      // Handle the uncommon case of "123[Ptr]".
4655     BaseExpr = RHSExp;
4656     IndexExpr = LHSExp;
4657     ResultType = PTy->getPointeeType();
4658     if (!LangOpts.isSubscriptPointerArithmetic()) {
4659       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4660         << ResultType << BaseExpr->getSourceRange();
4661       return ExprError();
4662     }
4663   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4664     BaseExpr = LHSExp;    // vectors: V[123]
4665     IndexExpr = RHSExp;
4666     // We apply C++ DR1213 to vector subscripting too.
4667     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4668       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4669       if (Materialized.isInvalid())
4670         return ExprError();
4671       LHSExp = Materialized.get();
4672     }
4673     VK = LHSExp->getValueKind();
4674     if (VK != VK_RValue)
4675       OK = OK_VectorComponent;
4676 
4677     ResultType = VTy->getElementType();
4678     QualType BaseType = BaseExpr->getType();
4679     Qualifiers BaseQuals = BaseType.getQualifiers();
4680     Qualifiers MemberQuals = ResultType.getQualifiers();
4681     Qualifiers Combined = BaseQuals + MemberQuals;
4682     if (Combined != MemberQuals)
4683       ResultType = Context.getQualifiedType(ResultType, Combined);
4684   } else if (LHSTy->isArrayType()) {
4685     // If we see an array that wasn't promoted by
4686     // DefaultFunctionArrayLvalueConversion, it must be an array that
4687     // wasn't promoted because of the C90 rule that doesn't
4688     // allow promoting non-lvalue arrays.  Warn, then
4689     // force the promotion here.
4690     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4691         << LHSExp->getSourceRange();
4692     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4693                                CK_ArrayToPointerDecay).get();
4694     LHSTy = LHSExp->getType();
4695 
4696     BaseExpr = LHSExp;
4697     IndexExpr = RHSExp;
4698     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4699   } else if (RHSTy->isArrayType()) {
4700     // Same as previous, except for 123[f().a] case
4701     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4702         << RHSExp->getSourceRange();
4703     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4704                                CK_ArrayToPointerDecay).get();
4705     RHSTy = RHSExp->getType();
4706 
4707     BaseExpr = RHSExp;
4708     IndexExpr = LHSExp;
4709     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4710   } else {
4711     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4712        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4713   }
4714   // C99 6.5.2.1p1
4715   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4716     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4717                      << IndexExpr->getSourceRange());
4718 
4719   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4720        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4721          && !IndexExpr->isTypeDependent())
4722     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4723 
4724   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4725   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4726   // type. Note that Functions are not objects, and that (in C99 parlance)
4727   // incomplete types are not object types.
4728   if (ResultType->isFunctionType()) {
4729     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4730         << ResultType << BaseExpr->getSourceRange();
4731     return ExprError();
4732   }
4733 
4734   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4735     // GNU extension: subscripting on pointer to void
4736     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4737       << BaseExpr->getSourceRange();
4738 
4739     // C forbids expressions of unqualified void type from being l-values.
4740     // See IsCForbiddenLValueType.
4741     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4742   } else if (!ResultType->isDependentType() &&
4743       RequireCompleteType(LLoc, ResultType,
4744                           diag::err_subscript_incomplete_type, BaseExpr))
4745     return ExprError();
4746 
4747   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4748          !ResultType.isCForbiddenLValueType());
4749 
4750   return new (Context)
4751       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4752 }
4753 
4754 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4755                                   ParmVarDecl *Param) {
4756   if (Param->hasUnparsedDefaultArg()) {
4757     Diag(CallLoc,
4758          diag::err_use_of_default_argument_to_function_declared_later) <<
4759       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4760     Diag(UnparsedDefaultArgLocs[Param],
4761          diag::note_default_argument_declared_here);
4762     return true;
4763   }
4764 
4765   if (Param->hasUninstantiatedDefaultArg()) {
4766     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4767 
4768     EnterExpressionEvaluationContext EvalContext(
4769         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4770 
4771     // Instantiate the expression.
4772     //
4773     // FIXME: Pass in a correct Pattern argument, otherwise
4774     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4775     //
4776     // template<typename T>
4777     // struct A {
4778     //   static int FooImpl();
4779     //
4780     //   template<typename Tp>
4781     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4782     //   // template argument list [[T], [Tp]], should be [[Tp]].
4783     //   friend A<Tp> Foo(int a);
4784     // };
4785     //
4786     // template<typename T>
4787     // A<T> Foo(int a = A<T>::FooImpl());
4788     MultiLevelTemplateArgumentList MutiLevelArgList
4789       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4790 
4791     InstantiatingTemplate Inst(*this, CallLoc, Param,
4792                                MutiLevelArgList.getInnermost());
4793     if (Inst.isInvalid())
4794       return true;
4795     if (Inst.isAlreadyInstantiating()) {
4796       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4797       Param->setInvalidDecl();
4798       return true;
4799     }
4800 
4801     ExprResult Result;
4802     {
4803       // C++ [dcl.fct.default]p5:
4804       //   The names in the [default argument] expression are bound, and
4805       //   the semantic constraints are checked, at the point where the
4806       //   default argument expression appears.
4807       ContextRAII SavedContext(*this, FD);
4808       LocalInstantiationScope Local(*this);
4809       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4810                                 /*DirectInit*/false);
4811     }
4812     if (Result.isInvalid())
4813       return true;
4814 
4815     // Check the expression as an initializer for the parameter.
4816     InitializedEntity Entity
4817       = InitializedEntity::InitializeParameter(Context, Param);
4818     InitializationKind Kind = InitializationKind::CreateCopy(
4819         Param->getLocation(),
4820         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4821     Expr *ResultE = Result.getAs<Expr>();
4822 
4823     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4824     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4825     if (Result.isInvalid())
4826       return true;
4827 
4828     Result =
4829         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4830                             /*DiscardedValue*/ false);
4831     if (Result.isInvalid())
4832       return true;
4833 
4834     // Remember the instantiated default argument.
4835     Param->setDefaultArg(Result.getAs<Expr>());
4836     if (ASTMutationListener *L = getASTMutationListener()) {
4837       L->DefaultArgumentInstantiated(Param);
4838     }
4839   }
4840 
4841   // If the default argument expression is not set yet, we are building it now.
4842   if (!Param->hasInit()) {
4843     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4844     Param->setInvalidDecl();
4845     return true;
4846   }
4847 
4848   // If the default expression creates temporaries, we need to
4849   // push them to the current stack of expression temporaries so they'll
4850   // be properly destroyed.
4851   // FIXME: We should really be rebuilding the default argument with new
4852   // bound temporaries; see the comment in PR5810.
4853   // We don't need to do that with block decls, though, because
4854   // blocks in default argument expression can never capture anything.
4855   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4856     // Set the "needs cleanups" bit regardless of whether there are
4857     // any explicit objects.
4858     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4859 
4860     // Append all the objects to the cleanup list.  Right now, this
4861     // should always be a no-op, because blocks in default argument
4862     // expressions should never be able to capture anything.
4863     assert(!Init->getNumObjects() &&
4864            "default argument expression has capturing blocks?");
4865   }
4866 
4867   // We already type-checked the argument, so we know it works.
4868   // Just mark all of the declarations in this potentially-evaluated expression
4869   // as being "referenced".
4870   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4871                                    /*SkipLocalVariables=*/true);
4872   return false;
4873 }
4874 
4875 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4876                                         FunctionDecl *FD, ParmVarDecl *Param) {
4877   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4878     return ExprError();
4879   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4880 }
4881 
4882 Sema::VariadicCallType
4883 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4884                           Expr *Fn) {
4885   if (Proto && Proto->isVariadic()) {
4886     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4887       return VariadicConstructor;
4888     else if (Fn && Fn->getType()->isBlockPointerType())
4889       return VariadicBlock;
4890     else if (FDecl) {
4891       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4892         if (Method->isInstance())
4893           return VariadicMethod;
4894     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4895       return VariadicMethod;
4896     return VariadicFunction;
4897   }
4898   return VariadicDoesNotApply;
4899 }
4900 
4901 namespace {
4902 class FunctionCallCCC : public FunctionCallFilterCCC {
4903 public:
4904   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4905                   unsigned NumArgs, MemberExpr *ME)
4906       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4907         FunctionName(FuncName) {}
4908 
4909   bool ValidateCandidate(const TypoCorrection &candidate) override {
4910     if (!candidate.getCorrectionSpecifier() ||
4911         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4912       return false;
4913     }
4914 
4915     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4916   }
4917 
4918 private:
4919   const IdentifierInfo *const FunctionName;
4920 };
4921 }
4922 
4923 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4924                                                FunctionDecl *FDecl,
4925                                                ArrayRef<Expr *> Args) {
4926   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4927   DeclarationName FuncName = FDecl->getDeclName();
4928   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4929 
4930   if (TypoCorrection Corrected = S.CorrectTypo(
4931           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4932           S.getScopeForContext(S.CurContext), nullptr,
4933           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4934                                              Args.size(), ME),
4935           Sema::CTK_ErrorRecovery)) {
4936     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4937       if (Corrected.isOverloaded()) {
4938         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4939         OverloadCandidateSet::iterator Best;
4940         for (NamedDecl *CD : Corrected) {
4941           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4942             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4943                                    OCS);
4944         }
4945         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4946         case OR_Success:
4947           ND = Best->FoundDecl;
4948           Corrected.setCorrectionDecl(ND);
4949           break;
4950         default:
4951           break;
4952         }
4953       }
4954       ND = ND->getUnderlyingDecl();
4955       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4956         return Corrected;
4957     }
4958   }
4959   return TypoCorrection();
4960 }
4961 
4962 /// ConvertArgumentsForCall - Converts the arguments specified in
4963 /// Args/NumArgs to the parameter types of the function FDecl with
4964 /// function prototype Proto. Call is the call expression itself, and
4965 /// Fn is the function expression. For a C++ member function, this
4966 /// routine does not attempt to convert the object argument. Returns
4967 /// true if the call is ill-formed.
4968 bool
4969 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4970                               FunctionDecl *FDecl,
4971                               const FunctionProtoType *Proto,
4972                               ArrayRef<Expr *> Args,
4973                               SourceLocation RParenLoc,
4974                               bool IsExecConfig) {
4975   // Bail out early if calling a builtin with custom typechecking.
4976   if (FDecl)
4977     if (unsigned ID = FDecl->getBuiltinID())
4978       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4979         return false;
4980 
4981   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4982   // assignment, to the types of the corresponding parameter, ...
4983   unsigned NumParams = Proto->getNumParams();
4984   bool Invalid = false;
4985   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4986   unsigned FnKind = Fn->getType()->isBlockPointerType()
4987                        ? 1 /* block */
4988                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4989                                        : 0 /* function */);
4990 
4991   // If too few arguments are available (and we don't have default
4992   // arguments for the remaining parameters), don't make the call.
4993   if (Args.size() < NumParams) {
4994     if (Args.size() < MinArgs) {
4995       TypoCorrection TC;
4996       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4997         unsigned diag_id =
4998             MinArgs == NumParams && !Proto->isVariadic()
4999                 ? diag::err_typecheck_call_too_few_args_suggest
5000                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5001         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5002                                         << static_cast<unsigned>(Args.size())
5003                                         << TC.getCorrectionRange());
5004       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5005         Diag(RParenLoc,
5006              MinArgs == NumParams && !Proto->isVariadic()
5007                  ? diag::err_typecheck_call_too_few_args_one
5008                  : diag::err_typecheck_call_too_few_args_at_least_one)
5009             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5010       else
5011         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5012                             ? diag::err_typecheck_call_too_few_args
5013                             : diag::err_typecheck_call_too_few_args_at_least)
5014             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5015             << Fn->getSourceRange();
5016 
5017       // Emit the location of the prototype.
5018       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5019         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5020 
5021       return true;
5022     }
5023     // We reserve space for the default arguments when we create
5024     // the call expression, before calling ConvertArgumentsForCall.
5025     assert((Call->getNumArgs() == NumParams) &&
5026            "We should have reserved space for the default arguments before!");
5027   }
5028 
5029   // If too many are passed and not variadic, error on the extras and drop
5030   // them.
5031   if (Args.size() > NumParams) {
5032     if (!Proto->isVariadic()) {
5033       TypoCorrection TC;
5034       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5035         unsigned diag_id =
5036             MinArgs == NumParams && !Proto->isVariadic()
5037                 ? diag::err_typecheck_call_too_many_args_suggest
5038                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5039         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5040                                         << static_cast<unsigned>(Args.size())
5041                                         << TC.getCorrectionRange());
5042       } else if (NumParams == 1 && FDecl &&
5043                  FDecl->getParamDecl(0)->getDeclName())
5044         Diag(Args[NumParams]->getBeginLoc(),
5045              MinArgs == NumParams
5046                  ? diag::err_typecheck_call_too_many_args_one
5047                  : diag::err_typecheck_call_too_many_args_at_most_one)
5048             << FnKind << FDecl->getParamDecl(0)
5049             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5050             << SourceRange(Args[NumParams]->getBeginLoc(),
5051                            Args.back()->getEndLoc());
5052       else
5053         Diag(Args[NumParams]->getBeginLoc(),
5054              MinArgs == NumParams
5055                  ? diag::err_typecheck_call_too_many_args
5056                  : diag::err_typecheck_call_too_many_args_at_most)
5057             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5058             << Fn->getSourceRange()
5059             << SourceRange(Args[NumParams]->getBeginLoc(),
5060                            Args.back()->getEndLoc());
5061 
5062       // Emit the location of the prototype.
5063       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5064         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5065 
5066       // This deletes the extra arguments.
5067       Call->shrinkNumArgs(NumParams);
5068       return true;
5069     }
5070   }
5071   SmallVector<Expr *, 8> AllArgs;
5072   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5073 
5074   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5075                                    AllArgs, CallType);
5076   if (Invalid)
5077     return true;
5078   unsigned TotalNumArgs = AllArgs.size();
5079   for (unsigned i = 0; i < TotalNumArgs; ++i)
5080     Call->setArg(i, AllArgs[i]);
5081 
5082   return false;
5083 }
5084 
5085 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5086                                   const FunctionProtoType *Proto,
5087                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5088                                   SmallVectorImpl<Expr *> &AllArgs,
5089                                   VariadicCallType CallType, bool AllowExplicit,
5090                                   bool IsListInitialization) {
5091   unsigned NumParams = Proto->getNumParams();
5092   bool Invalid = false;
5093   size_t ArgIx = 0;
5094   // Continue to check argument types (even if we have too few/many args).
5095   for (unsigned i = FirstParam; i < NumParams; i++) {
5096     QualType ProtoArgType = Proto->getParamType(i);
5097 
5098     Expr *Arg;
5099     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5100     if (ArgIx < Args.size()) {
5101       Arg = Args[ArgIx++];
5102 
5103       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5104                               diag::err_call_incomplete_argument, Arg))
5105         return true;
5106 
5107       // Strip the unbridged-cast placeholder expression off, if applicable.
5108       bool CFAudited = false;
5109       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5110           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5111           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5112         Arg = stripARCUnbridgedCast(Arg);
5113       else if (getLangOpts().ObjCAutoRefCount &&
5114                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5115                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5116         CFAudited = true;
5117 
5118       if (Proto->getExtParameterInfo(i).isNoEscape())
5119         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5120           BE->getBlockDecl()->setDoesNotEscape();
5121 
5122       InitializedEntity Entity =
5123           Param ? InitializedEntity::InitializeParameter(Context, Param,
5124                                                          ProtoArgType)
5125                 : InitializedEntity::InitializeParameter(
5126                       Context, ProtoArgType, Proto->isParamConsumed(i));
5127 
5128       // Remember that parameter belongs to a CF audited API.
5129       if (CFAudited)
5130         Entity.setParameterCFAudited();
5131 
5132       ExprResult ArgE = PerformCopyInitialization(
5133           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5134       if (ArgE.isInvalid())
5135         return true;
5136 
5137       Arg = ArgE.getAs<Expr>();
5138     } else {
5139       assert(Param && "can't use default arguments without a known callee");
5140 
5141       ExprResult ArgExpr =
5142         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5143       if (ArgExpr.isInvalid())
5144         return true;
5145 
5146       Arg = ArgExpr.getAs<Expr>();
5147     }
5148 
5149     // Check for array bounds violations for each argument to the call. This
5150     // check only triggers warnings when the argument isn't a more complex Expr
5151     // with its own checking, such as a BinaryOperator.
5152     CheckArrayAccess(Arg);
5153 
5154     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5155     CheckStaticArrayArgument(CallLoc, Param, Arg);
5156 
5157     AllArgs.push_back(Arg);
5158   }
5159 
5160   // If this is a variadic call, handle args passed through "...".
5161   if (CallType != VariadicDoesNotApply) {
5162     // Assume that extern "C" functions with variadic arguments that
5163     // return __unknown_anytype aren't *really* variadic.
5164     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5165         FDecl->isExternC()) {
5166       for (Expr *A : Args.slice(ArgIx)) {
5167         QualType paramType; // ignored
5168         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5169         Invalid |= arg.isInvalid();
5170         AllArgs.push_back(arg.get());
5171       }
5172 
5173     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5174     } else {
5175       for (Expr *A : Args.slice(ArgIx)) {
5176         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5177         Invalid |= Arg.isInvalid();
5178         AllArgs.push_back(Arg.get());
5179       }
5180     }
5181 
5182     // Check for array bounds violations.
5183     for (Expr *A : Args.slice(ArgIx))
5184       CheckArrayAccess(A);
5185   }
5186   return Invalid;
5187 }
5188 
5189 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5190   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5191   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5192     TL = DTL.getOriginalLoc();
5193   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5194     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5195       << ATL.getLocalSourceRange();
5196 }
5197 
5198 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5199 /// array parameter, check that it is non-null, and that if it is formed by
5200 /// array-to-pointer decay, the underlying array is sufficiently large.
5201 ///
5202 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5203 /// array type derivation, then for each call to the function, the value of the
5204 /// corresponding actual argument shall provide access to the first element of
5205 /// an array with at least as many elements as specified by the size expression.
5206 void
5207 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5208                                ParmVarDecl *Param,
5209                                const Expr *ArgExpr) {
5210   // Static array parameters are not supported in C++.
5211   if (!Param || getLangOpts().CPlusPlus)
5212     return;
5213 
5214   QualType OrigTy = Param->getOriginalType();
5215 
5216   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5217   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5218     return;
5219 
5220   if (ArgExpr->isNullPointerConstant(Context,
5221                                      Expr::NPC_NeverValueDependent)) {
5222     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5223     DiagnoseCalleeStaticArrayParam(*this, Param);
5224     return;
5225   }
5226 
5227   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5228   if (!CAT)
5229     return;
5230 
5231   const ConstantArrayType *ArgCAT =
5232     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5233   if (!ArgCAT)
5234     return;
5235 
5236   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5237                                              ArgCAT->getElementType())) {
5238     if (ArgCAT->getSize().ult(CAT->getSize())) {
5239       Diag(CallLoc, diag::warn_static_array_too_small)
5240           << ArgExpr->getSourceRange()
5241           << (unsigned)ArgCAT->getSize().getZExtValue()
5242           << (unsigned)CAT->getSize().getZExtValue() << 0;
5243       DiagnoseCalleeStaticArrayParam(*this, Param);
5244     }
5245     return;
5246   }
5247 
5248   Optional<CharUnits> ArgSize =
5249       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5250   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5251   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5252     Diag(CallLoc, diag::warn_static_array_too_small)
5253         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5254         << (unsigned)ParmSize->getQuantity() << 1;
5255     DiagnoseCalleeStaticArrayParam(*this, Param);
5256   }
5257 }
5258 
5259 /// Given a function expression of unknown-any type, try to rebuild it
5260 /// to have a function type.
5261 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5262 
5263 /// Is the given type a placeholder that we need to lower out
5264 /// immediately during argument processing?
5265 static bool isPlaceholderToRemoveAsArg(QualType type) {
5266   // Placeholders are never sugared.
5267   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5268   if (!placeholder) return false;
5269 
5270   switch (placeholder->getKind()) {
5271   // Ignore all the non-placeholder types.
5272 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5273   case BuiltinType::Id:
5274 #include "clang/Basic/OpenCLImageTypes.def"
5275 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5276   case BuiltinType::Id:
5277 #include "clang/Basic/OpenCLExtensionTypes.def"
5278 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5279 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5280 #include "clang/AST/BuiltinTypes.def"
5281     return false;
5282 
5283   // We cannot lower out overload sets; they might validly be resolved
5284   // by the call machinery.
5285   case BuiltinType::Overload:
5286     return false;
5287 
5288   // Unbridged casts in ARC can be handled in some call positions and
5289   // should be left in place.
5290   case BuiltinType::ARCUnbridgedCast:
5291     return false;
5292 
5293   // Pseudo-objects should be converted as soon as possible.
5294   case BuiltinType::PseudoObject:
5295     return true;
5296 
5297   // The debugger mode could theoretically but currently does not try
5298   // to resolve unknown-typed arguments based on known parameter types.
5299   case BuiltinType::UnknownAny:
5300     return true;
5301 
5302   // These are always invalid as call arguments and should be reported.
5303   case BuiltinType::BoundMember:
5304   case BuiltinType::BuiltinFn:
5305   case BuiltinType::OMPArraySection:
5306     return true;
5307 
5308   }
5309   llvm_unreachable("bad builtin type kind");
5310 }
5311 
5312 /// Check an argument list for placeholders that we won't try to
5313 /// handle later.
5314 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5315   // Apply this processing to all the arguments at once instead of
5316   // dying at the first failure.
5317   bool hasInvalid = false;
5318   for (size_t i = 0, e = args.size(); i != e; i++) {
5319     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5320       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5321       if (result.isInvalid()) hasInvalid = true;
5322       else args[i] = result.get();
5323     } else if (hasInvalid) {
5324       (void)S.CorrectDelayedTyposInExpr(args[i]);
5325     }
5326   }
5327   return hasInvalid;
5328 }
5329 
5330 /// If a builtin function has a pointer argument with no explicit address
5331 /// space, then it should be able to accept a pointer to any address
5332 /// space as input.  In order to do this, we need to replace the
5333 /// standard builtin declaration with one that uses the same address space
5334 /// as the call.
5335 ///
5336 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5337 ///                  it does not contain any pointer arguments without
5338 ///                  an address space qualifer.  Otherwise the rewritten
5339 ///                  FunctionDecl is returned.
5340 /// TODO: Handle pointer return types.
5341 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5342                                                 const FunctionDecl *FDecl,
5343                                                 MultiExprArg ArgExprs) {
5344 
5345   QualType DeclType = FDecl->getType();
5346   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5347 
5348   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5349       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5350     return nullptr;
5351 
5352   bool NeedsNewDecl = false;
5353   unsigned i = 0;
5354   SmallVector<QualType, 8> OverloadParams;
5355 
5356   for (QualType ParamType : FT->param_types()) {
5357 
5358     // Convert array arguments to pointer to simplify type lookup.
5359     ExprResult ArgRes =
5360         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5361     if (ArgRes.isInvalid())
5362       return nullptr;
5363     Expr *Arg = ArgRes.get();
5364     QualType ArgType = Arg->getType();
5365     if (!ParamType->isPointerType() ||
5366         ParamType.getQualifiers().hasAddressSpace() ||
5367         !ArgType->isPointerType() ||
5368         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5369       OverloadParams.push_back(ParamType);
5370       continue;
5371     }
5372 
5373     QualType PointeeType = ParamType->getPointeeType();
5374     if (PointeeType.getQualifiers().hasAddressSpace())
5375       continue;
5376 
5377     NeedsNewDecl = true;
5378     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5379 
5380     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5381     OverloadParams.push_back(Context.getPointerType(PointeeType));
5382   }
5383 
5384   if (!NeedsNewDecl)
5385     return nullptr;
5386 
5387   FunctionProtoType::ExtProtoInfo EPI;
5388   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5389                                                 OverloadParams, EPI);
5390   DeclContext *Parent = Context.getTranslationUnitDecl();
5391   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5392                                                     FDecl->getLocation(),
5393                                                     FDecl->getLocation(),
5394                                                     FDecl->getIdentifier(),
5395                                                     OverloadTy,
5396                                                     /*TInfo=*/nullptr,
5397                                                     SC_Extern, false,
5398                                                     /*hasPrototype=*/true);
5399   SmallVector<ParmVarDecl*, 16> Params;
5400   FT = cast<FunctionProtoType>(OverloadTy);
5401   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5402     QualType ParamType = FT->getParamType(i);
5403     ParmVarDecl *Parm =
5404         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5405                                 SourceLocation(), nullptr, ParamType,
5406                                 /*TInfo=*/nullptr, SC_None, nullptr);
5407     Parm->setScopeInfo(0, i);
5408     Params.push_back(Parm);
5409   }
5410   OverloadDecl->setParams(Params);
5411   return OverloadDecl;
5412 }
5413 
5414 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5415                                     FunctionDecl *Callee,
5416                                     MultiExprArg ArgExprs) {
5417   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5418   // similar attributes) really don't like it when functions are called with an
5419   // invalid number of args.
5420   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5421                          /*PartialOverloading=*/false) &&
5422       !Callee->isVariadic())
5423     return;
5424   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5425     return;
5426 
5427   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5428     S.Diag(Fn->getBeginLoc(),
5429            isa<CXXMethodDecl>(Callee)
5430                ? diag::err_ovl_no_viable_member_function_in_call
5431                : diag::err_ovl_no_viable_function_in_call)
5432         << Callee << Callee->getSourceRange();
5433     S.Diag(Callee->getLocation(),
5434            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5435         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5436     return;
5437   }
5438 }
5439 
5440 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5441     const UnresolvedMemberExpr *const UME, Sema &S) {
5442 
5443   const auto GetFunctionLevelDCIfCXXClass =
5444       [](Sema &S) -> const CXXRecordDecl * {
5445     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5446     if (!DC || !DC->getParent())
5447       return nullptr;
5448 
5449     // If the call to some member function was made from within a member
5450     // function body 'M' return return 'M's parent.
5451     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5452       return MD->getParent()->getCanonicalDecl();
5453     // else the call was made from within a default member initializer of a
5454     // class, so return the class.
5455     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5456       return RD->getCanonicalDecl();
5457     return nullptr;
5458   };
5459   // If our DeclContext is neither a member function nor a class (in the
5460   // case of a lambda in a default member initializer), we can't have an
5461   // enclosing 'this'.
5462 
5463   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5464   if (!CurParentClass)
5465     return false;
5466 
5467   // The naming class for implicit member functions call is the class in which
5468   // name lookup starts.
5469   const CXXRecordDecl *const NamingClass =
5470       UME->getNamingClass()->getCanonicalDecl();
5471   assert(NamingClass && "Must have naming class even for implicit access");
5472 
5473   // If the unresolved member functions were found in a 'naming class' that is
5474   // related (either the same or derived from) to the class that contains the
5475   // member function that itself contained the implicit member access.
5476 
5477   return CurParentClass == NamingClass ||
5478          CurParentClass->isDerivedFrom(NamingClass);
5479 }
5480 
5481 static void
5482 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5483     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5484 
5485   if (!UME)
5486     return;
5487 
5488   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5489   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5490   // already been captured, or if this is an implicit member function call (if
5491   // it isn't, an attempt to capture 'this' should already have been made).
5492   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5493       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5494     return;
5495 
5496   // Check if the naming class in which the unresolved members were found is
5497   // related (same as or is a base of) to the enclosing class.
5498 
5499   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5500     return;
5501 
5502 
5503   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5504   // If the enclosing function is not dependent, then this lambda is
5505   // capture ready, so if we can capture this, do so.
5506   if (!EnclosingFunctionCtx->isDependentContext()) {
5507     // If the current lambda and all enclosing lambdas can capture 'this' -
5508     // then go ahead and capture 'this' (since our unresolved overload set
5509     // contains at least one non-static member function).
5510     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5511       S.CheckCXXThisCapture(CallLoc);
5512   } else if (S.CurContext->isDependentContext()) {
5513     // ... since this is an implicit member reference, that might potentially
5514     // involve a 'this' capture, mark 'this' for potential capture in
5515     // enclosing lambdas.
5516     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5517       CurLSI->addPotentialThisCapture(CallLoc);
5518   }
5519 }
5520 
5521 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5522 /// This provides the location of the left/right parens and a list of comma
5523 /// locations.
5524 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5525                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5526                                Expr *ExecConfig, bool IsExecConfig) {
5527   // Since this might be a postfix expression, get rid of ParenListExprs.
5528   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5529   if (Result.isInvalid()) return ExprError();
5530   Fn = Result.get();
5531 
5532   if (checkArgsForPlaceholders(*this, ArgExprs))
5533     return ExprError();
5534 
5535   if (getLangOpts().CPlusPlus) {
5536     // If this is a pseudo-destructor expression, build the call immediately.
5537     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5538       if (!ArgExprs.empty()) {
5539         // Pseudo-destructor calls should not have any arguments.
5540         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5541             << FixItHint::CreateRemoval(
5542                    SourceRange(ArgExprs.front()->getBeginLoc(),
5543                                ArgExprs.back()->getEndLoc()));
5544       }
5545 
5546       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5547                               VK_RValue, RParenLoc);
5548     }
5549     if (Fn->getType() == Context.PseudoObjectTy) {
5550       ExprResult result = CheckPlaceholderExpr(Fn);
5551       if (result.isInvalid()) return ExprError();
5552       Fn = result.get();
5553     }
5554 
5555     // Determine whether this is a dependent call inside a C++ template,
5556     // in which case we won't do any semantic analysis now.
5557     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5558       if (ExecConfig) {
5559         return CUDAKernelCallExpr::Create(
5560             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5561             Context.DependentTy, VK_RValue, RParenLoc);
5562       } else {
5563 
5564         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5565             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5566             Fn->getBeginLoc());
5567 
5568         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5569                                 VK_RValue, RParenLoc);
5570       }
5571     }
5572 
5573     // Determine whether this is a call to an object (C++ [over.call.object]).
5574     if (Fn->getType()->isRecordType())
5575       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5576                                           RParenLoc);
5577 
5578     if (Fn->getType() == Context.UnknownAnyTy) {
5579       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5580       if (result.isInvalid()) return ExprError();
5581       Fn = result.get();
5582     }
5583 
5584     if (Fn->getType() == Context.BoundMemberTy) {
5585       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5586                                        RParenLoc);
5587     }
5588   }
5589 
5590   // Check for overloaded calls.  This can happen even in C due to extensions.
5591   if (Fn->getType() == Context.OverloadTy) {
5592     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5593 
5594     // We aren't supposed to apply this logic if there's an '&' involved.
5595     if (!find.HasFormOfMemberPointer) {
5596       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5597         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5598                                 VK_RValue, RParenLoc);
5599       OverloadExpr *ovl = find.Expression;
5600       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5601         return BuildOverloadedCallExpr(
5602             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5603             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5604       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5605                                        RParenLoc);
5606     }
5607   }
5608 
5609   // If we're directly calling a function, get the appropriate declaration.
5610   if (Fn->getType() == Context.UnknownAnyTy) {
5611     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5612     if (result.isInvalid()) return ExprError();
5613     Fn = result.get();
5614   }
5615 
5616   Expr *NakedFn = Fn->IgnoreParens();
5617 
5618   bool CallingNDeclIndirectly = false;
5619   NamedDecl *NDecl = nullptr;
5620   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5621     if (UnOp->getOpcode() == UO_AddrOf) {
5622       CallingNDeclIndirectly = true;
5623       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5624     }
5625   }
5626 
5627   if (isa<DeclRefExpr>(NakedFn)) {
5628     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5629 
5630     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5631     if (FDecl && FDecl->getBuiltinID()) {
5632       // Rewrite the function decl for this builtin by replacing parameters
5633       // with no explicit address space with the address space of the arguments
5634       // in ArgExprs.
5635       if ((FDecl =
5636                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5637         NDecl = FDecl;
5638         Fn = DeclRefExpr::Create(
5639             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5640             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5641       }
5642     }
5643   } else if (isa<MemberExpr>(NakedFn))
5644     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5645 
5646   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5647     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5648                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5649       return ExprError();
5650 
5651     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5652       return ExprError();
5653 
5654     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5655   }
5656 
5657   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5658                                ExecConfig, IsExecConfig);
5659 }
5660 
5661 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5662 ///
5663 /// __builtin_astype( value, dst type )
5664 ///
5665 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5666                                  SourceLocation BuiltinLoc,
5667                                  SourceLocation RParenLoc) {
5668   ExprValueKind VK = VK_RValue;
5669   ExprObjectKind OK = OK_Ordinary;
5670   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5671   QualType SrcTy = E->getType();
5672   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5673     return ExprError(Diag(BuiltinLoc,
5674                           diag::err_invalid_astype_of_different_size)
5675                      << DstTy
5676                      << SrcTy
5677                      << E->getSourceRange());
5678   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5679 }
5680 
5681 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5682 /// provided arguments.
5683 ///
5684 /// __builtin_convertvector( value, dst type )
5685 ///
5686 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5687                                         SourceLocation BuiltinLoc,
5688                                         SourceLocation RParenLoc) {
5689   TypeSourceInfo *TInfo;
5690   GetTypeFromParser(ParsedDestTy, &TInfo);
5691   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5692 }
5693 
5694 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5695 /// i.e. an expression not of \p OverloadTy.  The expression should
5696 /// unary-convert to an expression of function-pointer or
5697 /// block-pointer type.
5698 ///
5699 /// \param NDecl the declaration being called, if available
5700 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5701                                        SourceLocation LParenLoc,
5702                                        ArrayRef<Expr *> Args,
5703                                        SourceLocation RParenLoc, Expr *Config,
5704                                        bool IsExecConfig, ADLCallKind UsesADL) {
5705   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5706   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5707 
5708   // Functions with 'interrupt' attribute cannot be called directly.
5709   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5710     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5711     return ExprError();
5712   }
5713 
5714   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5715   // so there's some risk when calling out to non-interrupt handler functions
5716   // that the callee might not preserve them. This is easy to diagnose here,
5717   // but can be very challenging to debug.
5718   if (auto *Caller = getCurFunctionDecl())
5719     if (Caller->hasAttr<ARMInterruptAttr>()) {
5720       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5721       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5722         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5723     }
5724 
5725   // Promote the function operand.
5726   // We special-case function promotion here because we only allow promoting
5727   // builtin functions to function pointers in the callee of a call.
5728   ExprResult Result;
5729   QualType ResultTy;
5730   if (BuiltinID &&
5731       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5732     // Extract the return type from the (builtin) function pointer type.
5733     // FIXME Several builtins still have setType in
5734     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5735     // Builtins.def to ensure they are correct before removing setType calls.
5736     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5737     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5738     ResultTy = FDecl->getCallResultType();
5739   } else {
5740     Result = CallExprUnaryConversions(Fn);
5741     ResultTy = Context.BoolTy;
5742   }
5743   if (Result.isInvalid())
5744     return ExprError();
5745   Fn = Result.get();
5746 
5747   // Check for a valid function type, but only if it is not a builtin which
5748   // requires custom type checking. These will be handled by
5749   // CheckBuiltinFunctionCall below just after creation of the call expression.
5750   const FunctionType *FuncT = nullptr;
5751   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5752    retry:
5753     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5754       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5755       // have type pointer to function".
5756       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5757       if (!FuncT)
5758         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5759                            << Fn->getType() << Fn->getSourceRange());
5760     } else if (const BlockPointerType *BPT =
5761                  Fn->getType()->getAs<BlockPointerType>()) {
5762       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5763     } else {
5764       // Handle calls to expressions of unknown-any type.
5765       if (Fn->getType() == Context.UnknownAnyTy) {
5766         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5767         if (rewrite.isInvalid()) return ExprError();
5768         Fn = rewrite.get();
5769         goto retry;
5770       }
5771 
5772     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5773       << Fn->getType() << Fn->getSourceRange());
5774     }
5775   }
5776 
5777   // Get the number of parameters in the function prototype, if any.
5778   // We will allocate space for max(Args.size(), NumParams) arguments
5779   // in the call expression.
5780   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5781   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5782 
5783   CallExpr *TheCall;
5784   if (Config) {
5785     assert(UsesADL == ADLCallKind::NotADL &&
5786            "CUDAKernelCallExpr should not use ADL");
5787     TheCall =
5788         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5789                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5790   } else {
5791     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5792                                RParenLoc, NumParams, UsesADL);
5793   }
5794 
5795   if (!getLangOpts().CPlusPlus) {
5796     // Forget about the nulled arguments since typo correction
5797     // do not handle them well.
5798     TheCall->shrinkNumArgs(Args.size());
5799     // C cannot always handle TypoExpr nodes in builtin calls and direct
5800     // function calls as their argument checking don't necessarily handle
5801     // dependent types properly, so make sure any TypoExprs have been
5802     // dealt with.
5803     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5804     if (!Result.isUsable()) return ExprError();
5805     CallExpr *TheOldCall = TheCall;
5806     TheCall = dyn_cast<CallExpr>(Result.get());
5807     bool CorrectedTypos = TheCall != TheOldCall;
5808     if (!TheCall) return Result;
5809     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5810 
5811     // A new call expression node was created if some typos were corrected.
5812     // However it may not have been constructed with enough storage. In this
5813     // case, rebuild the node with enough storage. The waste of space is
5814     // immaterial since this only happens when some typos were corrected.
5815     if (CorrectedTypos && Args.size() < NumParams) {
5816       if (Config)
5817         TheCall = CUDAKernelCallExpr::Create(
5818             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5819             RParenLoc, NumParams);
5820       else
5821         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5822                                    RParenLoc, NumParams, UsesADL);
5823     }
5824     // We can now handle the nulled arguments for the default arguments.
5825     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5826   }
5827 
5828   // Bail out early if calling a builtin with custom type checking.
5829   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5830     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5831 
5832   if (getLangOpts().CUDA) {
5833     if (Config) {
5834       // CUDA: Kernel calls must be to global functions
5835       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5836         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5837             << FDecl << Fn->getSourceRange());
5838 
5839       // CUDA: Kernel function must have 'void' return type
5840       if (!FuncT->getReturnType()->isVoidType())
5841         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5842             << Fn->getType() << Fn->getSourceRange());
5843     } else {
5844       // CUDA: Calls to global functions must be configured
5845       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5846         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5847             << FDecl << Fn->getSourceRange());
5848     }
5849   }
5850 
5851   // Check for a valid return type
5852   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5853                           FDecl))
5854     return ExprError();
5855 
5856   // We know the result type of the call, set it.
5857   TheCall->setType(FuncT->getCallResultType(Context));
5858   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5859 
5860   if (Proto) {
5861     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5862                                 IsExecConfig))
5863       return ExprError();
5864   } else {
5865     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5866 
5867     if (FDecl) {
5868       // Check if we have too few/too many template arguments, based
5869       // on our knowledge of the function definition.
5870       const FunctionDecl *Def = nullptr;
5871       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5872         Proto = Def->getType()->getAs<FunctionProtoType>();
5873        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5874           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5875           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5876       }
5877 
5878       // If the function we're calling isn't a function prototype, but we have
5879       // a function prototype from a prior declaratiom, use that prototype.
5880       if (!FDecl->hasPrototype())
5881         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5882     }
5883 
5884     // Promote the arguments (C99 6.5.2.2p6).
5885     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5886       Expr *Arg = Args[i];
5887 
5888       if (Proto && i < Proto->getNumParams()) {
5889         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5890             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5891         ExprResult ArgE =
5892             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5893         if (ArgE.isInvalid())
5894           return true;
5895 
5896         Arg = ArgE.getAs<Expr>();
5897 
5898       } else {
5899         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5900 
5901         if (ArgE.isInvalid())
5902           return true;
5903 
5904         Arg = ArgE.getAs<Expr>();
5905       }
5906 
5907       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5908                               diag::err_call_incomplete_argument, Arg))
5909         return ExprError();
5910 
5911       TheCall->setArg(i, Arg);
5912     }
5913   }
5914 
5915   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5916     if (!Method->isStatic())
5917       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5918         << Fn->getSourceRange());
5919 
5920   // Check for sentinels
5921   if (NDecl)
5922     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5923 
5924   // Do special checking on direct calls to functions.
5925   if (FDecl) {
5926     if (CheckFunctionCall(FDecl, TheCall, Proto))
5927       return ExprError();
5928 
5929     if (BuiltinID)
5930       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5931   } else if (NDecl) {
5932     if (CheckPointerCall(NDecl, TheCall, Proto))
5933       return ExprError();
5934   } else {
5935     if (CheckOtherCall(TheCall, Proto))
5936       return ExprError();
5937   }
5938 
5939   return MaybeBindToTemporary(TheCall);
5940 }
5941 
5942 ExprResult
5943 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5944                            SourceLocation RParenLoc, Expr *InitExpr) {
5945   assert(Ty && "ActOnCompoundLiteral(): missing type");
5946   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5947 
5948   TypeSourceInfo *TInfo;
5949   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5950   if (!TInfo)
5951     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5952 
5953   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5954 }
5955 
5956 ExprResult
5957 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5958                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5959   QualType literalType = TInfo->getType();
5960 
5961   if (literalType->isArrayType()) {
5962     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5963           diag::err_illegal_decl_array_incomplete_type,
5964           SourceRange(LParenLoc,
5965                       LiteralExpr->getSourceRange().getEnd())))
5966       return ExprError();
5967     if (literalType->isVariableArrayType())
5968       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5969         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5970   } else if (!literalType->isDependentType() &&
5971              RequireCompleteType(LParenLoc, literalType,
5972                diag::err_typecheck_decl_incomplete_type,
5973                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5974     return ExprError();
5975 
5976   InitializedEntity Entity
5977     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5978   InitializationKind Kind
5979     = InitializationKind::CreateCStyleCast(LParenLoc,
5980                                            SourceRange(LParenLoc, RParenLoc),
5981                                            /*InitList=*/true);
5982   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5983   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5984                                       &literalType);
5985   if (Result.isInvalid())
5986     return ExprError();
5987   LiteralExpr = Result.get();
5988 
5989   bool isFileScope = !CurContext->isFunctionOrMethod();
5990 
5991   // In C, compound literals are l-values for some reason.
5992   // For GCC compatibility, in C++, file-scope array compound literals with
5993   // constant initializers are also l-values, and compound literals are
5994   // otherwise prvalues.
5995   //
5996   // (GCC also treats C++ list-initialized file-scope array prvalues with
5997   // constant initializers as l-values, but that's non-conforming, so we don't
5998   // follow it there.)
5999   //
6000   // FIXME: It would be better to handle the lvalue cases as materializing and
6001   // lifetime-extending a temporary object, but our materialized temporaries
6002   // representation only supports lifetime extension from a variable, not "out
6003   // of thin air".
6004   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6005   // is bound to the result of applying array-to-pointer decay to the compound
6006   // literal.
6007   // FIXME: GCC supports compound literals of reference type, which should
6008   // obviously have a value kind derived from the kind of reference involved.
6009   ExprValueKind VK =
6010       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6011           ? VK_RValue
6012           : VK_LValue;
6013 
6014   if (isFileScope)
6015     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6016       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6017         Expr *Init = ILE->getInit(i);
6018         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6019       }
6020 
6021   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6022                                               VK, LiteralExpr, isFileScope);
6023   if (isFileScope) {
6024     if (!LiteralExpr->isTypeDependent() &&
6025         !LiteralExpr->isValueDependent() &&
6026         !literalType->isDependentType()) // C99 6.5.2.5p3
6027       if (CheckForConstantInitializer(LiteralExpr, literalType))
6028         return ExprError();
6029   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6030              literalType.getAddressSpace() != LangAS::Default) {
6031     // Embedded-C extensions to C99 6.5.2.5:
6032     //   "If the compound literal occurs inside the body of a function, the
6033     //   type name shall not be qualified by an address-space qualifier."
6034     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6035       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6036     return ExprError();
6037   }
6038 
6039   return MaybeBindToTemporary(E);
6040 }
6041 
6042 ExprResult
6043 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6044                     SourceLocation RBraceLoc) {
6045   // Immediately handle non-overload placeholders.  Overloads can be
6046   // resolved contextually, but everything else here can't.
6047   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6048     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6049       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6050 
6051       // Ignore failures; dropping the entire initializer list because
6052       // of one failure would be terrible for indexing/etc.
6053       if (result.isInvalid()) continue;
6054 
6055       InitArgList[I] = result.get();
6056     }
6057   }
6058 
6059   // Semantic analysis for initializers is done by ActOnDeclarator() and
6060   // CheckInitializer() - it requires knowledge of the object being initialized.
6061 
6062   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6063                                                RBraceLoc);
6064   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6065   return E;
6066 }
6067 
6068 /// Do an explicit extend of the given block pointer if we're in ARC.
6069 void Sema::maybeExtendBlockObject(ExprResult &E) {
6070   assert(E.get()->getType()->isBlockPointerType());
6071   assert(E.get()->isRValue());
6072 
6073   // Only do this in an r-value context.
6074   if (!getLangOpts().ObjCAutoRefCount) return;
6075 
6076   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6077                                CK_ARCExtendBlockObject, E.get(),
6078                                /*base path*/ nullptr, VK_RValue);
6079   Cleanup.setExprNeedsCleanups(true);
6080 }
6081 
6082 /// Prepare a conversion of the given expression to an ObjC object
6083 /// pointer type.
6084 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6085   QualType type = E.get()->getType();
6086   if (type->isObjCObjectPointerType()) {
6087     return CK_BitCast;
6088   } else if (type->isBlockPointerType()) {
6089     maybeExtendBlockObject(E);
6090     return CK_BlockPointerToObjCPointerCast;
6091   } else {
6092     assert(type->isPointerType());
6093     return CK_CPointerToObjCPointerCast;
6094   }
6095 }
6096 
6097 /// Prepares for a scalar cast, performing all the necessary stages
6098 /// except the final cast and returning the kind required.
6099 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6100   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6101   // Also, callers should have filtered out the invalid cases with
6102   // pointers.  Everything else should be possible.
6103 
6104   QualType SrcTy = Src.get()->getType();
6105   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6106     return CK_NoOp;
6107 
6108   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6109   case Type::STK_MemberPointer:
6110     llvm_unreachable("member pointer type in C");
6111 
6112   case Type::STK_CPointer:
6113   case Type::STK_BlockPointer:
6114   case Type::STK_ObjCObjectPointer:
6115     switch (DestTy->getScalarTypeKind()) {
6116     case Type::STK_CPointer: {
6117       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6118       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6119       if (SrcAS != DestAS)
6120         return CK_AddressSpaceConversion;
6121       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6122         return CK_NoOp;
6123       return CK_BitCast;
6124     }
6125     case Type::STK_BlockPointer:
6126       return (SrcKind == Type::STK_BlockPointer
6127                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6128     case Type::STK_ObjCObjectPointer:
6129       if (SrcKind == Type::STK_ObjCObjectPointer)
6130         return CK_BitCast;
6131       if (SrcKind == Type::STK_CPointer)
6132         return CK_CPointerToObjCPointerCast;
6133       maybeExtendBlockObject(Src);
6134       return CK_BlockPointerToObjCPointerCast;
6135     case Type::STK_Bool:
6136       return CK_PointerToBoolean;
6137     case Type::STK_Integral:
6138       return CK_PointerToIntegral;
6139     case Type::STK_Floating:
6140     case Type::STK_FloatingComplex:
6141     case Type::STK_IntegralComplex:
6142     case Type::STK_MemberPointer:
6143     case Type::STK_FixedPoint:
6144       llvm_unreachable("illegal cast from pointer");
6145     }
6146     llvm_unreachable("Should have returned before this");
6147 
6148   case Type::STK_FixedPoint:
6149     switch (DestTy->getScalarTypeKind()) {
6150     case Type::STK_FixedPoint:
6151       return CK_FixedPointCast;
6152     case Type::STK_Bool:
6153       return CK_FixedPointToBoolean;
6154     case Type::STK_Integral:
6155     case Type::STK_Floating:
6156     case Type::STK_IntegralComplex:
6157     case Type::STK_FloatingComplex:
6158       Diag(Src.get()->getExprLoc(),
6159            diag::err_unimplemented_conversion_with_fixed_point_type)
6160           << DestTy;
6161       return CK_IntegralCast;
6162     case Type::STK_CPointer:
6163     case Type::STK_ObjCObjectPointer:
6164     case Type::STK_BlockPointer:
6165     case Type::STK_MemberPointer:
6166       llvm_unreachable("illegal cast to pointer type");
6167     }
6168     llvm_unreachable("Should have returned before this");
6169 
6170   case Type::STK_Bool: // casting from bool is like casting from an integer
6171   case Type::STK_Integral:
6172     switch (DestTy->getScalarTypeKind()) {
6173     case Type::STK_CPointer:
6174     case Type::STK_ObjCObjectPointer:
6175     case Type::STK_BlockPointer:
6176       if (Src.get()->isNullPointerConstant(Context,
6177                                            Expr::NPC_ValueDependentIsNull))
6178         return CK_NullToPointer;
6179       return CK_IntegralToPointer;
6180     case Type::STK_Bool:
6181       return CK_IntegralToBoolean;
6182     case Type::STK_Integral:
6183       return CK_IntegralCast;
6184     case Type::STK_Floating:
6185       return CK_IntegralToFloating;
6186     case Type::STK_IntegralComplex:
6187       Src = ImpCastExprToType(Src.get(),
6188                       DestTy->castAs<ComplexType>()->getElementType(),
6189                       CK_IntegralCast);
6190       return CK_IntegralRealToComplex;
6191     case Type::STK_FloatingComplex:
6192       Src = ImpCastExprToType(Src.get(),
6193                       DestTy->castAs<ComplexType>()->getElementType(),
6194                       CK_IntegralToFloating);
6195       return CK_FloatingRealToComplex;
6196     case Type::STK_MemberPointer:
6197       llvm_unreachable("member pointer type in C");
6198     case Type::STK_FixedPoint:
6199       Diag(Src.get()->getExprLoc(),
6200            diag::err_unimplemented_conversion_with_fixed_point_type)
6201           << SrcTy;
6202       return CK_IntegralCast;
6203     }
6204     llvm_unreachable("Should have returned before this");
6205 
6206   case Type::STK_Floating:
6207     switch (DestTy->getScalarTypeKind()) {
6208     case Type::STK_Floating:
6209       return CK_FloatingCast;
6210     case Type::STK_Bool:
6211       return CK_FloatingToBoolean;
6212     case Type::STK_Integral:
6213       return CK_FloatingToIntegral;
6214     case Type::STK_FloatingComplex:
6215       Src = ImpCastExprToType(Src.get(),
6216                               DestTy->castAs<ComplexType>()->getElementType(),
6217                               CK_FloatingCast);
6218       return CK_FloatingRealToComplex;
6219     case Type::STK_IntegralComplex:
6220       Src = ImpCastExprToType(Src.get(),
6221                               DestTy->castAs<ComplexType>()->getElementType(),
6222                               CK_FloatingToIntegral);
6223       return CK_IntegralRealToComplex;
6224     case Type::STK_CPointer:
6225     case Type::STK_ObjCObjectPointer:
6226     case Type::STK_BlockPointer:
6227       llvm_unreachable("valid float->pointer cast?");
6228     case Type::STK_MemberPointer:
6229       llvm_unreachable("member pointer type in C");
6230     case Type::STK_FixedPoint:
6231       Diag(Src.get()->getExprLoc(),
6232            diag::err_unimplemented_conversion_with_fixed_point_type)
6233           << SrcTy;
6234       return CK_IntegralCast;
6235     }
6236     llvm_unreachable("Should have returned before this");
6237 
6238   case Type::STK_FloatingComplex:
6239     switch (DestTy->getScalarTypeKind()) {
6240     case Type::STK_FloatingComplex:
6241       return CK_FloatingComplexCast;
6242     case Type::STK_IntegralComplex:
6243       return CK_FloatingComplexToIntegralComplex;
6244     case Type::STK_Floating: {
6245       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6246       if (Context.hasSameType(ET, DestTy))
6247         return CK_FloatingComplexToReal;
6248       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6249       return CK_FloatingCast;
6250     }
6251     case Type::STK_Bool:
6252       return CK_FloatingComplexToBoolean;
6253     case Type::STK_Integral:
6254       Src = ImpCastExprToType(Src.get(),
6255                               SrcTy->castAs<ComplexType>()->getElementType(),
6256                               CK_FloatingComplexToReal);
6257       return CK_FloatingToIntegral;
6258     case Type::STK_CPointer:
6259     case Type::STK_ObjCObjectPointer:
6260     case Type::STK_BlockPointer:
6261       llvm_unreachable("valid complex float->pointer cast?");
6262     case Type::STK_MemberPointer:
6263       llvm_unreachable("member pointer type in C");
6264     case Type::STK_FixedPoint:
6265       Diag(Src.get()->getExprLoc(),
6266            diag::err_unimplemented_conversion_with_fixed_point_type)
6267           << SrcTy;
6268       return CK_IntegralCast;
6269     }
6270     llvm_unreachable("Should have returned before this");
6271 
6272   case Type::STK_IntegralComplex:
6273     switch (DestTy->getScalarTypeKind()) {
6274     case Type::STK_FloatingComplex:
6275       return CK_IntegralComplexToFloatingComplex;
6276     case Type::STK_IntegralComplex:
6277       return CK_IntegralComplexCast;
6278     case Type::STK_Integral: {
6279       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6280       if (Context.hasSameType(ET, DestTy))
6281         return CK_IntegralComplexToReal;
6282       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6283       return CK_IntegralCast;
6284     }
6285     case Type::STK_Bool:
6286       return CK_IntegralComplexToBoolean;
6287     case Type::STK_Floating:
6288       Src = ImpCastExprToType(Src.get(),
6289                               SrcTy->castAs<ComplexType>()->getElementType(),
6290                               CK_IntegralComplexToReal);
6291       return CK_IntegralToFloating;
6292     case Type::STK_CPointer:
6293     case Type::STK_ObjCObjectPointer:
6294     case Type::STK_BlockPointer:
6295       llvm_unreachable("valid complex int->pointer cast?");
6296     case Type::STK_MemberPointer:
6297       llvm_unreachable("member pointer type in C");
6298     case Type::STK_FixedPoint:
6299       Diag(Src.get()->getExprLoc(),
6300            diag::err_unimplemented_conversion_with_fixed_point_type)
6301           << SrcTy;
6302       return CK_IntegralCast;
6303     }
6304     llvm_unreachable("Should have returned before this");
6305   }
6306 
6307   llvm_unreachable("Unhandled scalar cast");
6308 }
6309 
6310 static bool breakDownVectorType(QualType type, uint64_t &len,
6311                                 QualType &eltType) {
6312   // Vectors are simple.
6313   if (const VectorType *vecType = type->getAs<VectorType>()) {
6314     len = vecType->getNumElements();
6315     eltType = vecType->getElementType();
6316     assert(eltType->isScalarType());
6317     return true;
6318   }
6319 
6320   // We allow lax conversion to and from non-vector types, but only if
6321   // they're real types (i.e. non-complex, non-pointer scalar types).
6322   if (!type->isRealType()) return false;
6323 
6324   len = 1;
6325   eltType = type;
6326   return true;
6327 }
6328 
6329 /// Are the two types lax-compatible vector types?  That is, given
6330 /// that one of them is a vector, do they have equal storage sizes,
6331 /// where the storage size is the number of elements times the element
6332 /// size?
6333 ///
6334 /// This will also return false if either of the types is neither a
6335 /// vector nor a real type.
6336 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6337   assert(destTy->isVectorType() || srcTy->isVectorType());
6338 
6339   // Disallow lax conversions between scalars and ExtVectors (these
6340   // conversions are allowed for other vector types because common headers
6341   // depend on them).  Most scalar OP ExtVector cases are handled by the
6342   // splat path anyway, which does what we want (convert, not bitcast).
6343   // What this rules out for ExtVectors is crazy things like char4*float.
6344   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6345   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6346 
6347   uint64_t srcLen, destLen;
6348   QualType srcEltTy, destEltTy;
6349   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6350   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6351 
6352   // ASTContext::getTypeSize will return the size rounded up to a
6353   // power of 2, so instead of using that, we need to use the raw
6354   // element size multiplied by the element count.
6355   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6356   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6357 
6358   return (srcLen * srcEltSize == destLen * destEltSize);
6359 }
6360 
6361 /// Is this a legal conversion between two types, one of which is
6362 /// known to be a vector type?
6363 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6364   assert(destTy->isVectorType() || srcTy->isVectorType());
6365 
6366   if (!Context.getLangOpts().LaxVectorConversions)
6367     return false;
6368   return areLaxCompatibleVectorTypes(srcTy, destTy);
6369 }
6370 
6371 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6372                            CastKind &Kind) {
6373   assert(VectorTy->isVectorType() && "Not a vector type!");
6374 
6375   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6376     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6377       return Diag(R.getBegin(),
6378                   Ty->isVectorType() ?
6379                   diag::err_invalid_conversion_between_vectors :
6380                   diag::err_invalid_conversion_between_vector_and_integer)
6381         << VectorTy << Ty << R;
6382   } else
6383     return Diag(R.getBegin(),
6384                 diag::err_invalid_conversion_between_vector_and_scalar)
6385       << VectorTy << Ty << R;
6386 
6387   Kind = CK_BitCast;
6388   return false;
6389 }
6390 
6391 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6392   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6393 
6394   if (DestElemTy == SplattedExpr->getType())
6395     return SplattedExpr;
6396 
6397   assert(DestElemTy->isFloatingType() ||
6398          DestElemTy->isIntegralOrEnumerationType());
6399 
6400   CastKind CK;
6401   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6402     // OpenCL requires that we convert `true` boolean expressions to -1, but
6403     // only when splatting vectors.
6404     if (DestElemTy->isFloatingType()) {
6405       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6406       // in two steps: boolean to signed integral, then to floating.
6407       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6408                                                  CK_BooleanToSignedIntegral);
6409       SplattedExpr = CastExprRes.get();
6410       CK = CK_IntegralToFloating;
6411     } else {
6412       CK = CK_BooleanToSignedIntegral;
6413     }
6414   } else {
6415     ExprResult CastExprRes = SplattedExpr;
6416     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6417     if (CastExprRes.isInvalid())
6418       return ExprError();
6419     SplattedExpr = CastExprRes.get();
6420   }
6421   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6422 }
6423 
6424 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6425                                     Expr *CastExpr, CastKind &Kind) {
6426   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6427 
6428   QualType SrcTy = CastExpr->getType();
6429 
6430   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6431   // an ExtVectorType.
6432   // In OpenCL, casts between vectors of different types are not allowed.
6433   // (See OpenCL 6.2).
6434   if (SrcTy->isVectorType()) {
6435     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6436         (getLangOpts().OpenCL &&
6437          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6438       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6439         << DestTy << SrcTy << R;
6440       return ExprError();
6441     }
6442     Kind = CK_BitCast;
6443     return CastExpr;
6444   }
6445 
6446   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6447   // conversion will take place first from scalar to elt type, and then
6448   // splat from elt type to vector.
6449   if (SrcTy->isPointerType())
6450     return Diag(R.getBegin(),
6451                 diag::err_invalid_conversion_between_vector_and_scalar)
6452       << DestTy << SrcTy << R;
6453 
6454   Kind = CK_VectorSplat;
6455   return prepareVectorSplat(DestTy, CastExpr);
6456 }
6457 
6458 ExprResult
6459 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6460                     Declarator &D, ParsedType &Ty,
6461                     SourceLocation RParenLoc, Expr *CastExpr) {
6462   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6463          "ActOnCastExpr(): missing type or expr");
6464 
6465   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6466   if (D.isInvalidType())
6467     return ExprError();
6468 
6469   if (getLangOpts().CPlusPlus) {
6470     // Check that there are no default arguments (C++ only).
6471     CheckExtraCXXDefaultArguments(D);
6472   } else {
6473     // Make sure any TypoExprs have been dealt with.
6474     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6475     if (!Res.isUsable())
6476       return ExprError();
6477     CastExpr = Res.get();
6478   }
6479 
6480   checkUnusedDeclAttributes(D);
6481 
6482   QualType castType = castTInfo->getType();
6483   Ty = CreateParsedType(castType, castTInfo);
6484 
6485   bool isVectorLiteral = false;
6486 
6487   // Check for an altivec or OpenCL literal,
6488   // i.e. all the elements are integer constants.
6489   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6490   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6491   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6492        && castType->isVectorType() && (PE || PLE)) {
6493     if (PLE && PLE->getNumExprs() == 0) {
6494       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6495       return ExprError();
6496     }
6497     if (PE || PLE->getNumExprs() == 1) {
6498       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6499       if (!E->getType()->isVectorType())
6500         isVectorLiteral = true;
6501     }
6502     else
6503       isVectorLiteral = true;
6504   }
6505 
6506   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6507   // then handle it as such.
6508   if (isVectorLiteral)
6509     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6510 
6511   // If the Expr being casted is a ParenListExpr, handle it specially.
6512   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6513   // sequence of BinOp comma operators.
6514   if (isa<ParenListExpr>(CastExpr)) {
6515     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6516     if (Result.isInvalid()) return ExprError();
6517     CastExpr = Result.get();
6518   }
6519 
6520   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6521       !getSourceManager().isInSystemMacro(LParenLoc))
6522     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6523 
6524   CheckTollFreeBridgeCast(castType, CastExpr);
6525 
6526   CheckObjCBridgeRelatedCast(castType, CastExpr);
6527 
6528   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6529 
6530   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6531 }
6532 
6533 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6534                                     SourceLocation RParenLoc, Expr *E,
6535                                     TypeSourceInfo *TInfo) {
6536   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6537          "Expected paren or paren list expression");
6538 
6539   Expr **exprs;
6540   unsigned numExprs;
6541   Expr *subExpr;
6542   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6543   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6544     LiteralLParenLoc = PE->getLParenLoc();
6545     LiteralRParenLoc = PE->getRParenLoc();
6546     exprs = PE->getExprs();
6547     numExprs = PE->getNumExprs();
6548   } else { // isa<ParenExpr> by assertion at function entrance
6549     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6550     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6551     subExpr = cast<ParenExpr>(E)->getSubExpr();
6552     exprs = &subExpr;
6553     numExprs = 1;
6554   }
6555 
6556   QualType Ty = TInfo->getType();
6557   assert(Ty->isVectorType() && "Expected vector type");
6558 
6559   SmallVector<Expr *, 8> initExprs;
6560   const VectorType *VTy = Ty->getAs<VectorType>();
6561   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6562 
6563   // '(...)' form of vector initialization in AltiVec: the number of
6564   // initializers must be one or must match the size of the vector.
6565   // If a single value is specified in the initializer then it will be
6566   // replicated to all the components of the vector
6567   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6568     // The number of initializers must be one or must match the size of the
6569     // vector. If a single value is specified in the initializer then it will
6570     // be replicated to all the components of the vector
6571     if (numExprs == 1) {
6572       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6573       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6574       if (Literal.isInvalid())
6575         return ExprError();
6576       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6577                                   PrepareScalarCast(Literal, ElemTy));
6578       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6579     }
6580     else if (numExprs < numElems) {
6581       Diag(E->getExprLoc(),
6582            diag::err_incorrect_number_of_vector_initializers);
6583       return ExprError();
6584     }
6585     else
6586       initExprs.append(exprs, exprs + numExprs);
6587   }
6588   else {
6589     // For OpenCL, when the number of initializers is a single value,
6590     // it will be replicated to all components of the vector.
6591     if (getLangOpts().OpenCL &&
6592         VTy->getVectorKind() == VectorType::GenericVector &&
6593         numExprs == 1) {
6594         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6595         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6596         if (Literal.isInvalid())
6597           return ExprError();
6598         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6599                                     PrepareScalarCast(Literal, ElemTy));
6600         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6601     }
6602 
6603     initExprs.append(exprs, exprs + numExprs);
6604   }
6605   // FIXME: This means that pretty-printing the final AST will produce curly
6606   // braces instead of the original commas.
6607   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6608                                                    initExprs, LiteralRParenLoc);
6609   initE->setType(Ty);
6610   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6611 }
6612 
6613 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6614 /// the ParenListExpr into a sequence of comma binary operators.
6615 ExprResult
6616 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6617   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6618   if (!E)
6619     return OrigExpr;
6620 
6621   ExprResult Result(E->getExpr(0));
6622 
6623   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6624     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6625                         E->getExpr(i));
6626 
6627   if (Result.isInvalid()) return ExprError();
6628 
6629   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6630 }
6631 
6632 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6633                                     SourceLocation R,
6634                                     MultiExprArg Val) {
6635   return ParenListExpr::Create(Context, L, Val, R);
6636 }
6637 
6638 /// Emit a specialized diagnostic when one expression is a null pointer
6639 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6640 /// emitted.
6641 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6642                                       SourceLocation QuestionLoc) {
6643   Expr *NullExpr = LHSExpr;
6644   Expr *NonPointerExpr = RHSExpr;
6645   Expr::NullPointerConstantKind NullKind =
6646       NullExpr->isNullPointerConstant(Context,
6647                                       Expr::NPC_ValueDependentIsNotNull);
6648 
6649   if (NullKind == Expr::NPCK_NotNull) {
6650     NullExpr = RHSExpr;
6651     NonPointerExpr = LHSExpr;
6652     NullKind =
6653         NullExpr->isNullPointerConstant(Context,
6654                                         Expr::NPC_ValueDependentIsNotNull);
6655   }
6656 
6657   if (NullKind == Expr::NPCK_NotNull)
6658     return false;
6659 
6660   if (NullKind == Expr::NPCK_ZeroExpression)
6661     return false;
6662 
6663   if (NullKind == Expr::NPCK_ZeroLiteral) {
6664     // In this case, check to make sure that we got here from a "NULL"
6665     // string in the source code.
6666     NullExpr = NullExpr->IgnoreParenImpCasts();
6667     SourceLocation loc = NullExpr->getExprLoc();
6668     if (!findMacroSpelling(loc, "NULL"))
6669       return false;
6670   }
6671 
6672   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6673   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6674       << NonPointerExpr->getType() << DiagType
6675       << NonPointerExpr->getSourceRange();
6676   return true;
6677 }
6678 
6679 /// Return false if the condition expression is valid, true otherwise.
6680 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6681   QualType CondTy = Cond->getType();
6682 
6683   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6684   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6685     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6686       << CondTy << Cond->getSourceRange();
6687     return true;
6688   }
6689 
6690   // C99 6.5.15p2
6691   if (CondTy->isScalarType()) return false;
6692 
6693   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6694     << CondTy << Cond->getSourceRange();
6695   return true;
6696 }
6697 
6698 /// Handle when one or both operands are void type.
6699 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6700                                          ExprResult &RHS) {
6701     Expr *LHSExpr = LHS.get();
6702     Expr *RHSExpr = RHS.get();
6703 
6704     if (!LHSExpr->getType()->isVoidType())
6705       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6706           << RHSExpr->getSourceRange();
6707     if (!RHSExpr->getType()->isVoidType())
6708       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6709           << LHSExpr->getSourceRange();
6710     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6711     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6712     return S.Context.VoidTy;
6713 }
6714 
6715 /// Return false if the NullExpr can be promoted to PointerTy,
6716 /// true otherwise.
6717 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6718                                         QualType PointerTy) {
6719   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6720       !NullExpr.get()->isNullPointerConstant(S.Context,
6721                                             Expr::NPC_ValueDependentIsNull))
6722     return true;
6723 
6724   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6725   return false;
6726 }
6727 
6728 /// Checks compatibility between two pointers and return the resulting
6729 /// type.
6730 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6731                                                      ExprResult &RHS,
6732                                                      SourceLocation Loc) {
6733   QualType LHSTy = LHS.get()->getType();
6734   QualType RHSTy = RHS.get()->getType();
6735 
6736   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6737     // Two identical pointers types are always compatible.
6738     return LHSTy;
6739   }
6740 
6741   QualType lhptee, rhptee;
6742 
6743   // Get the pointee types.
6744   bool IsBlockPointer = false;
6745   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6746     lhptee = LHSBTy->getPointeeType();
6747     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6748     IsBlockPointer = true;
6749   } else {
6750     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6751     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6752   }
6753 
6754   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6755   // differently qualified versions of compatible types, the result type is
6756   // a pointer to an appropriately qualified version of the composite
6757   // type.
6758 
6759   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6760   // clause doesn't make sense for our extensions. E.g. address space 2 should
6761   // be incompatible with address space 3: they may live on different devices or
6762   // anything.
6763   Qualifiers lhQual = lhptee.getQualifiers();
6764   Qualifiers rhQual = rhptee.getQualifiers();
6765 
6766   LangAS ResultAddrSpace = LangAS::Default;
6767   LangAS LAddrSpace = lhQual.getAddressSpace();
6768   LangAS RAddrSpace = rhQual.getAddressSpace();
6769 
6770   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6771   // spaces is disallowed.
6772   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6773     ResultAddrSpace = LAddrSpace;
6774   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6775     ResultAddrSpace = RAddrSpace;
6776   else {
6777     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6778         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6779         << RHS.get()->getSourceRange();
6780     return QualType();
6781   }
6782 
6783   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6784   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6785   lhQual.removeCVRQualifiers();
6786   rhQual.removeCVRQualifiers();
6787 
6788   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6789   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6790   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6791   // qual types are compatible iff
6792   //  * corresponded types are compatible
6793   //  * CVR qualifiers are equal
6794   //  * address spaces are equal
6795   // Thus for conditional operator we merge CVR and address space unqualified
6796   // pointees and if there is a composite type we return a pointer to it with
6797   // merged qualifiers.
6798   LHSCastKind =
6799       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6800   RHSCastKind =
6801       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6802   lhQual.removeAddressSpace();
6803   rhQual.removeAddressSpace();
6804 
6805   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6806   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6807 
6808   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6809 
6810   if (CompositeTy.isNull()) {
6811     // In this situation, we assume void* type. No especially good
6812     // reason, but this is what gcc does, and we do have to pick
6813     // to get a consistent AST.
6814     QualType incompatTy;
6815     incompatTy = S.Context.getPointerType(
6816         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6817     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6818     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6819 
6820     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6821     // for casts between types with incompatible address space qualifiers.
6822     // For the following code the compiler produces casts between global and
6823     // local address spaces of the corresponded innermost pointees:
6824     // local int *global *a;
6825     // global int *global *b;
6826     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6827     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6828         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6829         << RHS.get()->getSourceRange();
6830 
6831     return incompatTy;
6832   }
6833 
6834   // The pointer types are compatible.
6835   // In case of OpenCL ResultTy should have the address space qualifier
6836   // which is a superset of address spaces of both the 2nd and the 3rd
6837   // operands of the conditional operator.
6838   QualType ResultTy = [&, ResultAddrSpace]() {
6839     if (S.getLangOpts().OpenCL) {
6840       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6841       CompositeQuals.setAddressSpace(ResultAddrSpace);
6842       return S.Context
6843           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6844           .withCVRQualifiers(MergedCVRQual);
6845     }
6846     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6847   }();
6848   if (IsBlockPointer)
6849     ResultTy = S.Context.getBlockPointerType(ResultTy);
6850   else
6851     ResultTy = S.Context.getPointerType(ResultTy);
6852 
6853   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6854   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6855   return ResultTy;
6856 }
6857 
6858 /// Return the resulting type when the operands are both block pointers.
6859 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6860                                                           ExprResult &LHS,
6861                                                           ExprResult &RHS,
6862                                                           SourceLocation Loc) {
6863   QualType LHSTy = LHS.get()->getType();
6864   QualType RHSTy = RHS.get()->getType();
6865 
6866   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6867     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6868       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6869       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6870       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6871       return destType;
6872     }
6873     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6874       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6875       << RHS.get()->getSourceRange();
6876     return QualType();
6877   }
6878 
6879   // We have 2 block pointer types.
6880   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6881 }
6882 
6883 /// Return the resulting type when the operands are both pointers.
6884 static QualType
6885 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6886                                             ExprResult &RHS,
6887                                             SourceLocation Loc) {
6888   // get the pointer types
6889   QualType LHSTy = LHS.get()->getType();
6890   QualType RHSTy = RHS.get()->getType();
6891 
6892   // get the "pointed to" types
6893   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6894   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6895 
6896   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6897   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6898     // Figure out necessary qualifiers (C99 6.5.15p6)
6899     QualType destPointee
6900       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6901     QualType destType = S.Context.getPointerType(destPointee);
6902     // Add qualifiers if necessary.
6903     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6904     // Promote to void*.
6905     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6906     return destType;
6907   }
6908   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6909     QualType destPointee
6910       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6911     QualType destType = S.Context.getPointerType(destPointee);
6912     // Add qualifiers if necessary.
6913     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6914     // Promote to void*.
6915     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6916     return destType;
6917   }
6918 
6919   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6920 }
6921 
6922 /// Return false if the first expression is not an integer and the second
6923 /// expression is not a pointer, true otherwise.
6924 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6925                                         Expr* PointerExpr, SourceLocation Loc,
6926                                         bool IsIntFirstExpr) {
6927   if (!PointerExpr->getType()->isPointerType() ||
6928       !Int.get()->getType()->isIntegerType())
6929     return false;
6930 
6931   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6932   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6933 
6934   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6935     << Expr1->getType() << Expr2->getType()
6936     << Expr1->getSourceRange() << Expr2->getSourceRange();
6937   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6938                             CK_IntegralToPointer);
6939   return true;
6940 }
6941 
6942 /// Simple conversion between integer and floating point types.
6943 ///
6944 /// Used when handling the OpenCL conditional operator where the
6945 /// condition is a vector while the other operands are scalar.
6946 ///
6947 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6948 /// types are either integer or floating type. Between the two
6949 /// operands, the type with the higher rank is defined as the "result
6950 /// type". The other operand needs to be promoted to the same type. No
6951 /// other type promotion is allowed. We cannot use
6952 /// UsualArithmeticConversions() for this purpose, since it always
6953 /// promotes promotable types.
6954 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6955                                             ExprResult &RHS,
6956                                             SourceLocation QuestionLoc) {
6957   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6958   if (LHS.isInvalid())
6959     return QualType();
6960   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6961   if (RHS.isInvalid())
6962     return QualType();
6963 
6964   // For conversion purposes, we ignore any qualifiers.
6965   // For example, "const float" and "float" are equivalent.
6966   QualType LHSType =
6967     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6968   QualType RHSType =
6969     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6970 
6971   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6972     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6973       << LHSType << LHS.get()->getSourceRange();
6974     return QualType();
6975   }
6976 
6977   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6978     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6979       << RHSType << RHS.get()->getSourceRange();
6980     return QualType();
6981   }
6982 
6983   // If both types are identical, no conversion is needed.
6984   if (LHSType == RHSType)
6985     return LHSType;
6986 
6987   // Now handle "real" floating types (i.e. float, double, long double).
6988   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6989     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6990                                  /*IsCompAssign = */ false);
6991 
6992   // Finally, we have two differing integer types.
6993   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6994   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6995 }
6996 
6997 /// Convert scalar operands to a vector that matches the
6998 ///        condition in length.
6999 ///
7000 /// Used when handling the OpenCL conditional operator where the
7001 /// condition is a vector while the other operands are scalar.
7002 ///
7003 /// We first compute the "result type" for the scalar operands
7004 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7005 /// into a vector of that type where the length matches the condition
7006 /// vector type. s6.11.6 requires that the element types of the result
7007 /// and the condition must have the same number of bits.
7008 static QualType
7009 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7010                               QualType CondTy, SourceLocation QuestionLoc) {
7011   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7012   if (ResTy.isNull()) return QualType();
7013 
7014   const VectorType *CV = CondTy->getAs<VectorType>();
7015   assert(CV);
7016 
7017   // Determine the vector result type
7018   unsigned NumElements = CV->getNumElements();
7019   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7020 
7021   // Ensure that all types have the same number of bits
7022   if (S.Context.getTypeSize(CV->getElementType())
7023       != S.Context.getTypeSize(ResTy)) {
7024     // Since VectorTy is created internally, it does not pretty print
7025     // with an OpenCL name. Instead, we just print a description.
7026     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7027     SmallString<64> Str;
7028     llvm::raw_svector_ostream OS(Str);
7029     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7030     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7031       << CondTy << OS.str();
7032     return QualType();
7033   }
7034 
7035   // Convert operands to the vector result type
7036   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7037   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7038 
7039   return VectorTy;
7040 }
7041 
7042 /// Return false if this is a valid OpenCL condition vector
7043 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7044                                        SourceLocation QuestionLoc) {
7045   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7046   // integral type.
7047   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7048   assert(CondTy);
7049   QualType EleTy = CondTy->getElementType();
7050   if (EleTy->isIntegerType()) return false;
7051 
7052   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7053     << Cond->getType() << Cond->getSourceRange();
7054   return true;
7055 }
7056 
7057 /// Return false if the vector condition type and the vector
7058 ///        result type are compatible.
7059 ///
7060 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7061 /// number of elements, and their element types have the same number
7062 /// of bits.
7063 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7064                               SourceLocation QuestionLoc) {
7065   const VectorType *CV = CondTy->getAs<VectorType>();
7066   const VectorType *RV = VecResTy->getAs<VectorType>();
7067   assert(CV && RV);
7068 
7069   if (CV->getNumElements() != RV->getNumElements()) {
7070     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7071       << CondTy << VecResTy;
7072     return true;
7073   }
7074 
7075   QualType CVE = CV->getElementType();
7076   QualType RVE = RV->getElementType();
7077 
7078   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7079     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7080       << CondTy << VecResTy;
7081     return true;
7082   }
7083 
7084   return false;
7085 }
7086 
7087 /// Return the resulting type for the conditional operator in
7088 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7089 ///        s6.3.i) when the condition is a vector type.
7090 static QualType
7091 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7092                              ExprResult &LHS, ExprResult &RHS,
7093                              SourceLocation QuestionLoc) {
7094   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7095   if (Cond.isInvalid())
7096     return QualType();
7097   QualType CondTy = Cond.get()->getType();
7098 
7099   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7100     return QualType();
7101 
7102   // If either operand is a vector then find the vector type of the
7103   // result as specified in OpenCL v1.1 s6.3.i.
7104   if (LHS.get()->getType()->isVectorType() ||
7105       RHS.get()->getType()->isVectorType()) {
7106     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7107                                               /*isCompAssign*/false,
7108                                               /*AllowBothBool*/true,
7109                                               /*AllowBoolConversions*/false);
7110     if (VecResTy.isNull()) return QualType();
7111     // The result type must match the condition type as specified in
7112     // OpenCL v1.1 s6.11.6.
7113     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7114       return QualType();
7115     return VecResTy;
7116   }
7117 
7118   // Both operands are scalar.
7119   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7120 }
7121 
7122 /// Return true if the Expr is block type
7123 static bool checkBlockType(Sema &S, const Expr *E) {
7124   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7125     QualType Ty = CE->getCallee()->getType();
7126     if (Ty->isBlockPointerType()) {
7127       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7128       return true;
7129     }
7130   }
7131   return false;
7132 }
7133 
7134 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7135 /// In that case, LHS = cond.
7136 /// C99 6.5.15
7137 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7138                                         ExprResult &RHS, ExprValueKind &VK,
7139                                         ExprObjectKind &OK,
7140                                         SourceLocation QuestionLoc) {
7141 
7142   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7143   if (!LHSResult.isUsable()) return QualType();
7144   LHS = LHSResult;
7145 
7146   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7147   if (!RHSResult.isUsable()) return QualType();
7148   RHS = RHSResult;
7149 
7150   // C++ is sufficiently different to merit its own checker.
7151   if (getLangOpts().CPlusPlus)
7152     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7153 
7154   VK = VK_RValue;
7155   OK = OK_Ordinary;
7156 
7157   // The OpenCL operator with a vector condition is sufficiently
7158   // different to merit its own checker.
7159   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7160     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7161 
7162   // First, check the condition.
7163   Cond = UsualUnaryConversions(Cond.get());
7164   if (Cond.isInvalid())
7165     return QualType();
7166   if (checkCondition(*this, Cond.get(), QuestionLoc))
7167     return QualType();
7168 
7169   // Now check the two expressions.
7170   if (LHS.get()->getType()->isVectorType() ||
7171       RHS.get()->getType()->isVectorType())
7172     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7173                                /*AllowBothBool*/true,
7174                                /*AllowBoolConversions*/false);
7175 
7176   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7177   if (LHS.isInvalid() || RHS.isInvalid())
7178     return QualType();
7179 
7180   QualType LHSTy = LHS.get()->getType();
7181   QualType RHSTy = RHS.get()->getType();
7182 
7183   // Diagnose attempts to convert between __float128 and long double where
7184   // such conversions currently can't be handled.
7185   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7186     Diag(QuestionLoc,
7187          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7188       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7189     return QualType();
7190   }
7191 
7192   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7193   // selection operator (?:).
7194   if (getLangOpts().OpenCL &&
7195       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7196     return QualType();
7197   }
7198 
7199   // If both operands have arithmetic type, do the usual arithmetic conversions
7200   // to find a common type: C99 6.5.15p3,5.
7201   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7202     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7203     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7204 
7205     return ResTy;
7206   }
7207 
7208   // If both operands are the same structure or union type, the result is that
7209   // type.
7210   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7211     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7212       if (LHSRT->getDecl() == RHSRT->getDecl())
7213         // "If both the operands have structure or union type, the result has
7214         // that type."  This implies that CV qualifiers are dropped.
7215         return LHSTy.getUnqualifiedType();
7216     // FIXME: Type of conditional expression must be complete in C mode.
7217   }
7218 
7219   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7220   // The following || allows only one side to be void (a GCC-ism).
7221   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7222     return checkConditionalVoidType(*this, LHS, RHS);
7223   }
7224 
7225   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7226   // the type of the other operand."
7227   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7228   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7229 
7230   // All objective-c pointer type analysis is done here.
7231   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7232                                                         QuestionLoc);
7233   if (LHS.isInvalid() || RHS.isInvalid())
7234     return QualType();
7235   if (!compositeType.isNull())
7236     return compositeType;
7237 
7238 
7239   // Handle block pointer types.
7240   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7241     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7242                                                      QuestionLoc);
7243 
7244   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7245   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7246     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7247                                                        QuestionLoc);
7248 
7249   // GCC compatibility: soften pointer/integer mismatch.  Note that
7250   // null pointers have been filtered out by this point.
7251   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7252       /*isIntFirstExpr=*/true))
7253     return RHSTy;
7254   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7255       /*isIntFirstExpr=*/false))
7256     return LHSTy;
7257 
7258   // Emit a better diagnostic if one of the expressions is a null pointer
7259   // constant and the other is not a pointer type. In this case, the user most
7260   // likely forgot to take the address of the other expression.
7261   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7262     return QualType();
7263 
7264   // Otherwise, the operands are not compatible.
7265   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7266     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7267     << RHS.get()->getSourceRange();
7268   return QualType();
7269 }
7270 
7271 /// FindCompositeObjCPointerType - Helper method to find composite type of
7272 /// two objective-c pointer types of the two input expressions.
7273 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7274                                             SourceLocation QuestionLoc) {
7275   QualType LHSTy = LHS.get()->getType();
7276   QualType RHSTy = RHS.get()->getType();
7277 
7278   // Handle things like Class and struct objc_class*.  Here we case the result
7279   // to the pseudo-builtin, because that will be implicitly cast back to the
7280   // redefinition type if an attempt is made to access its fields.
7281   if (LHSTy->isObjCClassType() &&
7282       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7283     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7284     return LHSTy;
7285   }
7286   if (RHSTy->isObjCClassType() &&
7287       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7288     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7289     return RHSTy;
7290   }
7291   // And the same for struct objc_object* / id
7292   if (LHSTy->isObjCIdType() &&
7293       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7294     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7295     return LHSTy;
7296   }
7297   if (RHSTy->isObjCIdType() &&
7298       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7299     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7300     return RHSTy;
7301   }
7302   // And the same for struct objc_selector* / SEL
7303   if (Context.isObjCSelType(LHSTy) &&
7304       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7305     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7306     return LHSTy;
7307   }
7308   if (Context.isObjCSelType(RHSTy) &&
7309       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7310     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7311     return RHSTy;
7312   }
7313   // Check constraints for Objective-C object pointers types.
7314   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7315 
7316     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7317       // Two identical object pointer types are always compatible.
7318       return LHSTy;
7319     }
7320     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7321     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7322     QualType compositeType = LHSTy;
7323 
7324     // If both operands are interfaces and either operand can be
7325     // assigned to the other, use that type as the composite
7326     // type. This allows
7327     //   xxx ? (A*) a : (B*) b
7328     // where B is a subclass of A.
7329     //
7330     // Additionally, as for assignment, if either type is 'id'
7331     // allow silent coercion. Finally, if the types are
7332     // incompatible then make sure to use 'id' as the composite
7333     // type so the result is acceptable for sending messages to.
7334 
7335     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7336     // It could return the composite type.
7337     if (!(compositeType =
7338           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7339       // Nothing more to do.
7340     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7341       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7342     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7343       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7344     } else if ((LHSTy->isObjCQualifiedIdType() ||
7345                 RHSTy->isObjCQualifiedIdType()) &&
7346                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7347       // Need to handle "id<xx>" explicitly.
7348       // GCC allows qualified id and any Objective-C type to devolve to
7349       // id. Currently localizing to here until clear this should be
7350       // part of ObjCQualifiedIdTypesAreCompatible.
7351       compositeType = Context.getObjCIdType();
7352     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7353       compositeType = Context.getObjCIdType();
7354     } else {
7355       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7356       << LHSTy << RHSTy
7357       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7358       QualType incompatTy = Context.getObjCIdType();
7359       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7360       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7361       return incompatTy;
7362     }
7363     // The object pointer types are compatible.
7364     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7365     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7366     return compositeType;
7367   }
7368   // Check Objective-C object pointer types and 'void *'
7369   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7370     if (getLangOpts().ObjCAutoRefCount) {
7371       // ARC forbids the implicit conversion of object pointers to 'void *',
7372       // so these types are not compatible.
7373       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7374           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7375       LHS = RHS = true;
7376       return QualType();
7377     }
7378     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7379     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7380     QualType destPointee
7381     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7382     QualType destType = Context.getPointerType(destPointee);
7383     // Add qualifiers if necessary.
7384     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7385     // Promote to void*.
7386     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7387     return destType;
7388   }
7389   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7390     if (getLangOpts().ObjCAutoRefCount) {
7391       // ARC forbids the implicit conversion of object pointers to 'void *',
7392       // so these types are not compatible.
7393       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7394           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7395       LHS = RHS = true;
7396       return QualType();
7397     }
7398     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7399     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7400     QualType destPointee
7401     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7402     QualType destType = Context.getPointerType(destPointee);
7403     // Add qualifiers if necessary.
7404     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7405     // Promote to void*.
7406     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7407     return destType;
7408   }
7409   return QualType();
7410 }
7411 
7412 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7413 /// ParenRange in parentheses.
7414 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7415                                const PartialDiagnostic &Note,
7416                                SourceRange ParenRange) {
7417   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7418   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7419       EndLoc.isValid()) {
7420     Self.Diag(Loc, Note)
7421       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7422       << FixItHint::CreateInsertion(EndLoc, ")");
7423   } else {
7424     // We can't display the parentheses, so just show the bare note.
7425     Self.Diag(Loc, Note) << ParenRange;
7426   }
7427 }
7428 
7429 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7430   return BinaryOperator::isAdditiveOp(Opc) ||
7431          BinaryOperator::isMultiplicativeOp(Opc) ||
7432          BinaryOperator::isShiftOp(Opc);
7433 }
7434 
7435 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7436 /// expression, either using a built-in or overloaded operator,
7437 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7438 /// expression.
7439 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7440                                    Expr **RHSExprs) {
7441   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7442   E = E->IgnoreImpCasts();
7443   E = E->IgnoreConversionOperator();
7444   E = E->IgnoreImpCasts();
7445   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7446     E = MTE->GetTemporaryExpr();
7447     E = E->IgnoreImpCasts();
7448   }
7449 
7450   // Built-in binary operator.
7451   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7452     if (IsArithmeticOp(OP->getOpcode())) {
7453       *Opcode = OP->getOpcode();
7454       *RHSExprs = OP->getRHS();
7455       return true;
7456     }
7457   }
7458 
7459   // Overloaded operator.
7460   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7461     if (Call->getNumArgs() != 2)
7462       return false;
7463 
7464     // Make sure this is really a binary operator that is safe to pass into
7465     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7466     OverloadedOperatorKind OO = Call->getOperator();
7467     if (OO < OO_Plus || OO > OO_Arrow ||
7468         OO == OO_PlusPlus || OO == OO_MinusMinus)
7469       return false;
7470 
7471     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7472     if (IsArithmeticOp(OpKind)) {
7473       *Opcode = OpKind;
7474       *RHSExprs = Call->getArg(1);
7475       return true;
7476     }
7477   }
7478 
7479   return false;
7480 }
7481 
7482 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7483 /// or is a logical expression such as (x==y) which has int type, but is
7484 /// commonly interpreted as boolean.
7485 static bool ExprLooksBoolean(Expr *E) {
7486   E = E->IgnoreParenImpCasts();
7487 
7488   if (E->getType()->isBooleanType())
7489     return true;
7490   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7491     return OP->isComparisonOp() || OP->isLogicalOp();
7492   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7493     return OP->getOpcode() == UO_LNot;
7494   if (E->getType()->isPointerType())
7495     return true;
7496   // FIXME: What about overloaded operator calls returning "unspecified boolean
7497   // type"s (commonly pointer-to-members)?
7498 
7499   return false;
7500 }
7501 
7502 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7503 /// and binary operator are mixed in a way that suggests the programmer assumed
7504 /// the conditional operator has higher precedence, for example:
7505 /// "int x = a + someBinaryCondition ? 1 : 2".
7506 static void DiagnoseConditionalPrecedence(Sema &Self,
7507                                           SourceLocation OpLoc,
7508                                           Expr *Condition,
7509                                           Expr *LHSExpr,
7510                                           Expr *RHSExpr) {
7511   BinaryOperatorKind CondOpcode;
7512   Expr *CondRHS;
7513 
7514   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7515     return;
7516   if (!ExprLooksBoolean(CondRHS))
7517     return;
7518 
7519   // The condition is an arithmetic binary expression, with a right-
7520   // hand side that looks boolean, so warn.
7521 
7522   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7523       << Condition->getSourceRange()
7524       << BinaryOperator::getOpcodeStr(CondOpcode);
7525 
7526   SuggestParentheses(
7527       Self, OpLoc,
7528       Self.PDiag(diag::note_precedence_silence)
7529           << BinaryOperator::getOpcodeStr(CondOpcode),
7530       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7531 
7532   SuggestParentheses(Self, OpLoc,
7533                      Self.PDiag(diag::note_precedence_conditional_first),
7534                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7535 }
7536 
7537 /// Compute the nullability of a conditional expression.
7538 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7539                                               QualType LHSTy, QualType RHSTy,
7540                                               ASTContext &Ctx) {
7541   if (!ResTy->isAnyPointerType())
7542     return ResTy;
7543 
7544   auto GetNullability = [&Ctx](QualType Ty) {
7545     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7546     if (Kind)
7547       return *Kind;
7548     return NullabilityKind::Unspecified;
7549   };
7550 
7551   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7552   NullabilityKind MergedKind;
7553 
7554   // Compute nullability of a binary conditional expression.
7555   if (IsBin) {
7556     if (LHSKind == NullabilityKind::NonNull)
7557       MergedKind = NullabilityKind::NonNull;
7558     else
7559       MergedKind = RHSKind;
7560   // Compute nullability of a normal conditional expression.
7561   } else {
7562     if (LHSKind == NullabilityKind::Nullable ||
7563         RHSKind == NullabilityKind::Nullable)
7564       MergedKind = NullabilityKind::Nullable;
7565     else if (LHSKind == NullabilityKind::NonNull)
7566       MergedKind = RHSKind;
7567     else if (RHSKind == NullabilityKind::NonNull)
7568       MergedKind = LHSKind;
7569     else
7570       MergedKind = NullabilityKind::Unspecified;
7571   }
7572 
7573   // Return if ResTy already has the correct nullability.
7574   if (GetNullability(ResTy) == MergedKind)
7575     return ResTy;
7576 
7577   // Strip all nullability from ResTy.
7578   while (ResTy->getNullability(Ctx))
7579     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7580 
7581   // Create a new AttributedType with the new nullability kind.
7582   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7583   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7584 }
7585 
7586 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7587 /// in the case of a the GNU conditional expr extension.
7588 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7589                                     SourceLocation ColonLoc,
7590                                     Expr *CondExpr, Expr *LHSExpr,
7591                                     Expr *RHSExpr) {
7592   if (!getLangOpts().CPlusPlus) {
7593     // C cannot handle TypoExpr nodes in the condition because it
7594     // doesn't handle dependent types properly, so make sure any TypoExprs have
7595     // been dealt with before checking the operands.
7596     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7597     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7598     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7599 
7600     if (!CondResult.isUsable())
7601       return ExprError();
7602 
7603     if (LHSExpr) {
7604       if (!LHSResult.isUsable())
7605         return ExprError();
7606     }
7607 
7608     if (!RHSResult.isUsable())
7609       return ExprError();
7610 
7611     CondExpr = CondResult.get();
7612     LHSExpr = LHSResult.get();
7613     RHSExpr = RHSResult.get();
7614   }
7615 
7616   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7617   // was the condition.
7618   OpaqueValueExpr *opaqueValue = nullptr;
7619   Expr *commonExpr = nullptr;
7620   if (!LHSExpr) {
7621     commonExpr = CondExpr;
7622     // Lower out placeholder types first.  This is important so that we don't
7623     // try to capture a placeholder. This happens in few cases in C++; such
7624     // as Objective-C++'s dictionary subscripting syntax.
7625     if (commonExpr->hasPlaceholderType()) {
7626       ExprResult result = CheckPlaceholderExpr(commonExpr);
7627       if (!result.isUsable()) return ExprError();
7628       commonExpr = result.get();
7629     }
7630     // We usually want to apply unary conversions *before* saving, except
7631     // in the special case of a C++ l-value conditional.
7632     if (!(getLangOpts().CPlusPlus
7633           && !commonExpr->isTypeDependent()
7634           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7635           && commonExpr->isGLValue()
7636           && commonExpr->isOrdinaryOrBitFieldObject()
7637           && RHSExpr->isOrdinaryOrBitFieldObject()
7638           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7639       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7640       if (commonRes.isInvalid())
7641         return ExprError();
7642       commonExpr = commonRes.get();
7643     }
7644 
7645     // If the common expression is a class or array prvalue, materialize it
7646     // so that we can safely refer to it multiple times.
7647     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7648                                    commonExpr->getType()->isArrayType())) {
7649       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7650       if (MatExpr.isInvalid())
7651         return ExprError();
7652       commonExpr = MatExpr.get();
7653     }
7654 
7655     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7656                                                 commonExpr->getType(),
7657                                                 commonExpr->getValueKind(),
7658                                                 commonExpr->getObjectKind(),
7659                                                 commonExpr);
7660     LHSExpr = CondExpr = opaqueValue;
7661   }
7662 
7663   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7664   ExprValueKind VK = VK_RValue;
7665   ExprObjectKind OK = OK_Ordinary;
7666   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7667   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7668                                              VK, OK, QuestionLoc);
7669   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7670       RHS.isInvalid())
7671     return ExprError();
7672 
7673   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7674                                 RHS.get());
7675 
7676   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7677 
7678   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7679                                          Context);
7680 
7681   if (!commonExpr)
7682     return new (Context)
7683         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7684                             RHS.get(), result, VK, OK);
7685 
7686   return new (Context) BinaryConditionalOperator(
7687       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7688       ColonLoc, result, VK, OK);
7689 }
7690 
7691 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7692 // being closely modeled after the C99 spec:-). The odd characteristic of this
7693 // routine is it effectively iqnores the qualifiers on the top level pointee.
7694 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7695 // FIXME: add a couple examples in this comment.
7696 static Sema::AssignConvertType
7697 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7698   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7699   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7700 
7701   // get the "pointed to" type (ignoring qualifiers at the top level)
7702   const Type *lhptee, *rhptee;
7703   Qualifiers lhq, rhq;
7704   std::tie(lhptee, lhq) =
7705       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7706   std::tie(rhptee, rhq) =
7707       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7708 
7709   Sema::AssignConvertType ConvTy = Sema::Compatible;
7710 
7711   // C99 6.5.16.1p1: This following citation is common to constraints
7712   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7713   // qualifiers of the type *pointed to* by the right;
7714 
7715   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7716   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7717       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7718     // Ignore lifetime for further calculation.
7719     lhq.removeObjCLifetime();
7720     rhq.removeObjCLifetime();
7721   }
7722 
7723   if (!lhq.compatiblyIncludes(rhq)) {
7724     // Treat address-space mismatches as fatal.  TODO: address subspaces
7725     if (!lhq.isAddressSpaceSupersetOf(rhq))
7726       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7727 
7728     // It's okay to add or remove GC or lifetime qualifiers when converting to
7729     // and from void*.
7730     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7731                         .compatiblyIncludes(
7732                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7733              && (lhptee->isVoidType() || rhptee->isVoidType()))
7734       ; // keep old
7735 
7736     // Treat lifetime mismatches as fatal.
7737     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7738       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7739 
7740     // For GCC/MS compatibility, other qualifier mismatches are treated
7741     // as still compatible in C.
7742     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7743   }
7744 
7745   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7746   // incomplete type and the other is a pointer to a qualified or unqualified
7747   // version of void...
7748   if (lhptee->isVoidType()) {
7749     if (rhptee->isIncompleteOrObjectType())
7750       return ConvTy;
7751 
7752     // As an extension, we allow cast to/from void* to function pointer.
7753     assert(rhptee->isFunctionType());
7754     return Sema::FunctionVoidPointer;
7755   }
7756 
7757   if (rhptee->isVoidType()) {
7758     if (lhptee->isIncompleteOrObjectType())
7759       return ConvTy;
7760 
7761     // As an extension, we allow cast to/from void* to function pointer.
7762     assert(lhptee->isFunctionType());
7763     return Sema::FunctionVoidPointer;
7764   }
7765 
7766   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7767   // unqualified versions of compatible types, ...
7768   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7769   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7770     // Check if the pointee types are compatible ignoring the sign.
7771     // We explicitly check for char so that we catch "char" vs
7772     // "unsigned char" on systems where "char" is unsigned.
7773     if (lhptee->isCharType())
7774       ltrans = S.Context.UnsignedCharTy;
7775     else if (lhptee->hasSignedIntegerRepresentation())
7776       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7777 
7778     if (rhptee->isCharType())
7779       rtrans = S.Context.UnsignedCharTy;
7780     else if (rhptee->hasSignedIntegerRepresentation())
7781       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7782 
7783     if (ltrans == rtrans) {
7784       // Types are compatible ignoring the sign. Qualifier incompatibility
7785       // takes priority over sign incompatibility because the sign
7786       // warning can be disabled.
7787       if (ConvTy != Sema::Compatible)
7788         return ConvTy;
7789 
7790       return Sema::IncompatiblePointerSign;
7791     }
7792 
7793     // If we are a multi-level pointer, it's possible that our issue is simply
7794     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7795     // the eventual target type is the same and the pointers have the same
7796     // level of indirection, this must be the issue.
7797     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7798       do {
7799         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7800         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7801       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7802 
7803       if (lhptee == rhptee)
7804         return Sema::IncompatibleNestedPointerQualifiers;
7805     }
7806 
7807     // General pointer incompatibility takes priority over qualifiers.
7808     return Sema::IncompatiblePointer;
7809   }
7810   if (!S.getLangOpts().CPlusPlus &&
7811       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7812     return Sema::IncompatiblePointer;
7813   return ConvTy;
7814 }
7815 
7816 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7817 /// block pointer types are compatible or whether a block and normal pointer
7818 /// are compatible. It is more restrict than comparing two function pointer
7819 // types.
7820 static Sema::AssignConvertType
7821 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7822                                     QualType RHSType) {
7823   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7824   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7825 
7826   QualType lhptee, rhptee;
7827 
7828   // get the "pointed to" type (ignoring qualifiers at the top level)
7829   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7830   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7831 
7832   // In C++, the types have to match exactly.
7833   if (S.getLangOpts().CPlusPlus)
7834     return Sema::IncompatibleBlockPointer;
7835 
7836   Sema::AssignConvertType ConvTy = Sema::Compatible;
7837 
7838   // For blocks we enforce that qualifiers are identical.
7839   Qualifiers LQuals = lhptee.getLocalQualifiers();
7840   Qualifiers RQuals = rhptee.getLocalQualifiers();
7841   if (S.getLangOpts().OpenCL) {
7842     LQuals.removeAddressSpace();
7843     RQuals.removeAddressSpace();
7844   }
7845   if (LQuals != RQuals)
7846     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7847 
7848   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7849   // assignment.
7850   // The current behavior is similar to C++ lambdas. A block might be
7851   // assigned to a variable iff its return type and parameters are compatible
7852   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7853   // an assignment. Presumably it should behave in way that a function pointer
7854   // assignment does in C, so for each parameter and return type:
7855   //  * CVR and address space of LHS should be a superset of CVR and address
7856   //  space of RHS.
7857   //  * unqualified types should be compatible.
7858   if (S.getLangOpts().OpenCL) {
7859     if (!S.Context.typesAreBlockPointerCompatible(
7860             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7861             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7862       return Sema::IncompatibleBlockPointer;
7863   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7864     return Sema::IncompatibleBlockPointer;
7865 
7866   return ConvTy;
7867 }
7868 
7869 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7870 /// for assignment compatibility.
7871 static Sema::AssignConvertType
7872 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7873                                    QualType RHSType) {
7874   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7875   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7876 
7877   if (LHSType->isObjCBuiltinType()) {
7878     // Class is not compatible with ObjC object pointers.
7879     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7880         !RHSType->isObjCQualifiedClassType())
7881       return Sema::IncompatiblePointer;
7882     return Sema::Compatible;
7883   }
7884   if (RHSType->isObjCBuiltinType()) {
7885     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7886         !LHSType->isObjCQualifiedClassType())
7887       return Sema::IncompatiblePointer;
7888     return Sema::Compatible;
7889   }
7890   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7891   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7892 
7893   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7894       // make an exception for id<P>
7895       !LHSType->isObjCQualifiedIdType())
7896     return Sema::CompatiblePointerDiscardsQualifiers;
7897 
7898   if (S.Context.typesAreCompatible(LHSType, RHSType))
7899     return Sema::Compatible;
7900   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7901     return Sema::IncompatibleObjCQualifiedId;
7902   return Sema::IncompatiblePointer;
7903 }
7904 
7905 Sema::AssignConvertType
7906 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7907                                  QualType LHSType, QualType RHSType) {
7908   // Fake up an opaque expression.  We don't actually care about what
7909   // cast operations are required, so if CheckAssignmentConstraints
7910   // adds casts to this they'll be wasted, but fortunately that doesn't
7911   // usually happen on valid code.
7912   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7913   ExprResult RHSPtr = &RHSExpr;
7914   CastKind K;
7915 
7916   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7917 }
7918 
7919 /// This helper function returns true if QT is a vector type that has element
7920 /// type ElementType.
7921 static bool isVector(QualType QT, QualType ElementType) {
7922   if (const VectorType *VT = QT->getAs<VectorType>())
7923     return VT->getElementType() == ElementType;
7924   return false;
7925 }
7926 
7927 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7928 /// has code to accommodate several GCC extensions when type checking
7929 /// pointers. Here are some objectionable examples that GCC considers warnings:
7930 ///
7931 ///  int a, *pint;
7932 ///  short *pshort;
7933 ///  struct foo *pfoo;
7934 ///
7935 ///  pint = pshort; // warning: assignment from incompatible pointer type
7936 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7937 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7938 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7939 ///
7940 /// As a result, the code for dealing with pointers is more complex than the
7941 /// C99 spec dictates.
7942 ///
7943 /// Sets 'Kind' for any result kind except Incompatible.
7944 Sema::AssignConvertType
7945 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7946                                  CastKind &Kind, bool ConvertRHS) {
7947   QualType RHSType = RHS.get()->getType();
7948   QualType OrigLHSType = LHSType;
7949 
7950   // Get canonical types.  We're not formatting these types, just comparing
7951   // them.
7952   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7953   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7954 
7955   // Common case: no conversion required.
7956   if (LHSType == RHSType) {
7957     Kind = CK_NoOp;
7958     return Compatible;
7959   }
7960 
7961   // If we have an atomic type, try a non-atomic assignment, then just add an
7962   // atomic qualification step.
7963   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7964     Sema::AssignConvertType result =
7965       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7966     if (result != Compatible)
7967       return result;
7968     if (Kind != CK_NoOp && ConvertRHS)
7969       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7970     Kind = CK_NonAtomicToAtomic;
7971     return Compatible;
7972   }
7973 
7974   // If the left-hand side is a reference type, then we are in a
7975   // (rare!) case where we've allowed the use of references in C,
7976   // e.g., as a parameter type in a built-in function. In this case,
7977   // just make sure that the type referenced is compatible with the
7978   // right-hand side type. The caller is responsible for adjusting
7979   // LHSType so that the resulting expression does not have reference
7980   // type.
7981   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7982     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7983       Kind = CK_LValueBitCast;
7984       return Compatible;
7985     }
7986     return Incompatible;
7987   }
7988 
7989   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7990   // to the same ExtVector type.
7991   if (LHSType->isExtVectorType()) {
7992     if (RHSType->isExtVectorType())
7993       return Incompatible;
7994     if (RHSType->isArithmeticType()) {
7995       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7996       if (ConvertRHS)
7997         RHS = prepareVectorSplat(LHSType, RHS.get());
7998       Kind = CK_VectorSplat;
7999       return Compatible;
8000     }
8001   }
8002 
8003   // Conversions to or from vector type.
8004   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8005     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8006       // Allow assignments of an AltiVec vector type to an equivalent GCC
8007       // vector type and vice versa
8008       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8009         Kind = CK_BitCast;
8010         return Compatible;
8011       }
8012 
8013       // If we are allowing lax vector conversions, and LHS and RHS are both
8014       // vectors, the total size only needs to be the same. This is a bitcast;
8015       // no bits are changed but the result type is different.
8016       if (isLaxVectorConversion(RHSType, LHSType)) {
8017         Kind = CK_BitCast;
8018         return IncompatibleVectors;
8019       }
8020     }
8021 
8022     // When the RHS comes from another lax conversion (e.g. binops between
8023     // scalars and vectors) the result is canonicalized as a vector. When the
8024     // LHS is also a vector, the lax is allowed by the condition above. Handle
8025     // the case where LHS is a scalar.
8026     if (LHSType->isScalarType()) {
8027       const VectorType *VecType = RHSType->getAs<VectorType>();
8028       if (VecType && VecType->getNumElements() == 1 &&
8029           isLaxVectorConversion(RHSType, LHSType)) {
8030         ExprResult *VecExpr = &RHS;
8031         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8032         Kind = CK_BitCast;
8033         return Compatible;
8034       }
8035     }
8036 
8037     return Incompatible;
8038   }
8039 
8040   // Diagnose attempts to convert between __float128 and long double where
8041   // such conversions currently can't be handled.
8042   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8043     return Incompatible;
8044 
8045   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8046   // discards the imaginary part.
8047   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8048       !LHSType->getAs<ComplexType>())
8049     return Incompatible;
8050 
8051   // Arithmetic conversions.
8052   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8053       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8054     if (ConvertRHS)
8055       Kind = PrepareScalarCast(RHS, LHSType);
8056     return Compatible;
8057   }
8058 
8059   // Conversions to normal pointers.
8060   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8061     // U* -> T*
8062     if (isa<PointerType>(RHSType)) {
8063       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8064       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8065       if (AddrSpaceL != AddrSpaceR)
8066         Kind = CK_AddressSpaceConversion;
8067       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8068         Kind = CK_NoOp;
8069       else
8070         Kind = CK_BitCast;
8071       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8072     }
8073 
8074     // int -> T*
8075     if (RHSType->isIntegerType()) {
8076       Kind = CK_IntegralToPointer; // FIXME: null?
8077       return IntToPointer;
8078     }
8079 
8080     // C pointers are not compatible with ObjC object pointers,
8081     // with two exceptions:
8082     if (isa<ObjCObjectPointerType>(RHSType)) {
8083       //  - conversions to void*
8084       if (LHSPointer->getPointeeType()->isVoidType()) {
8085         Kind = CK_BitCast;
8086         return Compatible;
8087       }
8088 
8089       //  - conversions from 'Class' to the redefinition type
8090       if (RHSType->isObjCClassType() &&
8091           Context.hasSameType(LHSType,
8092                               Context.getObjCClassRedefinitionType())) {
8093         Kind = CK_BitCast;
8094         return Compatible;
8095       }
8096 
8097       Kind = CK_BitCast;
8098       return IncompatiblePointer;
8099     }
8100 
8101     // U^ -> void*
8102     if (RHSType->getAs<BlockPointerType>()) {
8103       if (LHSPointer->getPointeeType()->isVoidType()) {
8104         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8105         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8106                                 ->getPointeeType()
8107                                 .getAddressSpace();
8108         Kind =
8109             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8110         return Compatible;
8111       }
8112     }
8113 
8114     return Incompatible;
8115   }
8116 
8117   // Conversions to block pointers.
8118   if (isa<BlockPointerType>(LHSType)) {
8119     // U^ -> T^
8120     if (RHSType->isBlockPointerType()) {
8121       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8122                               ->getPointeeType()
8123                               .getAddressSpace();
8124       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8125                               ->getPointeeType()
8126                               .getAddressSpace();
8127       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8128       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8129     }
8130 
8131     // int or null -> T^
8132     if (RHSType->isIntegerType()) {
8133       Kind = CK_IntegralToPointer; // FIXME: null
8134       return IntToBlockPointer;
8135     }
8136 
8137     // id -> T^
8138     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8139       Kind = CK_AnyPointerToBlockPointerCast;
8140       return Compatible;
8141     }
8142 
8143     // void* -> T^
8144     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8145       if (RHSPT->getPointeeType()->isVoidType()) {
8146         Kind = CK_AnyPointerToBlockPointerCast;
8147         return Compatible;
8148       }
8149 
8150     return Incompatible;
8151   }
8152 
8153   // Conversions to Objective-C pointers.
8154   if (isa<ObjCObjectPointerType>(LHSType)) {
8155     // A* -> B*
8156     if (RHSType->isObjCObjectPointerType()) {
8157       Kind = CK_BitCast;
8158       Sema::AssignConvertType result =
8159         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8160       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8161           result == Compatible &&
8162           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8163         result = IncompatibleObjCWeakRef;
8164       return result;
8165     }
8166 
8167     // int or null -> A*
8168     if (RHSType->isIntegerType()) {
8169       Kind = CK_IntegralToPointer; // FIXME: null
8170       return IntToPointer;
8171     }
8172 
8173     // In general, C pointers are not compatible with ObjC object pointers,
8174     // with two exceptions:
8175     if (isa<PointerType>(RHSType)) {
8176       Kind = CK_CPointerToObjCPointerCast;
8177 
8178       //  - conversions from 'void*'
8179       if (RHSType->isVoidPointerType()) {
8180         return Compatible;
8181       }
8182 
8183       //  - conversions to 'Class' from its redefinition type
8184       if (LHSType->isObjCClassType() &&
8185           Context.hasSameType(RHSType,
8186                               Context.getObjCClassRedefinitionType())) {
8187         return Compatible;
8188       }
8189 
8190       return IncompatiblePointer;
8191     }
8192 
8193     // Only under strict condition T^ is compatible with an Objective-C pointer.
8194     if (RHSType->isBlockPointerType() &&
8195         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8196       if (ConvertRHS)
8197         maybeExtendBlockObject(RHS);
8198       Kind = CK_BlockPointerToObjCPointerCast;
8199       return Compatible;
8200     }
8201 
8202     return Incompatible;
8203   }
8204 
8205   // Conversions from pointers that are not covered by the above.
8206   if (isa<PointerType>(RHSType)) {
8207     // T* -> _Bool
8208     if (LHSType == Context.BoolTy) {
8209       Kind = CK_PointerToBoolean;
8210       return Compatible;
8211     }
8212 
8213     // T* -> int
8214     if (LHSType->isIntegerType()) {
8215       Kind = CK_PointerToIntegral;
8216       return PointerToInt;
8217     }
8218 
8219     return Incompatible;
8220   }
8221 
8222   // Conversions from Objective-C pointers that are not covered by the above.
8223   if (isa<ObjCObjectPointerType>(RHSType)) {
8224     // T* -> _Bool
8225     if (LHSType == Context.BoolTy) {
8226       Kind = CK_PointerToBoolean;
8227       return Compatible;
8228     }
8229 
8230     // T* -> int
8231     if (LHSType->isIntegerType()) {
8232       Kind = CK_PointerToIntegral;
8233       return PointerToInt;
8234     }
8235 
8236     return Incompatible;
8237   }
8238 
8239   // struct A -> struct B
8240   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8241     if (Context.typesAreCompatible(LHSType, RHSType)) {
8242       Kind = CK_NoOp;
8243       return Compatible;
8244     }
8245   }
8246 
8247   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8248     Kind = CK_IntToOCLSampler;
8249     return Compatible;
8250   }
8251 
8252   return Incompatible;
8253 }
8254 
8255 /// Constructs a transparent union from an expression that is
8256 /// used to initialize the transparent union.
8257 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8258                                       ExprResult &EResult, QualType UnionType,
8259                                       FieldDecl *Field) {
8260   // Build an initializer list that designates the appropriate member
8261   // of the transparent union.
8262   Expr *E = EResult.get();
8263   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8264                                                    E, SourceLocation());
8265   Initializer->setType(UnionType);
8266   Initializer->setInitializedFieldInUnion(Field);
8267 
8268   // Build a compound literal constructing a value of the transparent
8269   // union type from this initializer list.
8270   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8271   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8272                                         VK_RValue, Initializer, false);
8273 }
8274 
8275 Sema::AssignConvertType
8276 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8277                                                ExprResult &RHS) {
8278   QualType RHSType = RHS.get()->getType();
8279 
8280   // If the ArgType is a Union type, we want to handle a potential
8281   // transparent_union GCC extension.
8282   const RecordType *UT = ArgType->getAsUnionType();
8283   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8284     return Incompatible;
8285 
8286   // The field to initialize within the transparent union.
8287   RecordDecl *UD = UT->getDecl();
8288   FieldDecl *InitField = nullptr;
8289   // It's compatible if the expression matches any of the fields.
8290   for (auto *it : UD->fields()) {
8291     if (it->getType()->isPointerType()) {
8292       // If the transparent union contains a pointer type, we allow:
8293       // 1) void pointer
8294       // 2) null pointer constant
8295       if (RHSType->isPointerType())
8296         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8297           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8298           InitField = it;
8299           break;
8300         }
8301 
8302       if (RHS.get()->isNullPointerConstant(Context,
8303                                            Expr::NPC_ValueDependentIsNull)) {
8304         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8305                                 CK_NullToPointer);
8306         InitField = it;
8307         break;
8308       }
8309     }
8310 
8311     CastKind Kind;
8312     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8313           == Compatible) {
8314       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8315       InitField = it;
8316       break;
8317     }
8318   }
8319 
8320   if (!InitField)
8321     return Incompatible;
8322 
8323   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8324   return Compatible;
8325 }
8326 
8327 Sema::AssignConvertType
8328 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8329                                        bool Diagnose,
8330                                        bool DiagnoseCFAudited,
8331                                        bool ConvertRHS) {
8332   // We need to be able to tell the caller whether we diagnosed a problem, if
8333   // they ask us to issue diagnostics.
8334   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8335 
8336   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8337   // we can't avoid *all* modifications at the moment, so we need some somewhere
8338   // to put the updated value.
8339   ExprResult LocalRHS = CallerRHS;
8340   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8341 
8342   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8343     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8344       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8345           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8346         Diag(RHS.get()->getExprLoc(),
8347              diag::warn_noderef_to_dereferenceable_pointer)
8348             << RHS.get()->getSourceRange();
8349       }
8350     }
8351   }
8352 
8353   if (getLangOpts().CPlusPlus) {
8354     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8355       // C++ 5.17p3: If the left operand is not of class type, the
8356       // expression is implicitly converted (C++ 4) to the
8357       // cv-unqualified type of the left operand.
8358       QualType RHSType = RHS.get()->getType();
8359       if (Diagnose) {
8360         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8361                                         AA_Assigning);
8362       } else {
8363         ImplicitConversionSequence ICS =
8364             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8365                                   /*SuppressUserConversions=*/false,
8366                                   /*AllowExplicit=*/false,
8367                                   /*InOverloadResolution=*/false,
8368                                   /*CStyle=*/false,
8369                                   /*AllowObjCWritebackConversion=*/false);
8370         if (ICS.isFailure())
8371           return Incompatible;
8372         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8373                                         ICS, AA_Assigning);
8374       }
8375       if (RHS.isInvalid())
8376         return Incompatible;
8377       Sema::AssignConvertType result = Compatible;
8378       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8379           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8380         result = IncompatibleObjCWeakRef;
8381       return result;
8382     }
8383 
8384     // FIXME: Currently, we fall through and treat C++ classes like C
8385     // structures.
8386     // FIXME: We also fall through for atomics; not sure what should
8387     // happen there, though.
8388   } else if (RHS.get()->getType() == Context.OverloadTy) {
8389     // As a set of extensions to C, we support overloading on functions. These
8390     // functions need to be resolved here.
8391     DeclAccessPair DAP;
8392     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8393             RHS.get(), LHSType, /*Complain=*/false, DAP))
8394       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8395     else
8396       return Incompatible;
8397   }
8398 
8399   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8400   // a null pointer constant.
8401   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8402        LHSType->isBlockPointerType()) &&
8403       RHS.get()->isNullPointerConstant(Context,
8404                                        Expr::NPC_ValueDependentIsNull)) {
8405     if (Diagnose || ConvertRHS) {
8406       CastKind Kind;
8407       CXXCastPath Path;
8408       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8409                              /*IgnoreBaseAccess=*/false, Diagnose);
8410       if (ConvertRHS)
8411         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8412     }
8413     return Compatible;
8414   }
8415 
8416   // OpenCL queue_t type assignment.
8417   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8418                                  Context, Expr::NPC_ValueDependentIsNull)) {
8419     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8420     return Compatible;
8421   }
8422 
8423   // This check seems unnatural, however it is necessary to ensure the proper
8424   // conversion of functions/arrays. If the conversion were done for all
8425   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8426   // expressions that suppress this implicit conversion (&, sizeof).
8427   //
8428   // Suppress this for references: C++ 8.5.3p5.
8429   if (!LHSType->isReferenceType()) {
8430     // FIXME: We potentially allocate here even if ConvertRHS is false.
8431     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8432     if (RHS.isInvalid())
8433       return Incompatible;
8434   }
8435   CastKind Kind;
8436   Sema::AssignConvertType result =
8437     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8438 
8439   // C99 6.5.16.1p2: The value of the right operand is converted to the
8440   // type of the assignment expression.
8441   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8442   // so that we can use references in built-in functions even in C.
8443   // The getNonReferenceType() call makes sure that the resulting expression
8444   // does not have reference type.
8445   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8446     QualType Ty = LHSType.getNonLValueExprType(Context);
8447     Expr *E = RHS.get();
8448 
8449     // Check for various Objective-C errors. If we are not reporting
8450     // diagnostics and just checking for errors, e.g., during overload
8451     // resolution, return Incompatible to indicate the failure.
8452     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8453         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8454                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8455       if (!Diagnose)
8456         return Incompatible;
8457     }
8458     if (getLangOpts().ObjC &&
8459         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8460                                            E->getType(), E, Diagnose) ||
8461          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8462       if (!Diagnose)
8463         return Incompatible;
8464       // Replace the expression with a corrected version and continue so we
8465       // can find further errors.
8466       RHS = E;
8467       return Compatible;
8468     }
8469 
8470     if (ConvertRHS)
8471       RHS = ImpCastExprToType(E, Ty, Kind);
8472   }
8473 
8474   return result;
8475 }
8476 
8477 namespace {
8478 /// The original operand to an operator, prior to the application of the usual
8479 /// arithmetic conversions and converting the arguments of a builtin operator
8480 /// candidate.
8481 struct OriginalOperand {
8482   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8483     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8484       Op = MTE->GetTemporaryExpr();
8485     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8486       Op = BTE->getSubExpr();
8487     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8488       Orig = ICE->getSubExprAsWritten();
8489       Conversion = ICE->getConversionFunction();
8490     }
8491   }
8492 
8493   QualType getType() const { return Orig->getType(); }
8494 
8495   Expr *Orig;
8496   NamedDecl *Conversion;
8497 };
8498 }
8499 
8500 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8501                                ExprResult &RHS) {
8502   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8503 
8504   Diag(Loc, diag::err_typecheck_invalid_operands)
8505     << OrigLHS.getType() << OrigRHS.getType()
8506     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8507 
8508   // If a user-defined conversion was applied to either of the operands prior
8509   // to applying the built-in operator rules, tell the user about it.
8510   if (OrigLHS.Conversion) {
8511     Diag(OrigLHS.Conversion->getLocation(),
8512          diag::note_typecheck_invalid_operands_converted)
8513       << 0 << LHS.get()->getType();
8514   }
8515   if (OrigRHS.Conversion) {
8516     Diag(OrigRHS.Conversion->getLocation(),
8517          diag::note_typecheck_invalid_operands_converted)
8518       << 1 << RHS.get()->getType();
8519   }
8520 
8521   return QualType();
8522 }
8523 
8524 // Diagnose cases where a scalar was implicitly converted to a vector and
8525 // diagnose the underlying types. Otherwise, diagnose the error
8526 // as invalid vector logical operands for non-C++ cases.
8527 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8528                                             ExprResult &RHS) {
8529   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8530   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8531 
8532   bool LHSNatVec = LHSType->isVectorType();
8533   bool RHSNatVec = RHSType->isVectorType();
8534 
8535   if (!(LHSNatVec && RHSNatVec)) {
8536     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8537     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8538     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8539         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8540         << Vector->getSourceRange();
8541     return QualType();
8542   }
8543 
8544   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8545       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8546       << RHS.get()->getSourceRange();
8547 
8548   return QualType();
8549 }
8550 
8551 /// Try to convert a value of non-vector type to a vector type by converting
8552 /// the type to the element type of the vector and then performing a splat.
8553 /// If the language is OpenCL, we only use conversions that promote scalar
8554 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8555 /// for float->int.
8556 ///
8557 /// OpenCL V2.0 6.2.6.p2:
8558 /// An error shall occur if any scalar operand type has greater rank
8559 /// than the type of the vector element.
8560 ///
8561 /// \param scalar - if non-null, actually perform the conversions
8562 /// \return true if the operation fails (but without diagnosing the failure)
8563 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8564                                      QualType scalarTy,
8565                                      QualType vectorEltTy,
8566                                      QualType vectorTy,
8567                                      unsigned &DiagID) {
8568   // The conversion to apply to the scalar before splatting it,
8569   // if necessary.
8570   CastKind scalarCast = CK_NoOp;
8571 
8572   if (vectorEltTy->isIntegralType(S.Context)) {
8573     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8574         (scalarTy->isIntegerType() &&
8575          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8576       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8577       return true;
8578     }
8579     if (!scalarTy->isIntegralType(S.Context))
8580       return true;
8581     scalarCast = CK_IntegralCast;
8582   } else if (vectorEltTy->isRealFloatingType()) {
8583     if (scalarTy->isRealFloatingType()) {
8584       if (S.getLangOpts().OpenCL &&
8585           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8586         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8587         return true;
8588       }
8589       scalarCast = CK_FloatingCast;
8590     }
8591     else if (scalarTy->isIntegralType(S.Context))
8592       scalarCast = CK_IntegralToFloating;
8593     else
8594       return true;
8595   } else {
8596     return true;
8597   }
8598 
8599   // Adjust scalar if desired.
8600   if (scalar) {
8601     if (scalarCast != CK_NoOp)
8602       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8603     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8604   }
8605   return false;
8606 }
8607 
8608 /// Convert vector E to a vector with the same number of elements but different
8609 /// element type.
8610 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8611   const auto *VecTy = E->getType()->getAs<VectorType>();
8612   assert(VecTy && "Expression E must be a vector");
8613   QualType NewVecTy = S.Context.getVectorType(ElementType,
8614                                               VecTy->getNumElements(),
8615                                               VecTy->getVectorKind());
8616 
8617   // Look through the implicit cast. Return the subexpression if its type is
8618   // NewVecTy.
8619   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8620     if (ICE->getSubExpr()->getType() == NewVecTy)
8621       return ICE->getSubExpr();
8622 
8623   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8624   return S.ImpCastExprToType(E, NewVecTy, Cast);
8625 }
8626 
8627 /// Test if a (constant) integer Int can be casted to another integer type
8628 /// IntTy without losing precision.
8629 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8630                                       QualType OtherIntTy) {
8631   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8632 
8633   // Reject cases where the value of the Int is unknown as that would
8634   // possibly cause truncation, but accept cases where the scalar can be
8635   // demoted without loss of precision.
8636   Expr::EvalResult EVResult;
8637   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8638   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8639   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8640   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8641 
8642   if (CstInt) {
8643     // If the scalar is constant and is of a higher order and has more active
8644     // bits that the vector element type, reject it.
8645     llvm::APSInt Result = EVResult.Val.getInt();
8646     unsigned NumBits = IntSigned
8647                            ? (Result.isNegative() ? Result.getMinSignedBits()
8648                                                   : Result.getActiveBits())
8649                            : Result.getActiveBits();
8650     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8651       return true;
8652 
8653     // If the signedness of the scalar type and the vector element type
8654     // differs and the number of bits is greater than that of the vector
8655     // element reject it.
8656     return (IntSigned != OtherIntSigned &&
8657             NumBits > S.Context.getIntWidth(OtherIntTy));
8658   }
8659 
8660   // Reject cases where the value of the scalar is not constant and it's
8661   // order is greater than that of the vector element type.
8662   return (Order < 0);
8663 }
8664 
8665 /// Test if a (constant) integer Int can be casted to floating point type
8666 /// FloatTy without losing precision.
8667 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8668                                      QualType FloatTy) {
8669   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8670 
8671   // Determine if the integer constant can be expressed as a floating point
8672   // number of the appropriate type.
8673   Expr::EvalResult EVResult;
8674   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8675 
8676   uint64_t Bits = 0;
8677   if (CstInt) {
8678     // Reject constants that would be truncated if they were converted to
8679     // the floating point type. Test by simple to/from conversion.
8680     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8681     //        could be avoided if there was a convertFromAPInt method
8682     //        which could signal back if implicit truncation occurred.
8683     llvm::APSInt Result = EVResult.Val.getInt();
8684     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8685     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8686                            llvm::APFloat::rmTowardZero);
8687     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8688                              !IntTy->hasSignedIntegerRepresentation());
8689     bool Ignored = false;
8690     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8691                            &Ignored);
8692     if (Result != ConvertBack)
8693       return true;
8694   } else {
8695     // Reject types that cannot be fully encoded into the mantissa of
8696     // the float.
8697     Bits = S.Context.getTypeSize(IntTy);
8698     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8699         S.Context.getFloatTypeSemantics(FloatTy));
8700     if (Bits > FloatPrec)
8701       return true;
8702   }
8703 
8704   return false;
8705 }
8706 
8707 /// Attempt to convert and splat Scalar into a vector whose types matches
8708 /// Vector following GCC conversion rules. The rule is that implicit
8709 /// conversion can occur when Scalar can be casted to match Vector's element
8710 /// type without causing truncation of Scalar.
8711 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8712                                         ExprResult *Vector) {
8713   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8714   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8715   const VectorType *VT = VectorTy->getAs<VectorType>();
8716 
8717   assert(!isa<ExtVectorType>(VT) &&
8718          "ExtVectorTypes should not be handled here!");
8719 
8720   QualType VectorEltTy = VT->getElementType();
8721 
8722   // Reject cases where the vector element type or the scalar element type are
8723   // not integral or floating point types.
8724   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8725     return true;
8726 
8727   // The conversion to apply to the scalar before splatting it,
8728   // if necessary.
8729   CastKind ScalarCast = CK_NoOp;
8730 
8731   // Accept cases where the vector elements are integers and the scalar is
8732   // an integer.
8733   // FIXME: Notionally if the scalar was a floating point value with a precise
8734   //        integral representation, we could cast it to an appropriate integer
8735   //        type and then perform the rest of the checks here. GCC will perform
8736   //        this conversion in some cases as determined by the input language.
8737   //        We should accept it on a language independent basis.
8738   if (VectorEltTy->isIntegralType(S.Context) &&
8739       ScalarTy->isIntegralType(S.Context) &&
8740       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8741 
8742     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8743       return true;
8744 
8745     ScalarCast = CK_IntegralCast;
8746   } else if (VectorEltTy->isRealFloatingType()) {
8747     if (ScalarTy->isRealFloatingType()) {
8748 
8749       // Reject cases where the scalar type is not a constant and has a higher
8750       // Order than the vector element type.
8751       llvm::APFloat Result(0.0);
8752       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8753       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8754       if (!CstScalar && Order < 0)
8755         return true;
8756 
8757       // If the scalar cannot be safely casted to the vector element type,
8758       // reject it.
8759       if (CstScalar) {
8760         bool Truncated = false;
8761         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8762                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8763         if (Truncated)
8764           return true;
8765       }
8766 
8767       ScalarCast = CK_FloatingCast;
8768     } else if (ScalarTy->isIntegralType(S.Context)) {
8769       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8770         return true;
8771 
8772       ScalarCast = CK_IntegralToFloating;
8773     } else
8774       return true;
8775   }
8776 
8777   // Adjust scalar if desired.
8778   if (Scalar) {
8779     if (ScalarCast != CK_NoOp)
8780       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8781     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8782   }
8783   return false;
8784 }
8785 
8786 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8787                                    SourceLocation Loc, bool IsCompAssign,
8788                                    bool AllowBothBool,
8789                                    bool AllowBoolConversions) {
8790   if (!IsCompAssign) {
8791     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8792     if (LHS.isInvalid())
8793       return QualType();
8794   }
8795   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8796   if (RHS.isInvalid())
8797     return QualType();
8798 
8799   // For conversion purposes, we ignore any qualifiers.
8800   // For example, "const float" and "float" are equivalent.
8801   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8802   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8803 
8804   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8805   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8806   assert(LHSVecType || RHSVecType);
8807 
8808   // AltiVec-style "vector bool op vector bool" combinations are allowed
8809   // for some operators but not others.
8810   if (!AllowBothBool &&
8811       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8812       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8813     return InvalidOperands(Loc, LHS, RHS);
8814 
8815   // If the vector types are identical, return.
8816   if (Context.hasSameType(LHSType, RHSType))
8817     return LHSType;
8818 
8819   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8820   if (LHSVecType && RHSVecType &&
8821       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8822     if (isa<ExtVectorType>(LHSVecType)) {
8823       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8824       return LHSType;
8825     }
8826 
8827     if (!IsCompAssign)
8828       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8829     return RHSType;
8830   }
8831 
8832   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8833   // can be mixed, with the result being the non-bool type.  The non-bool
8834   // operand must have integer element type.
8835   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8836       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8837       (Context.getTypeSize(LHSVecType->getElementType()) ==
8838        Context.getTypeSize(RHSVecType->getElementType()))) {
8839     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8840         LHSVecType->getElementType()->isIntegerType() &&
8841         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8842       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8843       return LHSType;
8844     }
8845     if (!IsCompAssign &&
8846         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8847         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8848         RHSVecType->getElementType()->isIntegerType()) {
8849       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8850       return RHSType;
8851     }
8852   }
8853 
8854   // If there's a vector type and a scalar, try to convert the scalar to
8855   // the vector element type and splat.
8856   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8857   if (!RHSVecType) {
8858     if (isa<ExtVectorType>(LHSVecType)) {
8859       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8860                                     LHSVecType->getElementType(), LHSType,
8861                                     DiagID))
8862         return LHSType;
8863     } else {
8864       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8865         return LHSType;
8866     }
8867   }
8868   if (!LHSVecType) {
8869     if (isa<ExtVectorType>(RHSVecType)) {
8870       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8871                                     LHSType, RHSVecType->getElementType(),
8872                                     RHSType, DiagID))
8873         return RHSType;
8874     } else {
8875       if (LHS.get()->getValueKind() == VK_LValue ||
8876           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8877         return RHSType;
8878     }
8879   }
8880 
8881   // FIXME: The code below also handles conversion between vectors and
8882   // non-scalars, we should break this down into fine grained specific checks
8883   // and emit proper diagnostics.
8884   QualType VecType = LHSVecType ? LHSType : RHSType;
8885   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8886   QualType OtherType = LHSVecType ? RHSType : LHSType;
8887   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8888   if (isLaxVectorConversion(OtherType, VecType)) {
8889     // If we're allowing lax vector conversions, only the total (data) size
8890     // needs to be the same. For non compound assignment, if one of the types is
8891     // scalar, the result is always the vector type.
8892     if (!IsCompAssign) {
8893       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8894       return VecType;
8895     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8896     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8897     // type. Note that this is already done by non-compound assignments in
8898     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8899     // <1 x T> -> T. The result is also a vector type.
8900     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8901                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8902       ExprResult *RHSExpr = &RHS;
8903       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8904       return VecType;
8905     }
8906   }
8907 
8908   // Okay, the expression is invalid.
8909 
8910   // If there's a non-vector, non-real operand, diagnose that.
8911   if ((!RHSVecType && !RHSType->isRealType()) ||
8912       (!LHSVecType && !LHSType->isRealType())) {
8913     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8914       << LHSType << RHSType
8915       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8916     return QualType();
8917   }
8918 
8919   // OpenCL V1.1 6.2.6.p1:
8920   // If the operands are of more than one vector type, then an error shall
8921   // occur. Implicit conversions between vector types are not permitted, per
8922   // section 6.2.1.
8923   if (getLangOpts().OpenCL &&
8924       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8925       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8926     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8927                                                            << RHSType;
8928     return QualType();
8929   }
8930 
8931 
8932   // If there is a vector type that is not a ExtVector and a scalar, we reach
8933   // this point if scalar could not be converted to the vector's element type
8934   // without truncation.
8935   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8936       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8937     QualType Scalar = LHSVecType ? RHSType : LHSType;
8938     QualType Vector = LHSVecType ? LHSType : RHSType;
8939     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8940     Diag(Loc,
8941          diag::err_typecheck_vector_not_convertable_implict_truncation)
8942         << ScalarOrVector << Scalar << Vector;
8943 
8944     return QualType();
8945   }
8946 
8947   // Otherwise, use the generic diagnostic.
8948   Diag(Loc, DiagID)
8949     << LHSType << RHSType
8950     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8951   return QualType();
8952 }
8953 
8954 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8955 // expression.  These are mainly cases where the null pointer is used as an
8956 // integer instead of a pointer.
8957 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8958                                 SourceLocation Loc, bool IsCompare) {
8959   // The canonical way to check for a GNU null is with isNullPointerConstant,
8960   // but we use a bit of a hack here for speed; this is a relatively
8961   // hot path, and isNullPointerConstant is slow.
8962   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8963   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8964 
8965   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8966 
8967   // Avoid analyzing cases where the result will either be invalid (and
8968   // diagnosed as such) or entirely valid and not something to warn about.
8969   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8970       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8971     return;
8972 
8973   // Comparison operations would not make sense with a null pointer no matter
8974   // what the other expression is.
8975   if (!IsCompare) {
8976     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8977         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8978         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8979     return;
8980   }
8981 
8982   // The rest of the operations only make sense with a null pointer
8983   // if the other expression is a pointer.
8984   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8985       NonNullType->canDecayToPointerType())
8986     return;
8987 
8988   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8989       << LHSNull /* LHS is NULL */ << NonNullType
8990       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8991 }
8992 
8993 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8994                                           SourceLocation Loc) {
8995   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8996   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
8997   if (!LUE || !RUE)
8998     return;
8999   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9000       RUE->getKind() != UETT_SizeOf)
9001     return;
9002 
9003   QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
9004   QualType RHSTy;
9005 
9006   if (RUE->isArgumentType())
9007     RHSTy = RUE->getArgumentType();
9008   else
9009     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9010 
9011   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
9012     return;
9013   if (LHSTy->getPointeeType() != RHSTy)
9014     return;
9015 
9016   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9017 }
9018 
9019 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9020                                                ExprResult &RHS,
9021                                                SourceLocation Loc, bool IsDiv) {
9022   // Check for division/remainder by zero.
9023   Expr::EvalResult RHSValue;
9024   if (!RHS.get()->isValueDependent() &&
9025       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9026       RHSValue.Val.getInt() == 0)
9027     S.DiagRuntimeBehavior(Loc, RHS.get(),
9028                           S.PDiag(diag::warn_remainder_division_by_zero)
9029                             << IsDiv << RHS.get()->getSourceRange());
9030 }
9031 
9032 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9033                                            SourceLocation Loc,
9034                                            bool IsCompAssign, bool IsDiv) {
9035   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9036 
9037   if (LHS.get()->getType()->isVectorType() ||
9038       RHS.get()->getType()->isVectorType())
9039     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9040                                /*AllowBothBool*/getLangOpts().AltiVec,
9041                                /*AllowBoolConversions*/false);
9042 
9043   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9044   if (LHS.isInvalid() || RHS.isInvalid())
9045     return QualType();
9046 
9047 
9048   if (compType.isNull() || !compType->isArithmeticType())
9049     return InvalidOperands(Loc, LHS, RHS);
9050   if (IsDiv) {
9051     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9052     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9053   }
9054   return compType;
9055 }
9056 
9057 QualType Sema::CheckRemainderOperands(
9058   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9059   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9060 
9061   if (LHS.get()->getType()->isVectorType() ||
9062       RHS.get()->getType()->isVectorType()) {
9063     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9064         RHS.get()->getType()->hasIntegerRepresentation())
9065       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9066                                  /*AllowBothBool*/getLangOpts().AltiVec,
9067                                  /*AllowBoolConversions*/false);
9068     return InvalidOperands(Loc, LHS, RHS);
9069   }
9070 
9071   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9072   if (LHS.isInvalid() || RHS.isInvalid())
9073     return QualType();
9074 
9075   if (compType.isNull() || !compType->isIntegerType())
9076     return InvalidOperands(Loc, LHS, RHS);
9077   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9078   return compType;
9079 }
9080 
9081 /// Diagnose invalid arithmetic on two void pointers.
9082 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9083                                                 Expr *LHSExpr, Expr *RHSExpr) {
9084   S.Diag(Loc, S.getLangOpts().CPlusPlus
9085                 ? diag::err_typecheck_pointer_arith_void_type
9086                 : diag::ext_gnu_void_ptr)
9087     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9088                             << RHSExpr->getSourceRange();
9089 }
9090 
9091 /// Diagnose invalid arithmetic on a void pointer.
9092 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9093                                             Expr *Pointer) {
9094   S.Diag(Loc, S.getLangOpts().CPlusPlus
9095                 ? diag::err_typecheck_pointer_arith_void_type
9096                 : diag::ext_gnu_void_ptr)
9097     << 0 /* one pointer */ << Pointer->getSourceRange();
9098 }
9099 
9100 /// Diagnose invalid arithmetic on a null pointer.
9101 ///
9102 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9103 /// idiom, which we recognize as a GNU extension.
9104 ///
9105 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9106                                             Expr *Pointer, bool IsGNUIdiom) {
9107   if (IsGNUIdiom)
9108     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9109       << Pointer->getSourceRange();
9110   else
9111     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9112       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9113 }
9114 
9115 /// Diagnose invalid arithmetic on two function pointers.
9116 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9117                                                     Expr *LHS, Expr *RHS) {
9118   assert(LHS->getType()->isAnyPointerType());
9119   assert(RHS->getType()->isAnyPointerType());
9120   S.Diag(Loc, S.getLangOpts().CPlusPlus
9121                 ? diag::err_typecheck_pointer_arith_function_type
9122                 : diag::ext_gnu_ptr_func_arith)
9123     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9124     // We only show the second type if it differs from the first.
9125     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9126                                                    RHS->getType())
9127     << RHS->getType()->getPointeeType()
9128     << LHS->getSourceRange() << RHS->getSourceRange();
9129 }
9130 
9131 /// Diagnose invalid arithmetic on a function pointer.
9132 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9133                                                 Expr *Pointer) {
9134   assert(Pointer->getType()->isAnyPointerType());
9135   S.Diag(Loc, S.getLangOpts().CPlusPlus
9136                 ? diag::err_typecheck_pointer_arith_function_type
9137                 : diag::ext_gnu_ptr_func_arith)
9138     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9139     << 0 /* one pointer, so only one type */
9140     << Pointer->getSourceRange();
9141 }
9142 
9143 /// Emit error if Operand is incomplete pointer type
9144 ///
9145 /// \returns True if pointer has incomplete type
9146 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9147                                                  Expr *Operand) {
9148   QualType ResType = Operand->getType();
9149   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9150     ResType = ResAtomicType->getValueType();
9151 
9152   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9153   QualType PointeeTy = ResType->getPointeeType();
9154   return S.RequireCompleteType(Loc, PointeeTy,
9155                                diag::err_typecheck_arithmetic_incomplete_type,
9156                                PointeeTy, Operand->getSourceRange());
9157 }
9158 
9159 /// Check the validity of an arithmetic pointer operand.
9160 ///
9161 /// If the operand has pointer type, this code will check for pointer types
9162 /// which are invalid in arithmetic operations. These will be diagnosed
9163 /// appropriately, including whether or not the use is supported as an
9164 /// extension.
9165 ///
9166 /// \returns True when the operand is valid to use (even if as an extension).
9167 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9168                                             Expr *Operand) {
9169   QualType ResType = Operand->getType();
9170   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9171     ResType = ResAtomicType->getValueType();
9172 
9173   if (!ResType->isAnyPointerType()) return true;
9174 
9175   QualType PointeeTy = ResType->getPointeeType();
9176   if (PointeeTy->isVoidType()) {
9177     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9178     return !S.getLangOpts().CPlusPlus;
9179   }
9180   if (PointeeTy->isFunctionType()) {
9181     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9182     return !S.getLangOpts().CPlusPlus;
9183   }
9184 
9185   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9186 
9187   return true;
9188 }
9189 
9190 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9191 /// operands.
9192 ///
9193 /// This routine will diagnose any invalid arithmetic on pointer operands much
9194 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9195 /// for emitting a single diagnostic even for operations where both LHS and RHS
9196 /// are (potentially problematic) pointers.
9197 ///
9198 /// \returns True when the operand is valid to use (even if as an extension).
9199 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9200                                                 Expr *LHSExpr, Expr *RHSExpr) {
9201   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9202   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9203   if (!isLHSPointer && !isRHSPointer) return true;
9204 
9205   QualType LHSPointeeTy, RHSPointeeTy;
9206   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9207   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9208 
9209   // if both are pointers check if operation is valid wrt address spaces
9210   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9211     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9212     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9213     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9214       S.Diag(Loc,
9215              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9216           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9217           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9218       return false;
9219     }
9220   }
9221 
9222   // Check for arithmetic on pointers to incomplete types.
9223   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9224   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9225   if (isLHSVoidPtr || isRHSVoidPtr) {
9226     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9227     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9228     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9229 
9230     return !S.getLangOpts().CPlusPlus;
9231   }
9232 
9233   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9234   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9235   if (isLHSFuncPtr || isRHSFuncPtr) {
9236     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9237     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9238                                                                 RHSExpr);
9239     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9240 
9241     return !S.getLangOpts().CPlusPlus;
9242   }
9243 
9244   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9245     return false;
9246   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9247     return false;
9248 
9249   return true;
9250 }
9251 
9252 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9253 /// literal.
9254 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9255                                   Expr *LHSExpr, Expr *RHSExpr) {
9256   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9257   Expr* IndexExpr = RHSExpr;
9258   if (!StrExpr) {
9259     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9260     IndexExpr = LHSExpr;
9261   }
9262 
9263   bool IsStringPlusInt = StrExpr &&
9264       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9265   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9266     return;
9267 
9268   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9269   Self.Diag(OpLoc, diag::warn_string_plus_int)
9270       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9271 
9272   // Only print a fixit for "str" + int, not for int + "str".
9273   if (IndexExpr == RHSExpr) {
9274     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9275     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9276         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9277         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9278         << FixItHint::CreateInsertion(EndLoc, "]");
9279   } else
9280     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9281 }
9282 
9283 /// Emit a warning when adding a char literal to a string.
9284 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9285                                    Expr *LHSExpr, Expr *RHSExpr) {
9286   const Expr *StringRefExpr = LHSExpr;
9287   const CharacterLiteral *CharExpr =
9288       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9289 
9290   if (!CharExpr) {
9291     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9292     StringRefExpr = RHSExpr;
9293   }
9294 
9295   if (!CharExpr || !StringRefExpr)
9296     return;
9297 
9298   const QualType StringType = StringRefExpr->getType();
9299 
9300   // Return if not a PointerType.
9301   if (!StringType->isAnyPointerType())
9302     return;
9303 
9304   // Return if not a CharacterType.
9305   if (!StringType->getPointeeType()->isAnyCharacterType())
9306     return;
9307 
9308   ASTContext &Ctx = Self.getASTContext();
9309   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9310 
9311   const QualType CharType = CharExpr->getType();
9312   if (!CharType->isAnyCharacterType() &&
9313       CharType->isIntegerType() &&
9314       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9315     Self.Diag(OpLoc, diag::warn_string_plus_char)
9316         << DiagRange << Ctx.CharTy;
9317   } else {
9318     Self.Diag(OpLoc, diag::warn_string_plus_char)
9319         << DiagRange << CharExpr->getType();
9320   }
9321 
9322   // Only print a fixit for str + char, not for char + str.
9323   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9324     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9325     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9326         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9327         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9328         << FixItHint::CreateInsertion(EndLoc, "]");
9329   } else {
9330     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9331   }
9332 }
9333 
9334 /// Emit error when two pointers are incompatible.
9335 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9336                                            Expr *LHSExpr, Expr *RHSExpr) {
9337   assert(LHSExpr->getType()->isAnyPointerType());
9338   assert(RHSExpr->getType()->isAnyPointerType());
9339   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9340     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9341     << RHSExpr->getSourceRange();
9342 }
9343 
9344 // C99 6.5.6
9345 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9346                                      SourceLocation Loc, BinaryOperatorKind Opc,
9347                                      QualType* CompLHSTy) {
9348   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9349 
9350   if (LHS.get()->getType()->isVectorType() ||
9351       RHS.get()->getType()->isVectorType()) {
9352     QualType compType = CheckVectorOperands(
9353         LHS, RHS, Loc, CompLHSTy,
9354         /*AllowBothBool*/getLangOpts().AltiVec,
9355         /*AllowBoolConversions*/getLangOpts().ZVector);
9356     if (CompLHSTy) *CompLHSTy = compType;
9357     return compType;
9358   }
9359 
9360   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9361   if (LHS.isInvalid() || RHS.isInvalid())
9362     return QualType();
9363 
9364   // Diagnose "string literal" '+' int and string '+' "char literal".
9365   if (Opc == BO_Add) {
9366     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9367     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9368   }
9369 
9370   // handle the common case first (both operands are arithmetic).
9371   if (!compType.isNull() && compType->isArithmeticType()) {
9372     if (CompLHSTy) *CompLHSTy = compType;
9373     return compType;
9374   }
9375 
9376   // Type-checking.  Ultimately the pointer's going to be in PExp;
9377   // note that we bias towards the LHS being the pointer.
9378   Expr *PExp = LHS.get(), *IExp = RHS.get();
9379 
9380   bool isObjCPointer;
9381   if (PExp->getType()->isPointerType()) {
9382     isObjCPointer = false;
9383   } else if (PExp->getType()->isObjCObjectPointerType()) {
9384     isObjCPointer = true;
9385   } else {
9386     std::swap(PExp, IExp);
9387     if (PExp->getType()->isPointerType()) {
9388       isObjCPointer = false;
9389     } else if (PExp->getType()->isObjCObjectPointerType()) {
9390       isObjCPointer = true;
9391     } else {
9392       return InvalidOperands(Loc, LHS, RHS);
9393     }
9394   }
9395   assert(PExp->getType()->isAnyPointerType());
9396 
9397   if (!IExp->getType()->isIntegerType())
9398     return InvalidOperands(Loc, LHS, RHS);
9399 
9400   // Adding to a null pointer results in undefined behavior.
9401   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9402           Context, Expr::NPC_ValueDependentIsNotNull)) {
9403     // In C++ adding zero to a null pointer is defined.
9404     Expr::EvalResult KnownVal;
9405     if (!getLangOpts().CPlusPlus ||
9406         (!IExp->isValueDependent() &&
9407          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9408           KnownVal.Val.getInt() != 0))) {
9409       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9410       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9411           Context, BO_Add, PExp, IExp);
9412       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9413     }
9414   }
9415 
9416   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9417     return QualType();
9418 
9419   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9420     return QualType();
9421 
9422   // Check array bounds for pointer arithemtic
9423   CheckArrayAccess(PExp, IExp);
9424 
9425   if (CompLHSTy) {
9426     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9427     if (LHSTy.isNull()) {
9428       LHSTy = LHS.get()->getType();
9429       if (LHSTy->isPromotableIntegerType())
9430         LHSTy = Context.getPromotedIntegerType(LHSTy);
9431     }
9432     *CompLHSTy = LHSTy;
9433   }
9434 
9435   return PExp->getType();
9436 }
9437 
9438 // C99 6.5.6
9439 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9440                                         SourceLocation Loc,
9441                                         QualType* CompLHSTy) {
9442   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9443 
9444   if (LHS.get()->getType()->isVectorType() ||
9445       RHS.get()->getType()->isVectorType()) {
9446     QualType compType = CheckVectorOperands(
9447         LHS, RHS, Loc, CompLHSTy,
9448         /*AllowBothBool*/getLangOpts().AltiVec,
9449         /*AllowBoolConversions*/getLangOpts().ZVector);
9450     if (CompLHSTy) *CompLHSTy = compType;
9451     return compType;
9452   }
9453 
9454   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9455   if (LHS.isInvalid() || RHS.isInvalid())
9456     return QualType();
9457 
9458   // Enforce type constraints: C99 6.5.6p3.
9459 
9460   // Handle the common case first (both operands are arithmetic).
9461   if (!compType.isNull() && compType->isArithmeticType()) {
9462     if (CompLHSTy) *CompLHSTy = compType;
9463     return compType;
9464   }
9465 
9466   // Either ptr - int   or   ptr - ptr.
9467   if (LHS.get()->getType()->isAnyPointerType()) {
9468     QualType lpointee = LHS.get()->getType()->getPointeeType();
9469 
9470     // Diagnose bad cases where we step over interface counts.
9471     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9472         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9473       return QualType();
9474 
9475     // The result type of a pointer-int computation is the pointer type.
9476     if (RHS.get()->getType()->isIntegerType()) {
9477       // Subtracting from a null pointer should produce a warning.
9478       // The last argument to the diagnose call says this doesn't match the
9479       // GNU int-to-pointer idiom.
9480       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9481                                            Expr::NPC_ValueDependentIsNotNull)) {
9482         // In C++ adding zero to a null pointer is defined.
9483         Expr::EvalResult KnownVal;
9484         if (!getLangOpts().CPlusPlus ||
9485             (!RHS.get()->isValueDependent() &&
9486              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9487               KnownVal.Val.getInt() != 0))) {
9488           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9489         }
9490       }
9491 
9492       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9493         return QualType();
9494 
9495       // Check array bounds for pointer arithemtic
9496       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9497                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9498 
9499       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9500       return LHS.get()->getType();
9501     }
9502 
9503     // Handle pointer-pointer subtractions.
9504     if (const PointerType *RHSPTy
9505           = RHS.get()->getType()->getAs<PointerType>()) {
9506       QualType rpointee = RHSPTy->getPointeeType();
9507 
9508       if (getLangOpts().CPlusPlus) {
9509         // Pointee types must be the same: C++ [expr.add]
9510         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9511           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9512         }
9513       } else {
9514         // Pointee types must be compatible C99 6.5.6p3
9515         if (!Context.typesAreCompatible(
9516                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9517                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9518           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9519           return QualType();
9520         }
9521       }
9522 
9523       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9524                                                LHS.get(), RHS.get()))
9525         return QualType();
9526 
9527       // FIXME: Add warnings for nullptr - ptr.
9528 
9529       // The pointee type may have zero size.  As an extension, a structure or
9530       // union may have zero size or an array may have zero length.  In this
9531       // case subtraction does not make sense.
9532       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9533         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9534         if (ElementSize.isZero()) {
9535           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9536             << rpointee.getUnqualifiedType()
9537             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9538         }
9539       }
9540 
9541       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9542       return Context.getPointerDiffType();
9543     }
9544   }
9545 
9546   return InvalidOperands(Loc, LHS, RHS);
9547 }
9548 
9549 static bool isScopedEnumerationType(QualType T) {
9550   if (const EnumType *ET = T->getAs<EnumType>())
9551     return ET->getDecl()->isScoped();
9552   return false;
9553 }
9554 
9555 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9556                                    SourceLocation Loc, BinaryOperatorKind Opc,
9557                                    QualType LHSType) {
9558   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9559   // so skip remaining warnings as we don't want to modify values within Sema.
9560   if (S.getLangOpts().OpenCL)
9561     return;
9562 
9563   // Check right/shifter operand
9564   Expr::EvalResult RHSResult;
9565   if (RHS.get()->isValueDependent() ||
9566       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9567     return;
9568   llvm::APSInt Right = RHSResult.Val.getInt();
9569 
9570   if (Right.isNegative()) {
9571     S.DiagRuntimeBehavior(Loc, RHS.get(),
9572                           S.PDiag(diag::warn_shift_negative)
9573                             << RHS.get()->getSourceRange());
9574     return;
9575   }
9576   llvm::APInt LeftBits(Right.getBitWidth(),
9577                        S.Context.getTypeSize(LHS.get()->getType()));
9578   if (Right.uge(LeftBits)) {
9579     S.DiagRuntimeBehavior(Loc, RHS.get(),
9580                           S.PDiag(diag::warn_shift_gt_typewidth)
9581                             << RHS.get()->getSourceRange());
9582     return;
9583   }
9584   if (Opc != BO_Shl)
9585     return;
9586 
9587   // When left shifting an ICE which is signed, we can check for overflow which
9588   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9589   // integers have defined behavior modulo one more than the maximum value
9590   // representable in the result type, so never warn for those.
9591   Expr::EvalResult LHSResult;
9592   if (LHS.get()->isValueDependent() ||
9593       LHSType->hasUnsignedIntegerRepresentation() ||
9594       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9595     return;
9596   llvm::APSInt Left = LHSResult.Val.getInt();
9597 
9598   // If LHS does not have a signed type and non-negative value
9599   // then, the behavior is undefined. Warn about it.
9600   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9601     S.DiagRuntimeBehavior(Loc, LHS.get(),
9602                           S.PDiag(diag::warn_shift_lhs_negative)
9603                             << LHS.get()->getSourceRange());
9604     return;
9605   }
9606 
9607   llvm::APInt ResultBits =
9608       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9609   if (LeftBits.uge(ResultBits))
9610     return;
9611   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9612   Result = Result.shl(Right);
9613 
9614   // Print the bit representation of the signed integer as an unsigned
9615   // hexadecimal number.
9616   SmallString<40> HexResult;
9617   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9618 
9619   // If we are only missing a sign bit, this is less likely to result in actual
9620   // bugs -- if the result is cast back to an unsigned type, it will have the
9621   // expected value. Thus we place this behind a different warning that can be
9622   // turned off separately if needed.
9623   if (LeftBits == ResultBits - 1) {
9624     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9625         << HexResult << LHSType
9626         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9627     return;
9628   }
9629 
9630   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9631     << HexResult.str() << Result.getMinSignedBits() << LHSType
9632     << Left.getBitWidth() << LHS.get()->getSourceRange()
9633     << RHS.get()->getSourceRange();
9634 }
9635 
9636 /// Return the resulting type when a vector is shifted
9637 ///        by a scalar or vector shift amount.
9638 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9639                                  SourceLocation Loc, bool IsCompAssign) {
9640   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9641   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9642       !LHS.get()->getType()->isVectorType()) {
9643     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9644       << RHS.get()->getType() << LHS.get()->getType()
9645       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9646     return QualType();
9647   }
9648 
9649   if (!IsCompAssign) {
9650     LHS = S.UsualUnaryConversions(LHS.get());
9651     if (LHS.isInvalid()) return QualType();
9652   }
9653 
9654   RHS = S.UsualUnaryConversions(RHS.get());
9655   if (RHS.isInvalid()) return QualType();
9656 
9657   QualType LHSType = LHS.get()->getType();
9658   // Note that LHS might be a scalar because the routine calls not only in
9659   // OpenCL case.
9660   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9661   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9662 
9663   // Note that RHS might not be a vector.
9664   QualType RHSType = RHS.get()->getType();
9665   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9666   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9667 
9668   // The operands need to be integers.
9669   if (!LHSEleType->isIntegerType()) {
9670     S.Diag(Loc, diag::err_typecheck_expect_int)
9671       << LHS.get()->getType() << LHS.get()->getSourceRange();
9672     return QualType();
9673   }
9674 
9675   if (!RHSEleType->isIntegerType()) {
9676     S.Diag(Loc, diag::err_typecheck_expect_int)
9677       << RHS.get()->getType() << RHS.get()->getSourceRange();
9678     return QualType();
9679   }
9680 
9681   if (!LHSVecTy) {
9682     assert(RHSVecTy);
9683     if (IsCompAssign)
9684       return RHSType;
9685     if (LHSEleType != RHSEleType) {
9686       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9687       LHSEleType = RHSEleType;
9688     }
9689     QualType VecTy =
9690         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9691     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9692     LHSType = VecTy;
9693   } else if (RHSVecTy) {
9694     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9695     // are applied component-wise. So if RHS is a vector, then ensure
9696     // that the number of elements is the same as LHS...
9697     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9698       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9699         << LHS.get()->getType() << RHS.get()->getType()
9700         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9701       return QualType();
9702     }
9703     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9704       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9705       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9706       if (LHSBT != RHSBT &&
9707           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9708         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9709             << LHS.get()->getType() << RHS.get()->getType()
9710             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9711       }
9712     }
9713   } else {
9714     // ...else expand RHS to match the number of elements in LHS.
9715     QualType VecTy =
9716       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9717     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9718   }
9719 
9720   return LHSType;
9721 }
9722 
9723 // C99 6.5.7
9724 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9725                                   SourceLocation Loc, BinaryOperatorKind Opc,
9726                                   bool IsCompAssign) {
9727   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9728 
9729   // Vector shifts promote their scalar inputs to vector type.
9730   if (LHS.get()->getType()->isVectorType() ||
9731       RHS.get()->getType()->isVectorType()) {
9732     if (LangOpts.ZVector) {
9733       // The shift operators for the z vector extensions work basically
9734       // like general shifts, except that neither the LHS nor the RHS is
9735       // allowed to be a "vector bool".
9736       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9737         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9738           return InvalidOperands(Loc, LHS, RHS);
9739       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9740         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9741           return InvalidOperands(Loc, LHS, RHS);
9742     }
9743     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9744   }
9745 
9746   // Shifts don't perform usual arithmetic conversions, they just do integer
9747   // promotions on each operand. C99 6.5.7p3
9748 
9749   // For the LHS, do usual unary conversions, but then reset them away
9750   // if this is a compound assignment.
9751   ExprResult OldLHS = LHS;
9752   LHS = UsualUnaryConversions(LHS.get());
9753   if (LHS.isInvalid())
9754     return QualType();
9755   QualType LHSType = LHS.get()->getType();
9756   if (IsCompAssign) LHS = OldLHS;
9757 
9758   // The RHS is simpler.
9759   RHS = UsualUnaryConversions(RHS.get());
9760   if (RHS.isInvalid())
9761     return QualType();
9762   QualType RHSType = RHS.get()->getType();
9763 
9764   // C99 6.5.7p2: Each of the operands shall have integer type.
9765   if (!LHSType->hasIntegerRepresentation() ||
9766       !RHSType->hasIntegerRepresentation())
9767     return InvalidOperands(Loc, LHS, RHS);
9768 
9769   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9770   // hasIntegerRepresentation() above instead of this.
9771   if (isScopedEnumerationType(LHSType) ||
9772       isScopedEnumerationType(RHSType)) {
9773     return InvalidOperands(Loc, LHS, RHS);
9774   }
9775   // Sanity-check shift operands
9776   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9777 
9778   // "The type of the result is that of the promoted left operand."
9779   return LHSType;
9780 }
9781 
9782 /// If two different enums are compared, raise a warning.
9783 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9784                                 Expr *RHS) {
9785   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9786   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9787 
9788   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9789   if (!LHSEnumType)
9790     return;
9791   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9792   if (!RHSEnumType)
9793     return;
9794 
9795   // Ignore anonymous enums.
9796   if (!LHSEnumType->getDecl()->getIdentifier() &&
9797       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9798     return;
9799   if (!RHSEnumType->getDecl()->getIdentifier() &&
9800       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9801     return;
9802 
9803   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9804     return;
9805 
9806   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9807       << LHSStrippedType << RHSStrippedType
9808       << LHS->getSourceRange() << RHS->getSourceRange();
9809 }
9810 
9811 /// Diagnose bad pointer comparisons.
9812 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9813                                               ExprResult &LHS, ExprResult &RHS,
9814                                               bool IsError) {
9815   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9816                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9817     << LHS.get()->getType() << RHS.get()->getType()
9818     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9819 }
9820 
9821 /// Returns false if the pointers are converted to a composite type,
9822 /// true otherwise.
9823 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9824                                            ExprResult &LHS, ExprResult &RHS) {
9825   // C++ [expr.rel]p2:
9826   //   [...] Pointer conversions (4.10) and qualification
9827   //   conversions (4.4) are performed on pointer operands (or on
9828   //   a pointer operand and a null pointer constant) to bring
9829   //   them to their composite pointer type. [...]
9830   //
9831   // C++ [expr.eq]p1 uses the same notion for (in)equality
9832   // comparisons of pointers.
9833 
9834   QualType LHSType = LHS.get()->getType();
9835   QualType RHSType = RHS.get()->getType();
9836   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9837          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9838 
9839   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9840   if (T.isNull()) {
9841     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9842         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9843       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9844     else
9845       S.InvalidOperands(Loc, LHS, RHS);
9846     return true;
9847   }
9848 
9849   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9850   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9851   return false;
9852 }
9853 
9854 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9855                                                     ExprResult &LHS,
9856                                                     ExprResult &RHS,
9857                                                     bool IsError) {
9858   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9859                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9860     << LHS.get()->getType() << RHS.get()->getType()
9861     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9862 }
9863 
9864 static bool isObjCObjectLiteral(ExprResult &E) {
9865   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9866   case Stmt::ObjCArrayLiteralClass:
9867   case Stmt::ObjCDictionaryLiteralClass:
9868   case Stmt::ObjCStringLiteralClass:
9869   case Stmt::ObjCBoxedExprClass:
9870     return true;
9871   default:
9872     // Note that ObjCBoolLiteral is NOT an object literal!
9873     return false;
9874   }
9875 }
9876 
9877 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9878   const ObjCObjectPointerType *Type =
9879     LHS->getType()->getAs<ObjCObjectPointerType>();
9880 
9881   // If this is not actually an Objective-C object, bail out.
9882   if (!Type)
9883     return false;
9884 
9885   // Get the LHS object's interface type.
9886   QualType InterfaceType = Type->getPointeeType();
9887 
9888   // If the RHS isn't an Objective-C object, bail out.
9889   if (!RHS->getType()->isObjCObjectPointerType())
9890     return false;
9891 
9892   // Try to find the -isEqual: method.
9893   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9894   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9895                                                       InterfaceType,
9896                                                       /*instance=*/true);
9897   if (!Method) {
9898     if (Type->isObjCIdType()) {
9899       // For 'id', just check the global pool.
9900       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9901                                                   /*receiverId=*/true);
9902     } else {
9903       // Check protocols.
9904       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9905                                              /*instance=*/true);
9906     }
9907   }
9908 
9909   if (!Method)
9910     return false;
9911 
9912   QualType T = Method->parameters()[0]->getType();
9913   if (!T->isObjCObjectPointerType())
9914     return false;
9915 
9916   QualType R = Method->getReturnType();
9917   if (!R->isScalarType())
9918     return false;
9919 
9920   return true;
9921 }
9922 
9923 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9924   FromE = FromE->IgnoreParenImpCasts();
9925   switch (FromE->getStmtClass()) {
9926     default:
9927       break;
9928     case Stmt::ObjCStringLiteralClass:
9929       // "string literal"
9930       return LK_String;
9931     case Stmt::ObjCArrayLiteralClass:
9932       // "array literal"
9933       return LK_Array;
9934     case Stmt::ObjCDictionaryLiteralClass:
9935       // "dictionary literal"
9936       return LK_Dictionary;
9937     case Stmt::BlockExprClass:
9938       return LK_Block;
9939     case Stmt::ObjCBoxedExprClass: {
9940       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9941       switch (Inner->getStmtClass()) {
9942         case Stmt::IntegerLiteralClass:
9943         case Stmt::FloatingLiteralClass:
9944         case Stmt::CharacterLiteralClass:
9945         case Stmt::ObjCBoolLiteralExprClass:
9946         case Stmt::CXXBoolLiteralExprClass:
9947           // "numeric literal"
9948           return LK_Numeric;
9949         case Stmt::ImplicitCastExprClass: {
9950           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9951           // Boolean literals can be represented by implicit casts.
9952           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9953             return LK_Numeric;
9954           break;
9955         }
9956         default:
9957           break;
9958       }
9959       return LK_Boxed;
9960     }
9961   }
9962   return LK_None;
9963 }
9964 
9965 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9966                                           ExprResult &LHS, ExprResult &RHS,
9967                                           BinaryOperator::Opcode Opc){
9968   Expr *Literal;
9969   Expr *Other;
9970   if (isObjCObjectLiteral(LHS)) {
9971     Literal = LHS.get();
9972     Other = RHS.get();
9973   } else {
9974     Literal = RHS.get();
9975     Other = LHS.get();
9976   }
9977 
9978   // Don't warn on comparisons against nil.
9979   Other = Other->IgnoreParenCasts();
9980   if (Other->isNullPointerConstant(S.getASTContext(),
9981                                    Expr::NPC_ValueDependentIsNotNull))
9982     return;
9983 
9984   // This should be kept in sync with warn_objc_literal_comparison.
9985   // LK_String should always be after the other literals, since it has its own
9986   // warning flag.
9987   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9988   assert(LiteralKind != Sema::LK_Block);
9989   if (LiteralKind == Sema::LK_None) {
9990     llvm_unreachable("Unknown Objective-C object literal kind");
9991   }
9992 
9993   if (LiteralKind == Sema::LK_String)
9994     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9995       << Literal->getSourceRange();
9996   else
9997     S.Diag(Loc, diag::warn_objc_literal_comparison)
9998       << LiteralKind << Literal->getSourceRange();
9999 
10000   if (BinaryOperator::isEqualityOp(Opc) &&
10001       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10002     SourceLocation Start = LHS.get()->getBeginLoc();
10003     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10004     CharSourceRange OpRange =
10005       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10006 
10007     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10008       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10009       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10010       << FixItHint::CreateInsertion(End, "]");
10011   }
10012 }
10013 
10014 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10015 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10016                                            ExprResult &RHS, SourceLocation Loc,
10017                                            BinaryOperatorKind Opc) {
10018   // Check that left hand side is !something.
10019   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10020   if (!UO || UO->getOpcode() != UO_LNot) return;
10021 
10022   // Only check if the right hand side is non-bool arithmetic type.
10023   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10024 
10025   // Make sure that the something in !something is not bool.
10026   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10027   if (SubExpr->isKnownToHaveBooleanValue()) return;
10028 
10029   // Emit warning.
10030   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10031   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10032       << Loc << IsBitwiseOp;
10033 
10034   // First note suggest !(x < y)
10035   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10036   SourceLocation FirstClose = RHS.get()->getEndLoc();
10037   FirstClose = S.getLocForEndOfToken(FirstClose);
10038   if (FirstClose.isInvalid())
10039     FirstOpen = SourceLocation();
10040   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10041       << IsBitwiseOp
10042       << FixItHint::CreateInsertion(FirstOpen, "(")
10043       << FixItHint::CreateInsertion(FirstClose, ")");
10044 
10045   // Second note suggests (!x) < y
10046   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10047   SourceLocation SecondClose = LHS.get()->getEndLoc();
10048   SecondClose = S.getLocForEndOfToken(SecondClose);
10049   if (SecondClose.isInvalid())
10050     SecondOpen = SourceLocation();
10051   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10052       << FixItHint::CreateInsertion(SecondOpen, "(")
10053       << FixItHint::CreateInsertion(SecondClose, ")");
10054 }
10055 
10056 // Get the decl for a simple expression: a reference to a variable,
10057 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10058 static ValueDecl *getCompareDecl(Expr *E) {
10059   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10060     return DR->getDecl();
10061   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10062     if (Ivar->isFreeIvar())
10063       return Ivar->getDecl();
10064   }
10065   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10066     if (Mem->isImplicitAccess())
10067       return Mem->getMemberDecl();
10068   }
10069   return nullptr;
10070 }
10071 
10072 /// Diagnose some forms of syntactically-obvious tautological comparison.
10073 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10074                                            Expr *LHS, Expr *RHS,
10075                                            BinaryOperatorKind Opc) {
10076   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10077   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10078 
10079   QualType LHSType = LHS->getType();
10080   QualType RHSType = RHS->getType();
10081   if (LHSType->hasFloatingRepresentation() ||
10082       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10083       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10084       S.inTemplateInstantiation())
10085     return;
10086 
10087   // Comparisons between two array types are ill-formed for operator<=>, so
10088   // we shouldn't emit any additional warnings about it.
10089   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10090     return;
10091 
10092   // For non-floating point types, check for self-comparisons of the form
10093   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10094   // often indicate logic errors in the program.
10095   //
10096   // NOTE: Don't warn about comparison expressions resulting from macro
10097   // expansion. Also don't warn about comparisons which are only self
10098   // comparisons within a template instantiation. The warnings should catch
10099   // obvious cases in the definition of the template anyways. The idea is to
10100   // warn when the typed comparison operator will always evaluate to the same
10101   // result.
10102   ValueDecl *DL = getCompareDecl(LHSStripped);
10103   ValueDecl *DR = getCompareDecl(RHSStripped);
10104   if (DL && DR && declaresSameEntity(DL, DR)) {
10105     StringRef Result;
10106     switch (Opc) {
10107     case BO_EQ: case BO_LE: case BO_GE:
10108       Result = "true";
10109       break;
10110     case BO_NE: case BO_LT: case BO_GT:
10111       Result = "false";
10112       break;
10113     case BO_Cmp:
10114       Result = "'std::strong_ordering::equal'";
10115       break;
10116     default:
10117       break;
10118     }
10119     S.DiagRuntimeBehavior(Loc, nullptr,
10120                           S.PDiag(diag::warn_comparison_always)
10121                               << 0 /*self-comparison*/ << !Result.empty()
10122                               << Result);
10123   } else if (DL && DR &&
10124              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10125              !DL->isWeak() && !DR->isWeak()) {
10126     // What is it always going to evaluate to?
10127     StringRef Result;
10128     switch(Opc) {
10129     case BO_EQ: // e.g. array1 == array2
10130       Result = "false";
10131       break;
10132     case BO_NE: // e.g. array1 != array2
10133       Result = "true";
10134       break;
10135     default: // e.g. array1 <= array2
10136       // The best we can say is 'a constant'
10137       break;
10138     }
10139     S.DiagRuntimeBehavior(Loc, nullptr,
10140                           S.PDiag(diag::warn_comparison_always)
10141                               << 1 /*array comparison*/
10142                               << !Result.empty() << Result);
10143   }
10144 
10145   if (isa<CastExpr>(LHSStripped))
10146     LHSStripped = LHSStripped->IgnoreParenCasts();
10147   if (isa<CastExpr>(RHSStripped))
10148     RHSStripped = RHSStripped->IgnoreParenCasts();
10149 
10150   // Warn about comparisons against a string constant (unless the other
10151   // operand is null); the user probably wants strcmp.
10152   Expr *LiteralString = nullptr;
10153   Expr *LiteralStringStripped = nullptr;
10154   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10155       !RHSStripped->isNullPointerConstant(S.Context,
10156                                           Expr::NPC_ValueDependentIsNull)) {
10157     LiteralString = LHS;
10158     LiteralStringStripped = LHSStripped;
10159   } else if ((isa<StringLiteral>(RHSStripped) ||
10160               isa<ObjCEncodeExpr>(RHSStripped)) &&
10161              !LHSStripped->isNullPointerConstant(S.Context,
10162                                           Expr::NPC_ValueDependentIsNull)) {
10163     LiteralString = RHS;
10164     LiteralStringStripped = RHSStripped;
10165   }
10166 
10167   if (LiteralString) {
10168     S.DiagRuntimeBehavior(Loc, nullptr,
10169                           S.PDiag(diag::warn_stringcompare)
10170                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10171                               << LiteralString->getSourceRange());
10172   }
10173 }
10174 
10175 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10176   switch (CK) {
10177   default: {
10178 #ifndef NDEBUG
10179     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10180                  << "\n";
10181 #endif
10182     llvm_unreachable("unhandled cast kind");
10183   }
10184   case CK_UserDefinedConversion:
10185     return ICK_Identity;
10186   case CK_LValueToRValue:
10187     return ICK_Lvalue_To_Rvalue;
10188   case CK_ArrayToPointerDecay:
10189     return ICK_Array_To_Pointer;
10190   case CK_FunctionToPointerDecay:
10191     return ICK_Function_To_Pointer;
10192   case CK_IntegralCast:
10193     return ICK_Integral_Conversion;
10194   case CK_FloatingCast:
10195     return ICK_Floating_Conversion;
10196   case CK_IntegralToFloating:
10197   case CK_FloatingToIntegral:
10198     return ICK_Floating_Integral;
10199   case CK_IntegralComplexCast:
10200   case CK_FloatingComplexCast:
10201   case CK_FloatingComplexToIntegralComplex:
10202   case CK_IntegralComplexToFloatingComplex:
10203     return ICK_Complex_Conversion;
10204   case CK_FloatingComplexToReal:
10205   case CK_FloatingRealToComplex:
10206   case CK_IntegralComplexToReal:
10207   case CK_IntegralRealToComplex:
10208     return ICK_Complex_Real;
10209   }
10210 }
10211 
10212 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10213                                              QualType FromType,
10214                                              SourceLocation Loc) {
10215   // Check for a narrowing implicit conversion.
10216   StandardConversionSequence SCS;
10217   SCS.setAsIdentityConversion();
10218   SCS.setToType(0, FromType);
10219   SCS.setToType(1, ToType);
10220   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10221     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10222 
10223   APValue PreNarrowingValue;
10224   QualType PreNarrowingType;
10225   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10226                                PreNarrowingType,
10227                                /*IgnoreFloatToIntegralConversion*/ true)) {
10228   case NK_Dependent_Narrowing:
10229     // Implicit conversion to a narrower type, but the expression is
10230     // value-dependent so we can't tell whether it's actually narrowing.
10231   case NK_Not_Narrowing:
10232     return false;
10233 
10234   case NK_Constant_Narrowing:
10235     // Implicit conversion to a narrower type, and the value is not a constant
10236     // expression.
10237     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10238         << /*Constant*/ 1
10239         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10240     return true;
10241 
10242   case NK_Variable_Narrowing:
10243     // Implicit conversion to a narrower type, and the value is not a constant
10244     // expression.
10245   case NK_Type_Narrowing:
10246     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10247         << /*Constant*/ 0 << FromType << ToType;
10248     // TODO: It's not a constant expression, but what if the user intended it
10249     // to be? Can we produce notes to help them figure out why it isn't?
10250     return true;
10251   }
10252   llvm_unreachable("unhandled case in switch");
10253 }
10254 
10255 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10256                                                          ExprResult &LHS,
10257                                                          ExprResult &RHS,
10258                                                          SourceLocation Loc) {
10259   using CCT = ComparisonCategoryType;
10260 
10261   QualType LHSType = LHS.get()->getType();
10262   QualType RHSType = RHS.get()->getType();
10263   // Dig out the original argument type and expression before implicit casts
10264   // were applied. These are the types/expressions we need to check the
10265   // [expr.spaceship] requirements against.
10266   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10267   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10268   QualType LHSStrippedType = LHSStripped.get()->getType();
10269   QualType RHSStrippedType = RHSStripped.get()->getType();
10270 
10271   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10272   // other is not, the program is ill-formed.
10273   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10274     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10275     return QualType();
10276   }
10277 
10278   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10279                     RHSStrippedType->isEnumeralType();
10280   if (NumEnumArgs == 1) {
10281     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10282     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10283     if (OtherTy->hasFloatingRepresentation()) {
10284       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10285       return QualType();
10286     }
10287   }
10288   if (NumEnumArgs == 2) {
10289     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10290     // type E, the operator yields the result of converting the operands
10291     // to the underlying type of E and applying <=> to the converted operands.
10292     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10293       S.InvalidOperands(Loc, LHS, RHS);
10294       return QualType();
10295     }
10296     QualType IntType =
10297         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10298     assert(IntType->isArithmeticType());
10299 
10300     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10301     // promote the boolean type, and all other promotable integer types, to
10302     // avoid this.
10303     if (IntType->isPromotableIntegerType())
10304       IntType = S.Context.getPromotedIntegerType(IntType);
10305 
10306     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10307     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10308     LHSType = RHSType = IntType;
10309   }
10310 
10311   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10312   // usual arithmetic conversions are applied to the operands.
10313   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10314   if (LHS.isInvalid() || RHS.isInvalid())
10315     return QualType();
10316   if (Type.isNull())
10317     return S.InvalidOperands(Loc, LHS, RHS);
10318   assert(Type->isArithmeticType() || Type->isEnumeralType());
10319 
10320   bool HasNarrowing = checkThreeWayNarrowingConversion(
10321       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10322   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10323                                                    RHS.get()->getBeginLoc());
10324   if (HasNarrowing)
10325     return QualType();
10326 
10327   assert(!Type.isNull() && "composite type for <=> has not been set");
10328 
10329   auto TypeKind = [&]() {
10330     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10331       if (CT->getElementType()->hasFloatingRepresentation())
10332         return CCT::WeakEquality;
10333       return CCT::StrongEquality;
10334     }
10335     if (Type->isIntegralOrEnumerationType())
10336       return CCT::StrongOrdering;
10337     if (Type->hasFloatingRepresentation())
10338       return CCT::PartialOrdering;
10339     llvm_unreachable("other types are unimplemented");
10340   }();
10341 
10342   return S.CheckComparisonCategoryType(TypeKind, Loc);
10343 }
10344 
10345 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10346                                                  ExprResult &RHS,
10347                                                  SourceLocation Loc,
10348                                                  BinaryOperatorKind Opc) {
10349   if (Opc == BO_Cmp)
10350     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10351 
10352   // C99 6.5.8p3 / C99 6.5.9p4
10353   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10354   if (LHS.isInvalid() || RHS.isInvalid())
10355     return QualType();
10356   if (Type.isNull())
10357     return S.InvalidOperands(Loc, LHS, RHS);
10358   assert(Type->isArithmeticType() || Type->isEnumeralType());
10359 
10360   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10361 
10362   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10363     return S.InvalidOperands(Loc, LHS, RHS);
10364 
10365   // Check for comparisons of floating point operands using != and ==.
10366   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10367     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10368 
10369   // The result of comparisons is 'bool' in C++, 'int' in C.
10370   return S.Context.getLogicalOperationType();
10371 }
10372 
10373 // C99 6.5.8, C++ [expr.rel]
10374 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10375                                     SourceLocation Loc,
10376                                     BinaryOperatorKind Opc) {
10377   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10378   bool IsThreeWay = Opc == BO_Cmp;
10379   auto IsAnyPointerType = [](ExprResult E) {
10380     QualType Ty = E.get()->getType();
10381     return Ty->isPointerType() || Ty->isMemberPointerType();
10382   };
10383 
10384   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10385   // type, array-to-pointer, ..., conversions are performed on both operands to
10386   // bring them to their composite type.
10387   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10388   // any type-related checks.
10389   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10390     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10391     if (LHS.isInvalid())
10392       return QualType();
10393     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10394     if (RHS.isInvalid())
10395       return QualType();
10396   } else {
10397     LHS = DefaultLvalueConversion(LHS.get());
10398     if (LHS.isInvalid())
10399       return QualType();
10400     RHS = DefaultLvalueConversion(RHS.get());
10401     if (RHS.isInvalid())
10402       return QualType();
10403   }
10404 
10405   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10406 
10407   // Handle vector comparisons separately.
10408   if (LHS.get()->getType()->isVectorType() ||
10409       RHS.get()->getType()->isVectorType())
10410     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10411 
10412   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10413   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10414 
10415   QualType LHSType = LHS.get()->getType();
10416   QualType RHSType = RHS.get()->getType();
10417   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10418       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10419     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10420 
10421   const Expr::NullPointerConstantKind LHSNullKind =
10422       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10423   const Expr::NullPointerConstantKind RHSNullKind =
10424       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10425   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10426   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10427 
10428   auto computeResultTy = [&]() {
10429     if (Opc != BO_Cmp)
10430       return Context.getLogicalOperationType();
10431     assert(getLangOpts().CPlusPlus);
10432     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10433 
10434     QualType CompositeTy = LHS.get()->getType();
10435     assert(!CompositeTy->isReferenceType());
10436 
10437     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10438       return CheckComparisonCategoryType(Kind, Loc);
10439     };
10440 
10441     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10442     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10443     // result is of type std::strong_equality
10444     if (CompositeTy->isFunctionPointerType() ||
10445         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10446       // FIXME: consider making the function pointer case produce
10447       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10448       // and direction polls
10449       return buildResultTy(ComparisonCategoryType::StrongEquality);
10450 
10451     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10452     // pointer type, p <=> q is of type std::strong_ordering.
10453     if (CompositeTy->isPointerType()) {
10454       // P0946R0: Comparisons between a null pointer constant and an object
10455       // pointer result in std::strong_equality
10456       if (LHSIsNull != RHSIsNull)
10457         return buildResultTy(ComparisonCategoryType::StrongEquality);
10458       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10459     }
10460     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10461     // TODO: Extend support for operator<=> to ObjC types.
10462     return InvalidOperands(Loc, LHS, RHS);
10463   };
10464 
10465 
10466   if (!IsRelational && LHSIsNull != RHSIsNull) {
10467     bool IsEquality = Opc == BO_EQ;
10468     if (RHSIsNull)
10469       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10470                                    RHS.get()->getSourceRange());
10471     else
10472       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10473                                    LHS.get()->getSourceRange());
10474   }
10475 
10476   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10477       (RHSType->isIntegerType() && !RHSIsNull)) {
10478     // Skip normal pointer conversion checks in this case; we have better
10479     // diagnostics for this below.
10480   } else if (getLangOpts().CPlusPlus) {
10481     // Equality comparison of a function pointer to a void pointer is invalid,
10482     // but we allow it as an extension.
10483     // FIXME: If we really want to allow this, should it be part of composite
10484     // pointer type computation so it works in conditionals too?
10485     if (!IsRelational &&
10486         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10487          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10488       // This is a gcc extension compatibility comparison.
10489       // In a SFINAE context, we treat this as a hard error to maintain
10490       // conformance with the C++ standard.
10491       diagnoseFunctionPointerToVoidComparison(
10492           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10493 
10494       if (isSFINAEContext())
10495         return QualType();
10496 
10497       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10498       return computeResultTy();
10499     }
10500 
10501     // C++ [expr.eq]p2:
10502     //   If at least one operand is a pointer [...] bring them to their
10503     //   composite pointer type.
10504     // C++ [expr.spaceship]p6
10505     //  If at least one of the operands is of pointer type, [...] bring them
10506     //  to their composite pointer type.
10507     // C++ [expr.rel]p2:
10508     //   If both operands are pointers, [...] bring them to their composite
10509     //   pointer type.
10510     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10511             (IsRelational ? 2 : 1) &&
10512         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10513                                          RHSType->isObjCObjectPointerType()))) {
10514       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10515         return QualType();
10516       return computeResultTy();
10517     }
10518   } else if (LHSType->isPointerType() &&
10519              RHSType->isPointerType()) { // C99 6.5.8p2
10520     // All of the following pointer-related warnings are GCC extensions, except
10521     // when handling null pointer constants.
10522     QualType LCanPointeeTy =
10523       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10524     QualType RCanPointeeTy =
10525       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10526 
10527     // C99 6.5.9p2 and C99 6.5.8p2
10528     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10529                                    RCanPointeeTy.getUnqualifiedType())) {
10530       // Valid unless a relational comparison of function pointers
10531       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10532         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10533           << LHSType << RHSType << LHS.get()->getSourceRange()
10534           << RHS.get()->getSourceRange();
10535       }
10536     } else if (!IsRelational &&
10537                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10538       // Valid unless comparison between non-null pointer and function pointer
10539       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10540           && !LHSIsNull && !RHSIsNull)
10541         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10542                                                 /*isError*/false);
10543     } else {
10544       // Invalid
10545       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10546     }
10547     if (LCanPointeeTy != RCanPointeeTy) {
10548       // Treat NULL constant as a special case in OpenCL.
10549       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10550         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10551         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10552           Diag(Loc,
10553                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10554               << LHSType << RHSType << 0 /* comparison */
10555               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10556         }
10557       }
10558       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10559       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10560       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10561                                                : CK_BitCast;
10562       if (LHSIsNull && !RHSIsNull)
10563         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10564       else
10565         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10566     }
10567     return computeResultTy();
10568   }
10569 
10570   if (getLangOpts().CPlusPlus) {
10571     // C++ [expr.eq]p4:
10572     //   Two operands of type std::nullptr_t or one operand of type
10573     //   std::nullptr_t and the other a null pointer constant compare equal.
10574     if (!IsRelational && LHSIsNull && RHSIsNull) {
10575       if (LHSType->isNullPtrType()) {
10576         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10577         return computeResultTy();
10578       }
10579       if (RHSType->isNullPtrType()) {
10580         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10581         return computeResultTy();
10582       }
10583     }
10584 
10585     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10586     // These aren't covered by the composite pointer type rules.
10587     if (!IsRelational && RHSType->isNullPtrType() &&
10588         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10589       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10590       return computeResultTy();
10591     }
10592     if (!IsRelational && LHSType->isNullPtrType() &&
10593         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10594       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10595       return computeResultTy();
10596     }
10597 
10598     if (IsRelational &&
10599         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10600          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10601       // HACK: Relational comparison of nullptr_t against a pointer type is
10602       // invalid per DR583, but we allow it within std::less<> and friends,
10603       // since otherwise common uses of it break.
10604       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10605       // friends to have std::nullptr_t overload candidates.
10606       DeclContext *DC = CurContext;
10607       if (isa<FunctionDecl>(DC))
10608         DC = DC->getParent();
10609       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10610         if (CTSD->isInStdNamespace() &&
10611             llvm::StringSwitch<bool>(CTSD->getName())
10612                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10613                 .Default(false)) {
10614           if (RHSType->isNullPtrType())
10615             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10616           else
10617             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10618           return computeResultTy();
10619         }
10620       }
10621     }
10622 
10623     // C++ [expr.eq]p2:
10624     //   If at least one operand is a pointer to member, [...] bring them to
10625     //   their composite pointer type.
10626     if (!IsRelational &&
10627         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10628       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10629         return QualType();
10630       else
10631         return computeResultTy();
10632     }
10633   }
10634 
10635   // Handle block pointer types.
10636   if (!IsRelational && LHSType->isBlockPointerType() &&
10637       RHSType->isBlockPointerType()) {
10638     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10639     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10640 
10641     if (!LHSIsNull && !RHSIsNull &&
10642         !Context.typesAreCompatible(lpointee, rpointee)) {
10643       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10644         << LHSType << RHSType << LHS.get()->getSourceRange()
10645         << RHS.get()->getSourceRange();
10646     }
10647     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10648     return computeResultTy();
10649   }
10650 
10651   // Allow block pointers to be compared with null pointer constants.
10652   if (!IsRelational
10653       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10654           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10655     if (!LHSIsNull && !RHSIsNull) {
10656       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10657              ->getPointeeType()->isVoidType())
10658             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10659                 ->getPointeeType()->isVoidType())))
10660         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10661           << LHSType << RHSType << LHS.get()->getSourceRange()
10662           << RHS.get()->getSourceRange();
10663     }
10664     if (LHSIsNull && !RHSIsNull)
10665       LHS = ImpCastExprToType(LHS.get(), RHSType,
10666                               RHSType->isPointerType() ? CK_BitCast
10667                                 : CK_AnyPointerToBlockPointerCast);
10668     else
10669       RHS = ImpCastExprToType(RHS.get(), LHSType,
10670                               LHSType->isPointerType() ? CK_BitCast
10671                                 : CK_AnyPointerToBlockPointerCast);
10672     return computeResultTy();
10673   }
10674 
10675   if (LHSType->isObjCObjectPointerType() ||
10676       RHSType->isObjCObjectPointerType()) {
10677     const PointerType *LPT = LHSType->getAs<PointerType>();
10678     const PointerType *RPT = RHSType->getAs<PointerType>();
10679     if (LPT || RPT) {
10680       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10681       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10682 
10683       if (!LPtrToVoid && !RPtrToVoid &&
10684           !Context.typesAreCompatible(LHSType, RHSType)) {
10685         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10686                                           /*isError*/false);
10687       }
10688       if (LHSIsNull && !RHSIsNull) {
10689         Expr *E = LHS.get();
10690         if (getLangOpts().ObjCAutoRefCount)
10691           CheckObjCConversion(SourceRange(), RHSType, E,
10692                               CCK_ImplicitConversion);
10693         LHS = ImpCastExprToType(E, RHSType,
10694                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10695       }
10696       else {
10697         Expr *E = RHS.get();
10698         if (getLangOpts().ObjCAutoRefCount)
10699           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10700                               /*Diagnose=*/true,
10701                               /*DiagnoseCFAudited=*/false, Opc);
10702         RHS = ImpCastExprToType(E, LHSType,
10703                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10704       }
10705       return computeResultTy();
10706     }
10707     if (LHSType->isObjCObjectPointerType() &&
10708         RHSType->isObjCObjectPointerType()) {
10709       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10710         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10711                                           /*isError*/false);
10712       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10713         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10714 
10715       if (LHSIsNull && !RHSIsNull)
10716         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10717       else
10718         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10719       return computeResultTy();
10720     }
10721 
10722     if (!IsRelational && LHSType->isBlockPointerType() &&
10723         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10724       LHS = ImpCastExprToType(LHS.get(), RHSType,
10725                               CK_BlockPointerToObjCPointerCast);
10726       return computeResultTy();
10727     } else if (!IsRelational &&
10728                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10729                RHSType->isBlockPointerType()) {
10730       RHS = ImpCastExprToType(RHS.get(), LHSType,
10731                               CK_BlockPointerToObjCPointerCast);
10732       return computeResultTy();
10733     }
10734   }
10735   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10736       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10737     unsigned DiagID = 0;
10738     bool isError = false;
10739     if (LangOpts.DebuggerSupport) {
10740       // Under a debugger, allow the comparison of pointers to integers,
10741       // since users tend to want to compare addresses.
10742     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10743                (RHSIsNull && RHSType->isIntegerType())) {
10744       if (IsRelational) {
10745         isError = getLangOpts().CPlusPlus;
10746         DiagID =
10747           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10748                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10749       }
10750     } else if (getLangOpts().CPlusPlus) {
10751       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10752       isError = true;
10753     } else if (IsRelational)
10754       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10755     else
10756       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10757 
10758     if (DiagID) {
10759       Diag(Loc, DiagID)
10760         << LHSType << RHSType << LHS.get()->getSourceRange()
10761         << RHS.get()->getSourceRange();
10762       if (isError)
10763         return QualType();
10764     }
10765 
10766     if (LHSType->isIntegerType())
10767       LHS = ImpCastExprToType(LHS.get(), RHSType,
10768                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10769     else
10770       RHS = ImpCastExprToType(RHS.get(), LHSType,
10771                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10772     return computeResultTy();
10773   }
10774 
10775   // Handle block pointers.
10776   if (!IsRelational && RHSIsNull
10777       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10778     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10779     return computeResultTy();
10780   }
10781   if (!IsRelational && LHSIsNull
10782       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10783     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10784     return computeResultTy();
10785   }
10786 
10787   if (getLangOpts().OpenCLVersion >= 200) {
10788     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10789       return computeResultTy();
10790     }
10791 
10792     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10793       return computeResultTy();
10794     }
10795 
10796     if (LHSIsNull && RHSType->isQueueT()) {
10797       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10798       return computeResultTy();
10799     }
10800 
10801     if (LHSType->isQueueT() && RHSIsNull) {
10802       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10803       return computeResultTy();
10804     }
10805   }
10806 
10807   return InvalidOperands(Loc, LHS, RHS);
10808 }
10809 
10810 // Return a signed ext_vector_type that is of identical size and number of
10811 // elements. For floating point vectors, return an integer type of identical
10812 // size and number of elements. In the non ext_vector_type case, search from
10813 // the largest type to the smallest type to avoid cases where long long == long,
10814 // where long gets picked over long long.
10815 QualType Sema::GetSignedVectorType(QualType V) {
10816   const VectorType *VTy = V->getAs<VectorType>();
10817   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10818 
10819   if (isa<ExtVectorType>(VTy)) {
10820     if (TypeSize == Context.getTypeSize(Context.CharTy))
10821       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10822     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10823       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10824     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10825       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10826     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10827       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10828     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10829            "Unhandled vector element size in vector compare");
10830     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10831   }
10832 
10833   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10834     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10835                                  VectorType::GenericVector);
10836   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10837     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10838                                  VectorType::GenericVector);
10839   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10840     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10841                                  VectorType::GenericVector);
10842   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10843     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10844                                  VectorType::GenericVector);
10845   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10846          "Unhandled vector element size in vector compare");
10847   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10848                                VectorType::GenericVector);
10849 }
10850 
10851 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10852 /// operates on extended vector types.  Instead of producing an IntTy result,
10853 /// like a scalar comparison, a vector comparison produces a vector of integer
10854 /// types.
10855 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10856                                           SourceLocation Loc,
10857                                           BinaryOperatorKind Opc) {
10858   // Check to make sure we're operating on vectors of the same type and width,
10859   // Allowing one side to be a scalar of element type.
10860   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10861                               /*AllowBothBool*/true,
10862                               /*AllowBoolConversions*/getLangOpts().ZVector);
10863   if (vType.isNull())
10864     return vType;
10865 
10866   QualType LHSType = LHS.get()->getType();
10867 
10868   // If AltiVec, the comparison results in a numeric type, i.e.
10869   // bool for C++, int for C
10870   if (getLangOpts().AltiVec &&
10871       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10872     return Context.getLogicalOperationType();
10873 
10874   // For non-floating point types, check for self-comparisons of the form
10875   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10876   // often indicate logic errors in the program.
10877   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10878 
10879   // Check for comparisons of floating point operands using != and ==.
10880   if (BinaryOperator::isEqualityOp(Opc) &&
10881       LHSType->hasFloatingRepresentation()) {
10882     assert(RHS.get()->getType()->hasFloatingRepresentation());
10883     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10884   }
10885 
10886   // Return a signed type for the vector.
10887   return GetSignedVectorType(vType);
10888 }
10889 
10890 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10891                                           SourceLocation Loc) {
10892   // Ensure that either both operands are of the same vector type, or
10893   // one operand is of a vector type and the other is of its element type.
10894   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10895                                        /*AllowBothBool*/true,
10896                                        /*AllowBoolConversions*/false);
10897   if (vType.isNull())
10898     return InvalidOperands(Loc, LHS, RHS);
10899   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10900       vType->hasFloatingRepresentation())
10901     return InvalidOperands(Loc, LHS, RHS);
10902   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10903   //        usage of the logical operators && and || with vectors in C. This
10904   //        check could be notionally dropped.
10905   if (!getLangOpts().CPlusPlus &&
10906       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10907     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10908 
10909   return GetSignedVectorType(LHS.get()->getType());
10910 }
10911 
10912 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10913                                            SourceLocation Loc,
10914                                            BinaryOperatorKind Opc) {
10915   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10916 
10917   bool IsCompAssign =
10918       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10919 
10920   if (LHS.get()->getType()->isVectorType() ||
10921       RHS.get()->getType()->isVectorType()) {
10922     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10923         RHS.get()->getType()->hasIntegerRepresentation())
10924       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10925                         /*AllowBothBool*/true,
10926                         /*AllowBoolConversions*/getLangOpts().ZVector);
10927     return InvalidOperands(Loc, LHS, RHS);
10928   }
10929 
10930   if (Opc == BO_And)
10931     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10932 
10933   ExprResult LHSResult = LHS, RHSResult = RHS;
10934   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10935                                                  IsCompAssign);
10936   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10937     return QualType();
10938   LHS = LHSResult.get();
10939   RHS = RHSResult.get();
10940 
10941   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10942     return compType;
10943   return InvalidOperands(Loc, LHS, RHS);
10944 }
10945 
10946 // C99 6.5.[13,14]
10947 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10948                                            SourceLocation Loc,
10949                                            BinaryOperatorKind Opc) {
10950   // Check vector operands differently.
10951   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10952     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10953 
10954   // Diagnose cases where the user write a logical and/or but probably meant a
10955   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10956   // is a constant.
10957   if (LHS.get()->getType()->isIntegerType() &&
10958       !LHS.get()->getType()->isBooleanType() &&
10959       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10960       // Don't warn in macros or template instantiations.
10961       !Loc.isMacroID() && !inTemplateInstantiation()) {
10962     // If the RHS can be constant folded, and if it constant folds to something
10963     // that isn't 0 or 1 (which indicate a potential logical operation that
10964     // happened to fold to true/false) then warn.
10965     // Parens on the RHS are ignored.
10966     Expr::EvalResult EVResult;
10967     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10968       llvm::APSInt Result = EVResult.Val.getInt();
10969       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10970            !RHS.get()->getExprLoc().isMacroID()) ||
10971           (Result != 0 && Result != 1)) {
10972         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10973           << RHS.get()->getSourceRange()
10974           << (Opc == BO_LAnd ? "&&" : "||");
10975         // Suggest replacing the logical operator with the bitwise version
10976         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10977             << (Opc == BO_LAnd ? "&" : "|")
10978             << FixItHint::CreateReplacement(SourceRange(
10979                                                  Loc, getLocForEndOfToken(Loc)),
10980                                             Opc == BO_LAnd ? "&" : "|");
10981         if (Opc == BO_LAnd)
10982           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10983           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10984               << FixItHint::CreateRemoval(
10985                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10986                                  RHS.get()->getEndLoc()));
10987       }
10988     }
10989   }
10990 
10991   if (!Context.getLangOpts().CPlusPlus) {
10992     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10993     // not operate on the built-in scalar and vector float types.
10994     if (Context.getLangOpts().OpenCL &&
10995         Context.getLangOpts().OpenCLVersion < 120) {
10996       if (LHS.get()->getType()->isFloatingType() ||
10997           RHS.get()->getType()->isFloatingType())
10998         return InvalidOperands(Loc, LHS, RHS);
10999     }
11000 
11001     LHS = UsualUnaryConversions(LHS.get());
11002     if (LHS.isInvalid())
11003       return QualType();
11004 
11005     RHS = UsualUnaryConversions(RHS.get());
11006     if (RHS.isInvalid())
11007       return QualType();
11008 
11009     if (!LHS.get()->getType()->isScalarType() ||
11010         !RHS.get()->getType()->isScalarType())
11011       return InvalidOperands(Loc, LHS, RHS);
11012 
11013     return Context.IntTy;
11014   }
11015 
11016   // The following is safe because we only use this method for
11017   // non-overloadable operands.
11018 
11019   // C++ [expr.log.and]p1
11020   // C++ [expr.log.or]p1
11021   // The operands are both contextually converted to type bool.
11022   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11023   if (LHSRes.isInvalid())
11024     return InvalidOperands(Loc, LHS, RHS);
11025   LHS = LHSRes;
11026 
11027   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11028   if (RHSRes.isInvalid())
11029     return InvalidOperands(Loc, LHS, RHS);
11030   RHS = RHSRes;
11031 
11032   // C++ [expr.log.and]p2
11033   // C++ [expr.log.or]p2
11034   // The result is a bool.
11035   return Context.BoolTy;
11036 }
11037 
11038 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11039   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11040   if (!ME) return false;
11041   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11042   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11043       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11044   if (!Base) return false;
11045   return Base->getMethodDecl() != nullptr;
11046 }
11047 
11048 /// Is the given expression (which must be 'const') a reference to a
11049 /// variable which was originally non-const, but which has become
11050 /// 'const' due to being captured within a block?
11051 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11052 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11053   assert(E->isLValue() && E->getType().isConstQualified());
11054   E = E->IgnoreParens();
11055 
11056   // Must be a reference to a declaration from an enclosing scope.
11057   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11058   if (!DRE) return NCCK_None;
11059   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11060 
11061   // The declaration must be a variable which is not declared 'const'.
11062   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11063   if (!var) return NCCK_None;
11064   if (var->getType().isConstQualified()) return NCCK_None;
11065   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11066 
11067   // Decide whether the first capture was for a block or a lambda.
11068   DeclContext *DC = S.CurContext, *Prev = nullptr;
11069   // Decide whether the first capture was for a block or a lambda.
11070   while (DC) {
11071     // For init-capture, it is possible that the variable belongs to the
11072     // template pattern of the current context.
11073     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11074       if (var->isInitCapture() &&
11075           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11076         break;
11077     if (DC == var->getDeclContext())
11078       break;
11079     Prev = DC;
11080     DC = DC->getParent();
11081   }
11082   // Unless we have an init-capture, we've gone one step too far.
11083   if (!var->isInitCapture())
11084     DC = Prev;
11085   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11086 }
11087 
11088 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11089   Ty = Ty.getNonReferenceType();
11090   if (IsDereference && Ty->isPointerType())
11091     Ty = Ty->getPointeeType();
11092   return !Ty.isConstQualified();
11093 }
11094 
11095 // Update err_typecheck_assign_const and note_typecheck_assign_const
11096 // when this enum is changed.
11097 enum {
11098   ConstFunction,
11099   ConstVariable,
11100   ConstMember,
11101   ConstMethod,
11102   NestedConstMember,
11103   ConstUnknown,  // Keep as last element
11104 };
11105 
11106 /// Emit the "read-only variable not assignable" error and print notes to give
11107 /// more information about why the variable is not assignable, such as pointing
11108 /// to the declaration of a const variable, showing that a method is const, or
11109 /// that the function is returning a const reference.
11110 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11111                                     SourceLocation Loc) {
11112   SourceRange ExprRange = E->getSourceRange();
11113 
11114   // Only emit one error on the first const found.  All other consts will emit
11115   // a note to the error.
11116   bool DiagnosticEmitted = false;
11117 
11118   // Track if the current expression is the result of a dereference, and if the
11119   // next checked expression is the result of a dereference.
11120   bool IsDereference = false;
11121   bool NextIsDereference = false;
11122 
11123   // Loop to process MemberExpr chains.
11124   while (true) {
11125     IsDereference = NextIsDereference;
11126 
11127     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11128     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11129       NextIsDereference = ME->isArrow();
11130       const ValueDecl *VD = ME->getMemberDecl();
11131       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11132         // Mutable fields can be modified even if the class is const.
11133         if (Field->isMutable()) {
11134           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11135           break;
11136         }
11137 
11138         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11139           if (!DiagnosticEmitted) {
11140             S.Diag(Loc, diag::err_typecheck_assign_const)
11141                 << ExprRange << ConstMember << false /*static*/ << Field
11142                 << Field->getType();
11143             DiagnosticEmitted = true;
11144           }
11145           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11146               << ConstMember << false /*static*/ << Field << Field->getType()
11147               << Field->getSourceRange();
11148         }
11149         E = ME->getBase();
11150         continue;
11151       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11152         if (VDecl->getType().isConstQualified()) {
11153           if (!DiagnosticEmitted) {
11154             S.Diag(Loc, diag::err_typecheck_assign_const)
11155                 << ExprRange << ConstMember << true /*static*/ << VDecl
11156                 << VDecl->getType();
11157             DiagnosticEmitted = true;
11158           }
11159           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11160               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11161               << VDecl->getSourceRange();
11162         }
11163         // Static fields do not inherit constness from parents.
11164         break;
11165       }
11166       break; // End MemberExpr
11167     } else if (const ArraySubscriptExpr *ASE =
11168                    dyn_cast<ArraySubscriptExpr>(E)) {
11169       E = ASE->getBase()->IgnoreParenImpCasts();
11170       continue;
11171     } else if (const ExtVectorElementExpr *EVE =
11172                    dyn_cast<ExtVectorElementExpr>(E)) {
11173       E = EVE->getBase()->IgnoreParenImpCasts();
11174       continue;
11175     }
11176     break;
11177   }
11178 
11179   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11180     // Function calls
11181     const FunctionDecl *FD = CE->getDirectCallee();
11182     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11183       if (!DiagnosticEmitted) {
11184         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11185                                                       << ConstFunction << FD;
11186         DiagnosticEmitted = true;
11187       }
11188       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11189              diag::note_typecheck_assign_const)
11190           << ConstFunction << FD << FD->getReturnType()
11191           << FD->getReturnTypeSourceRange();
11192     }
11193   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11194     // Point to variable declaration.
11195     if (const ValueDecl *VD = DRE->getDecl()) {
11196       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11197         if (!DiagnosticEmitted) {
11198           S.Diag(Loc, diag::err_typecheck_assign_const)
11199               << ExprRange << ConstVariable << VD << VD->getType();
11200           DiagnosticEmitted = true;
11201         }
11202         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11203             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11204       }
11205     }
11206   } else if (isa<CXXThisExpr>(E)) {
11207     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11208       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11209         if (MD->isConst()) {
11210           if (!DiagnosticEmitted) {
11211             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11212                                                           << ConstMethod << MD;
11213             DiagnosticEmitted = true;
11214           }
11215           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11216               << ConstMethod << MD << MD->getSourceRange();
11217         }
11218       }
11219     }
11220   }
11221 
11222   if (DiagnosticEmitted)
11223     return;
11224 
11225   // Can't determine a more specific message, so display the generic error.
11226   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11227 }
11228 
11229 enum OriginalExprKind {
11230   OEK_Variable,
11231   OEK_Member,
11232   OEK_LValue
11233 };
11234 
11235 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11236                                          const RecordType *Ty,
11237                                          SourceLocation Loc, SourceRange Range,
11238                                          OriginalExprKind OEK,
11239                                          bool &DiagnosticEmitted) {
11240   std::vector<const RecordType *> RecordTypeList;
11241   RecordTypeList.push_back(Ty);
11242   unsigned NextToCheckIndex = 0;
11243   // We walk the record hierarchy breadth-first to ensure that we print
11244   // diagnostics in field nesting order.
11245   while (RecordTypeList.size() > NextToCheckIndex) {
11246     bool IsNested = NextToCheckIndex > 0;
11247     for (const FieldDecl *Field :
11248          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11249       // First, check every field for constness.
11250       QualType FieldTy = Field->getType();
11251       if (FieldTy.isConstQualified()) {
11252         if (!DiagnosticEmitted) {
11253           S.Diag(Loc, diag::err_typecheck_assign_const)
11254               << Range << NestedConstMember << OEK << VD
11255               << IsNested << Field;
11256           DiagnosticEmitted = true;
11257         }
11258         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11259             << NestedConstMember << IsNested << Field
11260             << FieldTy << Field->getSourceRange();
11261       }
11262 
11263       // Then we append it to the list to check next in order.
11264       FieldTy = FieldTy.getCanonicalType();
11265       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11266         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11267           RecordTypeList.push_back(FieldRecTy);
11268       }
11269     }
11270     ++NextToCheckIndex;
11271   }
11272 }
11273 
11274 /// Emit an error for the case where a record we are trying to assign to has a
11275 /// const-qualified field somewhere in its hierarchy.
11276 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11277                                          SourceLocation Loc) {
11278   QualType Ty = E->getType();
11279   assert(Ty->isRecordType() && "lvalue was not record?");
11280   SourceRange Range = E->getSourceRange();
11281   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11282   bool DiagEmitted = false;
11283 
11284   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11285     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11286             Range, OEK_Member, DiagEmitted);
11287   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11288     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11289             Range, OEK_Variable, DiagEmitted);
11290   else
11291     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11292             Range, OEK_LValue, DiagEmitted);
11293   if (!DiagEmitted)
11294     DiagnoseConstAssignment(S, E, Loc);
11295 }
11296 
11297 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11298 /// emit an error and return true.  If so, return false.
11299 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11300   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11301 
11302   S.CheckShadowingDeclModification(E, Loc);
11303 
11304   SourceLocation OrigLoc = Loc;
11305   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11306                                                               &Loc);
11307   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11308     IsLV = Expr::MLV_InvalidMessageExpression;
11309   if (IsLV == Expr::MLV_Valid)
11310     return false;
11311 
11312   unsigned DiagID = 0;
11313   bool NeedType = false;
11314   switch (IsLV) { // C99 6.5.16p2
11315   case Expr::MLV_ConstQualified:
11316     // Use a specialized diagnostic when we're assigning to an object
11317     // from an enclosing function or block.
11318     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11319       if (NCCK == NCCK_Block)
11320         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11321       else
11322         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11323       break;
11324     }
11325 
11326     // In ARC, use some specialized diagnostics for occasions where we
11327     // infer 'const'.  These are always pseudo-strong variables.
11328     if (S.getLangOpts().ObjCAutoRefCount) {
11329       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11330       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11331         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11332 
11333         // Use the normal diagnostic if it's pseudo-__strong but the
11334         // user actually wrote 'const'.
11335         if (var->isARCPseudoStrong() &&
11336             (!var->getTypeSourceInfo() ||
11337              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11338           // There are three pseudo-strong cases:
11339           //  - self
11340           ObjCMethodDecl *method = S.getCurMethodDecl();
11341           if (method && var == method->getSelfDecl()) {
11342             DiagID = method->isClassMethod()
11343               ? diag::err_typecheck_arc_assign_self_class_method
11344               : diag::err_typecheck_arc_assign_self;
11345 
11346           //  - Objective-C externally_retained attribute.
11347           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11348                      isa<ParmVarDecl>(var)) {
11349             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11350 
11351           //  - fast enumeration variables
11352           } else {
11353             DiagID = diag::err_typecheck_arr_assign_enumeration;
11354           }
11355 
11356           SourceRange Assign;
11357           if (Loc != OrigLoc)
11358             Assign = SourceRange(OrigLoc, OrigLoc);
11359           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11360           // We need to preserve the AST regardless, so migration tool
11361           // can do its job.
11362           return false;
11363         }
11364       }
11365     }
11366 
11367     // If none of the special cases above are triggered, then this is a
11368     // simple const assignment.
11369     if (DiagID == 0) {
11370       DiagnoseConstAssignment(S, E, Loc);
11371       return true;
11372     }
11373 
11374     break;
11375   case Expr::MLV_ConstAddrSpace:
11376     DiagnoseConstAssignment(S, E, Loc);
11377     return true;
11378   case Expr::MLV_ConstQualifiedField:
11379     DiagnoseRecursiveConstFields(S, E, Loc);
11380     return true;
11381   case Expr::MLV_ArrayType:
11382   case Expr::MLV_ArrayTemporary:
11383     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11384     NeedType = true;
11385     break;
11386   case Expr::MLV_NotObjectType:
11387     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11388     NeedType = true;
11389     break;
11390   case Expr::MLV_LValueCast:
11391     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11392     break;
11393   case Expr::MLV_Valid:
11394     llvm_unreachable("did not take early return for MLV_Valid");
11395   case Expr::MLV_InvalidExpression:
11396   case Expr::MLV_MemberFunction:
11397   case Expr::MLV_ClassTemporary:
11398     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11399     break;
11400   case Expr::MLV_IncompleteType:
11401   case Expr::MLV_IncompleteVoidType:
11402     return S.RequireCompleteType(Loc, E->getType(),
11403              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11404   case Expr::MLV_DuplicateVectorComponents:
11405     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11406     break;
11407   case Expr::MLV_NoSetterProperty:
11408     llvm_unreachable("readonly properties should be processed differently");
11409   case Expr::MLV_InvalidMessageExpression:
11410     DiagID = diag::err_readonly_message_assignment;
11411     break;
11412   case Expr::MLV_SubObjCPropertySetting:
11413     DiagID = diag::err_no_subobject_property_setting;
11414     break;
11415   }
11416 
11417   SourceRange Assign;
11418   if (Loc != OrigLoc)
11419     Assign = SourceRange(OrigLoc, OrigLoc);
11420   if (NeedType)
11421     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11422   else
11423     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11424   return true;
11425 }
11426 
11427 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11428                                          SourceLocation Loc,
11429                                          Sema &Sema) {
11430   if (Sema.inTemplateInstantiation())
11431     return;
11432   if (Sema.isUnevaluatedContext())
11433     return;
11434   if (Loc.isInvalid() || Loc.isMacroID())
11435     return;
11436   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11437     return;
11438 
11439   // C / C++ fields
11440   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11441   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11442   if (ML && MR) {
11443     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11444       return;
11445     const ValueDecl *LHSDecl =
11446         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11447     const ValueDecl *RHSDecl =
11448         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11449     if (LHSDecl != RHSDecl)
11450       return;
11451     if (LHSDecl->getType().isVolatileQualified())
11452       return;
11453     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11454       if (RefTy->getPointeeType().isVolatileQualified())
11455         return;
11456 
11457     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11458   }
11459 
11460   // Objective-C instance variables
11461   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11462   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11463   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11464     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11465     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11466     if (RL && RR && RL->getDecl() == RR->getDecl())
11467       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11468   }
11469 }
11470 
11471 // C99 6.5.16.1
11472 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11473                                        SourceLocation Loc,
11474                                        QualType CompoundType) {
11475   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11476 
11477   // Verify that LHS is a modifiable lvalue, and emit error if not.
11478   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11479     return QualType();
11480 
11481   QualType LHSType = LHSExpr->getType();
11482   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11483                                              CompoundType;
11484   // OpenCL v1.2 s6.1.1.1 p2:
11485   // The half data type can only be used to declare a pointer to a buffer that
11486   // contains half values
11487   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11488     LHSType->isHalfType()) {
11489     Diag(Loc, diag::err_opencl_half_load_store) << 1
11490         << LHSType.getUnqualifiedType();
11491     return QualType();
11492   }
11493 
11494   AssignConvertType ConvTy;
11495   if (CompoundType.isNull()) {
11496     Expr *RHSCheck = RHS.get();
11497 
11498     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11499 
11500     QualType LHSTy(LHSType);
11501     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11502     if (RHS.isInvalid())
11503       return QualType();
11504     // Special case of NSObject attributes on c-style pointer types.
11505     if (ConvTy == IncompatiblePointer &&
11506         ((Context.isObjCNSObjectType(LHSType) &&
11507           RHSType->isObjCObjectPointerType()) ||
11508          (Context.isObjCNSObjectType(RHSType) &&
11509           LHSType->isObjCObjectPointerType())))
11510       ConvTy = Compatible;
11511 
11512     if (ConvTy == Compatible &&
11513         LHSType->isObjCObjectType())
11514         Diag(Loc, diag::err_objc_object_assignment)
11515           << LHSType;
11516 
11517     // If the RHS is a unary plus or minus, check to see if they = and + are
11518     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11519     // instead of "x += 4".
11520     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11521       RHSCheck = ICE->getSubExpr();
11522     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11523       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11524           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11525           // Only if the two operators are exactly adjacent.
11526           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11527           // And there is a space or other character before the subexpr of the
11528           // unary +/-.  We don't want to warn on "x=-1".
11529           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11530           UO->getSubExpr()->getBeginLoc().isFileID()) {
11531         Diag(Loc, diag::warn_not_compound_assign)
11532           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11533           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11534       }
11535     }
11536 
11537     if (ConvTy == Compatible) {
11538       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11539         // Warn about retain cycles where a block captures the LHS, but
11540         // not if the LHS is a simple variable into which the block is
11541         // being stored...unless that variable can be captured by reference!
11542         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11543         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11544         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11545           checkRetainCycles(LHSExpr, RHS.get());
11546       }
11547 
11548       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11549           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11550         // It is safe to assign a weak reference into a strong variable.
11551         // Although this code can still have problems:
11552         //   id x = self.weakProp;
11553         //   id y = self.weakProp;
11554         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11555         // paths through the function. This should be revisited if
11556         // -Wrepeated-use-of-weak is made flow-sensitive.
11557         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11558         // variable, which will be valid for the current autorelease scope.
11559         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11560                              RHS.get()->getBeginLoc()))
11561           getCurFunction()->markSafeWeakUse(RHS.get());
11562 
11563       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11564         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11565       }
11566     }
11567   } else {
11568     // Compound assignment "x += y"
11569     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11570   }
11571 
11572   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11573                                RHS.get(), AA_Assigning))
11574     return QualType();
11575 
11576   CheckForNullPointerDereference(*this, LHSExpr);
11577 
11578   // C99 6.5.16p3: The type of an assignment expression is the type of the
11579   // left operand unless the left operand has qualified type, in which case
11580   // it is the unqualified version of the type of the left operand.
11581   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11582   // is converted to the type of the assignment expression (above).
11583   // C++ 5.17p1: the type of the assignment expression is that of its left
11584   // operand.
11585   return (getLangOpts().CPlusPlus
11586           ? LHSType : LHSType.getUnqualifiedType());
11587 }
11588 
11589 // Only ignore explicit casts to void.
11590 static bool IgnoreCommaOperand(const Expr *E) {
11591   E = E->IgnoreParens();
11592 
11593   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11594     if (CE->getCastKind() == CK_ToVoid) {
11595       return true;
11596     }
11597 
11598     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11599     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11600         CE->getSubExpr()->getType()->isDependentType()) {
11601       return true;
11602     }
11603   }
11604 
11605   return false;
11606 }
11607 
11608 // Look for instances where it is likely the comma operator is confused with
11609 // another operator.  There is a whitelist of acceptable expressions for the
11610 // left hand side of the comma operator, otherwise emit a warning.
11611 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11612   // No warnings in macros
11613   if (Loc.isMacroID())
11614     return;
11615 
11616   // Don't warn in template instantiations.
11617   if (inTemplateInstantiation())
11618     return;
11619 
11620   // Scope isn't fine-grained enough to whitelist the specific cases, so
11621   // instead, skip more than needed, then call back into here with the
11622   // CommaVisitor in SemaStmt.cpp.
11623   // The whitelisted locations are the initialization and increment portions
11624   // of a for loop.  The additional checks are on the condition of
11625   // if statements, do/while loops, and for loops.
11626   // Differences in scope flags for C89 mode requires the extra logic.
11627   const unsigned ForIncrementFlags =
11628       getLangOpts().C99 || getLangOpts().CPlusPlus
11629           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11630           : Scope::ContinueScope | Scope::BreakScope;
11631   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11632   const unsigned ScopeFlags = getCurScope()->getFlags();
11633   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11634       (ScopeFlags & ForInitFlags) == ForInitFlags)
11635     return;
11636 
11637   // If there are multiple comma operators used together, get the RHS of the
11638   // of the comma operator as the LHS.
11639   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11640     if (BO->getOpcode() != BO_Comma)
11641       break;
11642     LHS = BO->getRHS();
11643   }
11644 
11645   // Only allow some expressions on LHS to not warn.
11646   if (IgnoreCommaOperand(LHS))
11647     return;
11648 
11649   Diag(Loc, diag::warn_comma_operator);
11650   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11651       << LHS->getSourceRange()
11652       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11653                                     LangOpts.CPlusPlus ? "static_cast<void>("
11654                                                        : "(void)(")
11655       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11656                                     ")");
11657 }
11658 
11659 // C99 6.5.17
11660 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11661                                    SourceLocation Loc) {
11662   LHS = S.CheckPlaceholderExpr(LHS.get());
11663   RHS = S.CheckPlaceholderExpr(RHS.get());
11664   if (LHS.isInvalid() || RHS.isInvalid())
11665     return QualType();
11666 
11667   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11668   // operands, but not unary promotions.
11669   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11670 
11671   // So we treat the LHS as a ignored value, and in C++ we allow the
11672   // containing site to determine what should be done with the RHS.
11673   LHS = S.IgnoredValueConversions(LHS.get());
11674   if (LHS.isInvalid())
11675     return QualType();
11676 
11677   S.DiagnoseUnusedExprResult(LHS.get());
11678 
11679   if (!S.getLangOpts().CPlusPlus) {
11680     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11681     if (RHS.isInvalid())
11682       return QualType();
11683     if (!RHS.get()->getType()->isVoidType())
11684       S.RequireCompleteType(Loc, RHS.get()->getType(),
11685                             diag::err_incomplete_type);
11686   }
11687 
11688   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11689     S.DiagnoseCommaOperator(LHS.get(), Loc);
11690 
11691   return RHS.get()->getType();
11692 }
11693 
11694 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11695 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11696 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11697                                                ExprValueKind &VK,
11698                                                ExprObjectKind &OK,
11699                                                SourceLocation OpLoc,
11700                                                bool IsInc, bool IsPrefix) {
11701   if (Op->isTypeDependent())
11702     return S.Context.DependentTy;
11703 
11704   QualType ResType = Op->getType();
11705   // Atomic types can be used for increment / decrement where the non-atomic
11706   // versions can, so ignore the _Atomic() specifier for the purpose of
11707   // checking.
11708   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11709     ResType = ResAtomicType->getValueType();
11710 
11711   assert(!ResType.isNull() && "no type for increment/decrement expression");
11712 
11713   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11714     // Decrement of bool is not allowed.
11715     if (!IsInc) {
11716       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11717       return QualType();
11718     }
11719     // Increment of bool sets it to true, but is deprecated.
11720     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11721                                               : diag::warn_increment_bool)
11722       << Op->getSourceRange();
11723   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11724     // Error on enum increments and decrements in C++ mode
11725     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11726     return QualType();
11727   } else if (ResType->isRealType()) {
11728     // OK!
11729   } else if (ResType->isPointerType()) {
11730     // C99 6.5.2.4p2, 6.5.6p2
11731     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11732       return QualType();
11733   } else if (ResType->isObjCObjectPointerType()) {
11734     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11735     // Otherwise, we just need a complete type.
11736     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11737         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11738       return QualType();
11739   } else if (ResType->isAnyComplexType()) {
11740     // C99 does not support ++/-- on complex types, we allow as an extension.
11741     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11742       << ResType << Op->getSourceRange();
11743   } else if (ResType->isPlaceholderType()) {
11744     ExprResult PR = S.CheckPlaceholderExpr(Op);
11745     if (PR.isInvalid()) return QualType();
11746     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11747                                           IsInc, IsPrefix);
11748   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11749     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11750   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11751              (ResType->getAs<VectorType>()->getVectorKind() !=
11752               VectorType::AltiVecBool)) {
11753     // The z vector extensions allow ++ and -- for non-bool vectors.
11754   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11755             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11756     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11757   } else {
11758     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11759       << ResType << int(IsInc) << Op->getSourceRange();
11760     return QualType();
11761   }
11762   // At this point, we know we have a real, complex or pointer type.
11763   // Now make sure the operand is a modifiable lvalue.
11764   if (CheckForModifiableLvalue(Op, OpLoc, S))
11765     return QualType();
11766   // In C++, a prefix increment is the same type as the operand. Otherwise
11767   // (in C or with postfix), the increment is the unqualified type of the
11768   // operand.
11769   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11770     VK = VK_LValue;
11771     OK = Op->getObjectKind();
11772     return ResType;
11773   } else {
11774     VK = VK_RValue;
11775     return ResType.getUnqualifiedType();
11776   }
11777 }
11778 
11779 
11780 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11781 /// This routine allows us to typecheck complex/recursive expressions
11782 /// where the declaration is needed for type checking. We only need to
11783 /// handle cases when the expression references a function designator
11784 /// or is an lvalue. Here are some examples:
11785 ///  - &(x) => x
11786 ///  - &*****f => f for f a function designator.
11787 ///  - &s.xx => s
11788 ///  - &s.zz[1].yy -> s, if zz is an array
11789 ///  - *(x + 1) -> x, if x is an array
11790 ///  - &"123"[2] -> 0
11791 ///  - & __real__ x -> x
11792 static ValueDecl *getPrimaryDecl(Expr *E) {
11793   switch (E->getStmtClass()) {
11794   case Stmt::DeclRefExprClass:
11795     return cast<DeclRefExpr>(E)->getDecl();
11796   case Stmt::MemberExprClass:
11797     // If this is an arrow operator, the address is an offset from
11798     // the base's value, so the object the base refers to is
11799     // irrelevant.
11800     if (cast<MemberExpr>(E)->isArrow())
11801       return nullptr;
11802     // Otherwise, the expression refers to a part of the base
11803     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11804   case Stmt::ArraySubscriptExprClass: {
11805     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11806     // promotion of register arrays earlier.
11807     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11808     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11809       if (ICE->getSubExpr()->getType()->isArrayType())
11810         return getPrimaryDecl(ICE->getSubExpr());
11811     }
11812     return nullptr;
11813   }
11814   case Stmt::UnaryOperatorClass: {
11815     UnaryOperator *UO = cast<UnaryOperator>(E);
11816 
11817     switch(UO->getOpcode()) {
11818     case UO_Real:
11819     case UO_Imag:
11820     case UO_Extension:
11821       return getPrimaryDecl(UO->getSubExpr());
11822     default:
11823       return nullptr;
11824     }
11825   }
11826   case Stmt::ParenExprClass:
11827     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11828   case Stmt::ImplicitCastExprClass:
11829     // If the result of an implicit cast is an l-value, we care about
11830     // the sub-expression; otherwise, the result here doesn't matter.
11831     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11832   default:
11833     return nullptr;
11834   }
11835 }
11836 
11837 namespace {
11838   enum {
11839     AO_Bit_Field = 0,
11840     AO_Vector_Element = 1,
11841     AO_Property_Expansion = 2,
11842     AO_Register_Variable = 3,
11843     AO_No_Error = 4
11844   };
11845 }
11846 /// Diagnose invalid operand for address of operations.
11847 ///
11848 /// \param Type The type of operand which cannot have its address taken.
11849 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11850                                          Expr *E, unsigned Type) {
11851   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11852 }
11853 
11854 /// CheckAddressOfOperand - The operand of & must be either a function
11855 /// designator or an lvalue designating an object. If it is an lvalue, the
11856 /// object cannot be declared with storage class register or be a bit field.
11857 /// Note: The usual conversions are *not* applied to the operand of the &
11858 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11859 /// In C++, the operand might be an overloaded function name, in which case
11860 /// we allow the '&' but retain the overloaded-function type.
11861 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11862   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11863     if (PTy->getKind() == BuiltinType::Overload) {
11864       Expr *E = OrigOp.get()->IgnoreParens();
11865       if (!isa<OverloadExpr>(E)) {
11866         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11867         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11868           << OrigOp.get()->getSourceRange();
11869         return QualType();
11870       }
11871 
11872       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11873       if (isa<UnresolvedMemberExpr>(Ovl))
11874         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11875           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11876             << OrigOp.get()->getSourceRange();
11877           return QualType();
11878         }
11879 
11880       return Context.OverloadTy;
11881     }
11882 
11883     if (PTy->getKind() == BuiltinType::UnknownAny)
11884       return Context.UnknownAnyTy;
11885 
11886     if (PTy->getKind() == BuiltinType::BoundMember) {
11887       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11888         << OrigOp.get()->getSourceRange();
11889       return QualType();
11890     }
11891 
11892     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11893     if (OrigOp.isInvalid()) return QualType();
11894   }
11895 
11896   if (OrigOp.get()->isTypeDependent())
11897     return Context.DependentTy;
11898 
11899   assert(!OrigOp.get()->getType()->isPlaceholderType());
11900 
11901   // Make sure to ignore parentheses in subsequent checks
11902   Expr *op = OrigOp.get()->IgnoreParens();
11903 
11904   // In OpenCL captures for blocks called as lambda functions
11905   // are located in the private address space. Blocks used in
11906   // enqueue_kernel can be located in a different address space
11907   // depending on a vendor implementation. Thus preventing
11908   // taking an address of the capture to avoid invalid AS casts.
11909   if (LangOpts.OpenCL) {
11910     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11911     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11912       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11913       return QualType();
11914     }
11915   }
11916 
11917   if (getLangOpts().C99) {
11918     // Implement C99-only parts of addressof rules.
11919     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11920       if (uOp->getOpcode() == UO_Deref)
11921         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11922         // (assuming the deref expression is valid).
11923         return uOp->getSubExpr()->getType();
11924     }
11925     // Technically, there should be a check for array subscript
11926     // expressions here, but the result of one is always an lvalue anyway.
11927   }
11928   ValueDecl *dcl = getPrimaryDecl(op);
11929 
11930   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11931     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11932                                            op->getBeginLoc()))
11933       return QualType();
11934 
11935   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11936   unsigned AddressOfError = AO_No_Error;
11937 
11938   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11939     bool sfinae = (bool)isSFINAEContext();
11940     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11941                                   : diag::ext_typecheck_addrof_temporary)
11942       << op->getType() << op->getSourceRange();
11943     if (sfinae)
11944       return QualType();
11945     // Materialize the temporary as an lvalue so that we can take its address.
11946     OrigOp = op =
11947         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11948   } else if (isa<ObjCSelectorExpr>(op)) {
11949     return Context.getPointerType(op->getType());
11950   } else if (lval == Expr::LV_MemberFunction) {
11951     // If it's an instance method, make a member pointer.
11952     // The expression must have exactly the form &A::foo.
11953 
11954     // If the underlying expression isn't a decl ref, give up.
11955     if (!isa<DeclRefExpr>(op)) {
11956       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11957         << OrigOp.get()->getSourceRange();
11958       return QualType();
11959     }
11960     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11961     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11962 
11963     // The id-expression was parenthesized.
11964     if (OrigOp.get() != DRE) {
11965       Diag(OpLoc, diag::err_parens_pointer_member_function)
11966         << OrigOp.get()->getSourceRange();
11967 
11968     // The method was named without a qualifier.
11969     } else if (!DRE->getQualifier()) {
11970       if (MD->getParent()->getName().empty())
11971         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11972           << op->getSourceRange();
11973       else {
11974         SmallString<32> Str;
11975         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11976         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11977           << op->getSourceRange()
11978           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11979       }
11980     }
11981 
11982     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11983     if (isa<CXXDestructorDecl>(MD))
11984       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11985 
11986     QualType MPTy = Context.getMemberPointerType(
11987         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11988     // Under the MS ABI, lock down the inheritance model now.
11989     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11990       (void)isCompleteType(OpLoc, MPTy);
11991     return MPTy;
11992   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11993     // C99 6.5.3.2p1
11994     // The operand must be either an l-value or a function designator
11995     if (!op->getType()->isFunctionType()) {
11996       // Use a special diagnostic for loads from property references.
11997       if (isa<PseudoObjectExpr>(op)) {
11998         AddressOfError = AO_Property_Expansion;
11999       } else {
12000         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12001           << op->getType() << op->getSourceRange();
12002         return QualType();
12003       }
12004     }
12005   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12006     // The operand cannot be a bit-field
12007     AddressOfError = AO_Bit_Field;
12008   } else if (op->getObjectKind() == OK_VectorComponent) {
12009     // The operand cannot be an element of a vector
12010     AddressOfError = AO_Vector_Element;
12011   } else if (dcl) { // C99 6.5.3.2p1
12012     // We have an lvalue with a decl. Make sure the decl is not declared
12013     // with the register storage-class specifier.
12014     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12015       // in C++ it is not error to take address of a register
12016       // variable (c++03 7.1.1P3)
12017       if (vd->getStorageClass() == SC_Register &&
12018           !getLangOpts().CPlusPlus) {
12019         AddressOfError = AO_Register_Variable;
12020       }
12021     } else if (isa<MSPropertyDecl>(dcl)) {
12022       AddressOfError = AO_Property_Expansion;
12023     } else if (isa<FunctionTemplateDecl>(dcl)) {
12024       return Context.OverloadTy;
12025     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12026       // Okay: we can take the address of a field.
12027       // Could be a pointer to member, though, if there is an explicit
12028       // scope qualifier for the class.
12029       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12030         DeclContext *Ctx = dcl->getDeclContext();
12031         if (Ctx && Ctx->isRecord()) {
12032           if (dcl->getType()->isReferenceType()) {
12033             Diag(OpLoc,
12034                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12035               << dcl->getDeclName() << dcl->getType();
12036             return QualType();
12037           }
12038 
12039           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12040             Ctx = Ctx->getParent();
12041 
12042           QualType MPTy = Context.getMemberPointerType(
12043               op->getType(),
12044               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12045           // Under the MS ABI, lock down the inheritance model now.
12046           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12047             (void)isCompleteType(OpLoc, MPTy);
12048           return MPTy;
12049         }
12050       }
12051     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12052                !isa<BindingDecl>(dcl))
12053       llvm_unreachable("Unknown/unexpected decl type");
12054   }
12055 
12056   if (AddressOfError != AO_No_Error) {
12057     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12058     return QualType();
12059   }
12060 
12061   if (lval == Expr::LV_IncompleteVoidType) {
12062     // Taking the address of a void variable is technically illegal, but we
12063     // allow it in cases which are otherwise valid.
12064     // Example: "extern void x; void* y = &x;".
12065     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12066   }
12067 
12068   // If the operand has type "type", the result has type "pointer to type".
12069   if (op->getType()->isObjCObjectType())
12070     return Context.getObjCObjectPointerType(op->getType());
12071 
12072   CheckAddressOfPackedMember(op);
12073 
12074   return Context.getPointerType(op->getType());
12075 }
12076 
12077 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12078   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12079   if (!DRE)
12080     return;
12081   const Decl *D = DRE->getDecl();
12082   if (!D)
12083     return;
12084   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12085   if (!Param)
12086     return;
12087   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12088     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12089       return;
12090   if (FunctionScopeInfo *FD = S.getCurFunction())
12091     if (!FD->ModifiedNonNullParams.count(Param))
12092       FD->ModifiedNonNullParams.insert(Param);
12093 }
12094 
12095 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12096 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12097                                         SourceLocation OpLoc) {
12098   if (Op->isTypeDependent())
12099     return S.Context.DependentTy;
12100 
12101   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12102   if (ConvResult.isInvalid())
12103     return QualType();
12104   Op = ConvResult.get();
12105   QualType OpTy = Op->getType();
12106   QualType Result;
12107 
12108   if (isa<CXXReinterpretCastExpr>(Op)) {
12109     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12110     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12111                                      Op->getSourceRange());
12112   }
12113 
12114   if (const PointerType *PT = OpTy->getAs<PointerType>())
12115   {
12116     Result = PT->getPointeeType();
12117   }
12118   else if (const ObjCObjectPointerType *OPT =
12119              OpTy->getAs<ObjCObjectPointerType>())
12120     Result = OPT->getPointeeType();
12121   else {
12122     ExprResult PR = S.CheckPlaceholderExpr(Op);
12123     if (PR.isInvalid()) return QualType();
12124     if (PR.get() != Op)
12125       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12126   }
12127 
12128   if (Result.isNull()) {
12129     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12130       << OpTy << Op->getSourceRange();
12131     return QualType();
12132   }
12133 
12134   // Note that per both C89 and C99, indirection is always legal, even if Result
12135   // is an incomplete type or void.  It would be possible to warn about
12136   // dereferencing a void pointer, but it's completely well-defined, and such a
12137   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12138   // for pointers to 'void' but is fine for any other pointer type:
12139   //
12140   // C++ [expr.unary.op]p1:
12141   //   [...] the expression to which [the unary * operator] is applied shall
12142   //   be a pointer to an object type, or a pointer to a function type
12143   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12144     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12145       << OpTy << Op->getSourceRange();
12146 
12147   // Dereferences are usually l-values...
12148   VK = VK_LValue;
12149 
12150   // ...except that certain expressions are never l-values in C.
12151   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12152     VK = VK_RValue;
12153 
12154   return Result;
12155 }
12156 
12157 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12158   BinaryOperatorKind Opc;
12159   switch (Kind) {
12160   default: llvm_unreachable("Unknown binop!");
12161   case tok::periodstar:           Opc = BO_PtrMemD; break;
12162   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12163   case tok::star:                 Opc = BO_Mul; break;
12164   case tok::slash:                Opc = BO_Div; break;
12165   case tok::percent:              Opc = BO_Rem; break;
12166   case tok::plus:                 Opc = BO_Add; break;
12167   case tok::minus:                Opc = BO_Sub; break;
12168   case tok::lessless:             Opc = BO_Shl; break;
12169   case tok::greatergreater:       Opc = BO_Shr; break;
12170   case tok::lessequal:            Opc = BO_LE; break;
12171   case tok::less:                 Opc = BO_LT; break;
12172   case tok::greaterequal:         Opc = BO_GE; break;
12173   case tok::greater:              Opc = BO_GT; break;
12174   case tok::exclaimequal:         Opc = BO_NE; break;
12175   case tok::equalequal:           Opc = BO_EQ; break;
12176   case tok::spaceship:            Opc = BO_Cmp; break;
12177   case tok::amp:                  Opc = BO_And; break;
12178   case tok::caret:                Opc = BO_Xor; break;
12179   case tok::pipe:                 Opc = BO_Or; break;
12180   case tok::ampamp:               Opc = BO_LAnd; break;
12181   case tok::pipepipe:             Opc = BO_LOr; break;
12182   case tok::equal:                Opc = BO_Assign; break;
12183   case tok::starequal:            Opc = BO_MulAssign; break;
12184   case tok::slashequal:           Opc = BO_DivAssign; break;
12185   case tok::percentequal:         Opc = BO_RemAssign; break;
12186   case tok::plusequal:            Opc = BO_AddAssign; break;
12187   case tok::minusequal:           Opc = BO_SubAssign; break;
12188   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12189   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12190   case tok::ampequal:             Opc = BO_AndAssign; break;
12191   case tok::caretequal:           Opc = BO_XorAssign; break;
12192   case tok::pipeequal:            Opc = BO_OrAssign; break;
12193   case tok::comma:                Opc = BO_Comma; break;
12194   }
12195   return Opc;
12196 }
12197 
12198 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12199   tok::TokenKind Kind) {
12200   UnaryOperatorKind Opc;
12201   switch (Kind) {
12202   default: llvm_unreachable("Unknown unary op!");
12203   case tok::plusplus:     Opc = UO_PreInc; break;
12204   case tok::minusminus:   Opc = UO_PreDec; break;
12205   case tok::amp:          Opc = UO_AddrOf; break;
12206   case tok::star:         Opc = UO_Deref; break;
12207   case tok::plus:         Opc = UO_Plus; break;
12208   case tok::minus:        Opc = UO_Minus; break;
12209   case tok::tilde:        Opc = UO_Not; break;
12210   case tok::exclaim:      Opc = UO_LNot; break;
12211   case tok::kw___real:    Opc = UO_Real; break;
12212   case tok::kw___imag:    Opc = UO_Imag; break;
12213   case tok::kw___extension__: Opc = UO_Extension; break;
12214   }
12215   return Opc;
12216 }
12217 
12218 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12219 /// This warning suppressed in the event of macro expansions.
12220 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12221                                    SourceLocation OpLoc, bool IsBuiltin) {
12222   if (S.inTemplateInstantiation())
12223     return;
12224   if (S.isUnevaluatedContext())
12225     return;
12226   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12227     return;
12228   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12229   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12230   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12231   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12232   if (!LHSDeclRef || !RHSDeclRef ||
12233       LHSDeclRef->getLocation().isMacroID() ||
12234       RHSDeclRef->getLocation().isMacroID())
12235     return;
12236   const ValueDecl *LHSDecl =
12237     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12238   const ValueDecl *RHSDecl =
12239     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12240   if (LHSDecl != RHSDecl)
12241     return;
12242   if (LHSDecl->getType().isVolatileQualified())
12243     return;
12244   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12245     if (RefTy->getPointeeType().isVolatileQualified())
12246       return;
12247 
12248   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12249                           : diag::warn_self_assignment_overloaded)
12250       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12251       << RHSExpr->getSourceRange();
12252 }
12253 
12254 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12255 /// is usually indicative of introspection within the Objective-C pointer.
12256 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12257                                           SourceLocation OpLoc) {
12258   if (!S.getLangOpts().ObjC)
12259     return;
12260 
12261   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12262   const Expr *LHS = L.get();
12263   const Expr *RHS = R.get();
12264 
12265   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12266     ObjCPointerExpr = LHS;
12267     OtherExpr = RHS;
12268   }
12269   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12270     ObjCPointerExpr = RHS;
12271     OtherExpr = LHS;
12272   }
12273 
12274   // This warning is deliberately made very specific to reduce false
12275   // positives with logic that uses '&' for hashing.  This logic mainly
12276   // looks for code trying to introspect into tagged pointers, which
12277   // code should generally never do.
12278   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12279     unsigned Diag = diag::warn_objc_pointer_masking;
12280     // Determine if we are introspecting the result of performSelectorXXX.
12281     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12282     // Special case messages to -performSelector and friends, which
12283     // can return non-pointer values boxed in a pointer value.
12284     // Some clients may wish to silence warnings in this subcase.
12285     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12286       Selector S = ME->getSelector();
12287       StringRef SelArg0 = S.getNameForSlot(0);
12288       if (SelArg0.startswith("performSelector"))
12289         Diag = diag::warn_objc_pointer_masking_performSelector;
12290     }
12291 
12292     S.Diag(OpLoc, Diag)
12293       << ObjCPointerExpr->getSourceRange();
12294   }
12295 }
12296 
12297 static NamedDecl *getDeclFromExpr(Expr *E) {
12298   if (!E)
12299     return nullptr;
12300   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12301     return DRE->getDecl();
12302   if (auto *ME = dyn_cast<MemberExpr>(E))
12303     return ME->getMemberDecl();
12304   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12305     return IRE->getDecl();
12306   return nullptr;
12307 }
12308 
12309 // This helper function promotes a binary operator's operands (which are of a
12310 // half vector type) to a vector of floats and then truncates the result to
12311 // a vector of either half or short.
12312 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12313                                       BinaryOperatorKind Opc, QualType ResultTy,
12314                                       ExprValueKind VK, ExprObjectKind OK,
12315                                       bool IsCompAssign, SourceLocation OpLoc,
12316                                       FPOptions FPFeatures) {
12317   auto &Context = S.getASTContext();
12318   assert((isVector(ResultTy, Context.HalfTy) ||
12319           isVector(ResultTy, Context.ShortTy)) &&
12320          "Result must be a vector of half or short");
12321   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12322          isVector(RHS.get()->getType(), Context.HalfTy) &&
12323          "both operands expected to be a half vector");
12324 
12325   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12326   QualType BinOpResTy = RHS.get()->getType();
12327 
12328   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12329   // change BinOpResTy to a vector of ints.
12330   if (isVector(ResultTy, Context.ShortTy))
12331     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12332 
12333   if (IsCompAssign)
12334     return new (Context) CompoundAssignOperator(
12335         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12336         OpLoc, FPFeatures);
12337 
12338   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12339   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12340                                           VK, OK, OpLoc, FPFeatures);
12341   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12342 }
12343 
12344 static std::pair<ExprResult, ExprResult>
12345 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12346                            Expr *RHSExpr) {
12347   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12348   if (!S.getLangOpts().CPlusPlus) {
12349     // C cannot handle TypoExpr nodes on either side of a binop because it
12350     // doesn't handle dependent types properly, so make sure any TypoExprs have
12351     // been dealt with before checking the operands.
12352     LHS = S.CorrectDelayedTyposInExpr(LHS);
12353     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12354       if (Opc != BO_Assign)
12355         return ExprResult(E);
12356       // Avoid correcting the RHS to the same Expr as the LHS.
12357       Decl *D = getDeclFromExpr(E);
12358       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12359     });
12360   }
12361   return std::make_pair(LHS, RHS);
12362 }
12363 
12364 /// Returns true if conversion between vectors of halfs and vectors of floats
12365 /// is needed.
12366 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12367                                      QualType SrcType) {
12368   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12369          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12370          isVector(SrcType, Ctx.HalfTy);
12371 }
12372 
12373 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12374 /// operator @p Opc at location @c TokLoc. This routine only supports
12375 /// built-in operations; ActOnBinOp handles overloaded operators.
12376 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12377                                     BinaryOperatorKind Opc,
12378                                     Expr *LHSExpr, Expr *RHSExpr) {
12379   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12380     // The syntax only allows initializer lists on the RHS of assignment,
12381     // so we don't need to worry about accepting invalid code for
12382     // non-assignment operators.
12383     // C++11 5.17p9:
12384     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12385     //   of x = {} is x = T().
12386     InitializationKind Kind = InitializationKind::CreateDirectList(
12387         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12388     InitializedEntity Entity =
12389         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12390     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12391     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12392     if (Init.isInvalid())
12393       return Init;
12394     RHSExpr = Init.get();
12395   }
12396 
12397   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12398   QualType ResultTy;     // Result type of the binary operator.
12399   // The following two variables are used for compound assignment operators
12400   QualType CompLHSTy;    // Type of LHS after promotions for computation
12401   QualType CompResultTy; // Type of computation result
12402   ExprValueKind VK = VK_RValue;
12403   ExprObjectKind OK = OK_Ordinary;
12404   bool ConvertHalfVec = false;
12405 
12406   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12407   if (!LHS.isUsable() || !RHS.isUsable())
12408     return ExprError();
12409 
12410   if (getLangOpts().OpenCL) {
12411     QualType LHSTy = LHSExpr->getType();
12412     QualType RHSTy = RHSExpr->getType();
12413     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12414     // the ATOMIC_VAR_INIT macro.
12415     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12416       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12417       if (BO_Assign == Opc)
12418         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12419       else
12420         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12421       return ExprError();
12422     }
12423 
12424     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12425     // only with a builtin functions and therefore should be disallowed here.
12426     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12427         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12428         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12429         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12430       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12431       return ExprError();
12432     }
12433   }
12434 
12435   switch (Opc) {
12436   case BO_Assign:
12437     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12438     if (getLangOpts().CPlusPlus &&
12439         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12440       VK = LHS.get()->getValueKind();
12441       OK = LHS.get()->getObjectKind();
12442     }
12443     if (!ResultTy.isNull()) {
12444       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12445       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12446     }
12447     RecordModifiableNonNullParam(*this, LHS.get());
12448     break;
12449   case BO_PtrMemD:
12450   case BO_PtrMemI:
12451     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12452                                             Opc == BO_PtrMemI);
12453     break;
12454   case BO_Mul:
12455   case BO_Div:
12456     ConvertHalfVec = true;
12457     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12458                                            Opc == BO_Div);
12459     break;
12460   case BO_Rem:
12461     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12462     break;
12463   case BO_Add:
12464     ConvertHalfVec = true;
12465     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12466     break;
12467   case BO_Sub:
12468     ConvertHalfVec = true;
12469     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12470     break;
12471   case BO_Shl:
12472   case BO_Shr:
12473     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12474     break;
12475   case BO_LE:
12476   case BO_LT:
12477   case BO_GE:
12478   case BO_GT:
12479     ConvertHalfVec = true;
12480     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12481     break;
12482   case BO_EQ:
12483   case BO_NE:
12484     ConvertHalfVec = true;
12485     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12486     break;
12487   case BO_Cmp:
12488     ConvertHalfVec = true;
12489     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12490     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12491     break;
12492   case BO_And:
12493     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12494     LLVM_FALLTHROUGH;
12495   case BO_Xor:
12496   case BO_Or:
12497     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12498     break;
12499   case BO_LAnd:
12500   case BO_LOr:
12501     ConvertHalfVec = true;
12502     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12503     break;
12504   case BO_MulAssign:
12505   case BO_DivAssign:
12506     ConvertHalfVec = true;
12507     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12508                                                Opc == BO_DivAssign);
12509     CompLHSTy = CompResultTy;
12510     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12511       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12512     break;
12513   case BO_RemAssign:
12514     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12515     CompLHSTy = CompResultTy;
12516     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12517       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12518     break;
12519   case BO_AddAssign:
12520     ConvertHalfVec = true;
12521     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12522     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12523       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12524     break;
12525   case BO_SubAssign:
12526     ConvertHalfVec = true;
12527     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12528     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12529       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12530     break;
12531   case BO_ShlAssign:
12532   case BO_ShrAssign:
12533     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12534     CompLHSTy = CompResultTy;
12535     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12536       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12537     break;
12538   case BO_AndAssign:
12539   case BO_OrAssign: // fallthrough
12540     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12541     LLVM_FALLTHROUGH;
12542   case BO_XorAssign:
12543     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12544     CompLHSTy = CompResultTy;
12545     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12546       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12547     break;
12548   case BO_Comma:
12549     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12550     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12551       VK = RHS.get()->getValueKind();
12552       OK = RHS.get()->getObjectKind();
12553     }
12554     break;
12555   }
12556   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12557     return ExprError();
12558 
12559   // Some of the binary operations require promoting operands of half vector to
12560   // float vectors and truncating the result back to half vector. For now, we do
12561   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12562   // arm64).
12563   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12564          isVector(LHS.get()->getType(), Context.HalfTy) &&
12565          "both sides are half vectors or neither sides are");
12566   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12567                                             LHS.get()->getType());
12568 
12569   // Check for array bounds violations for both sides of the BinaryOperator
12570   CheckArrayAccess(LHS.get());
12571   CheckArrayAccess(RHS.get());
12572 
12573   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12574     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12575                                                  &Context.Idents.get("object_setClass"),
12576                                                  SourceLocation(), LookupOrdinaryName);
12577     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12578       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12579       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12580           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12581                                         "object_setClass(")
12582           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12583                                           ",")
12584           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12585     }
12586     else
12587       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12588   }
12589   else if (const ObjCIvarRefExpr *OIRE =
12590            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12591     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12592 
12593   // Opc is not a compound assignment if CompResultTy is null.
12594   if (CompResultTy.isNull()) {
12595     if (ConvertHalfVec)
12596       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12597                                  OpLoc, FPFeatures);
12598     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12599                                         OK, OpLoc, FPFeatures);
12600   }
12601 
12602   // Handle compound assignments.
12603   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12604       OK_ObjCProperty) {
12605     VK = VK_LValue;
12606     OK = LHS.get()->getObjectKind();
12607   }
12608 
12609   if (ConvertHalfVec)
12610     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12611                                OpLoc, FPFeatures);
12612 
12613   return new (Context) CompoundAssignOperator(
12614       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12615       OpLoc, FPFeatures);
12616 }
12617 
12618 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12619 /// operators are mixed in a way that suggests that the programmer forgot that
12620 /// comparison operators have higher precedence. The most typical example of
12621 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12622 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12623                                       SourceLocation OpLoc, Expr *LHSExpr,
12624                                       Expr *RHSExpr) {
12625   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12626   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12627 
12628   // Check that one of the sides is a comparison operator and the other isn't.
12629   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12630   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12631   if (isLeftComp == isRightComp)
12632     return;
12633 
12634   // Bitwise operations are sometimes used as eager logical ops.
12635   // Don't diagnose this.
12636   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12637   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12638   if (isLeftBitwise || isRightBitwise)
12639     return;
12640 
12641   SourceRange DiagRange = isLeftComp
12642                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12643                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12644   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12645   SourceRange ParensRange =
12646       isLeftComp
12647           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12648           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12649 
12650   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12651     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12652   SuggestParentheses(Self, OpLoc,
12653     Self.PDiag(diag::note_precedence_silence) << OpStr,
12654     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12655   SuggestParentheses(Self, OpLoc,
12656     Self.PDiag(diag::note_precedence_bitwise_first)
12657       << BinaryOperator::getOpcodeStr(Opc),
12658     ParensRange);
12659 }
12660 
12661 /// It accepts a '&&' expr that is inside a '||' one.
12662 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12663 /// in parentheses.
12664 static void
12665 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12666                                        BinaryOperator *Bop) {
12667   assert(Bop->getOpcode() == BO_LAnd);
12668   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12669       << Bop->getSourceRange() << OpLoc;
12670   SuggestParentheses(Self, Bop->getOperatorLoc(),
12671     Self.PDiag(diag::note_precedence_silence)
12672       << Bop->getOpcodeStr(),
12673     Bop->getSourceRange());
12674 }
12675 
12676 /// Returns true if the given expression can be evaluated as a constant
12677 /// 'true'.
12678 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12679   bool Res;
12680   return !E->isValueDependent() &&
12681          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12682 }
12683 
12684 /// Returns true if the given expression can be evaluated as a constant
12685 /// 'false'.
12686 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12687   bool Res;
12688   return !E->isValueDependent() &&
12689          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12690 }
12691 
12692 /// Look for '&&' in the left hand of a '||' expr.
12693 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12694                                              Expr *LHSExpr, Expr *RHSExpr) {
12695   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12696     if (Bop->getOpcode() == BO_LAnd) {
12697       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12698       if (EvaluatesAsFalse(S, RHSExpr))
12699         return;
12700       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12701       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12702         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12703     } else if (Bop->getOpcode() == BO_LOr) {
12704       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12705         // If it's "a || b && 1 || c" we didn't warn earlier for
12706         // "a || b && 1", but warn now.
12707         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12708           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12709       }
12710     }
12711   }
12712 }
12713 
12714 /// Look for '&&' in the right hand of a '||' expr.
12715 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12716                                              Expr *LHSExpr, Expr *RHSExpr) {
12717   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12718     if (Bop->getOpcode() == BO_LAnd) {
12719       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12720       if (EvaluatesAsFalse(S, LHSExpr))
12721         return;
12722       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12723       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12724         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12725     }
12726   }
12727 }
12728 
12729 /// Look for bitwise op in the left or right hand of a bitwise op with
12730 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12731 /// the '&' expression in parentheses.
12732 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12733                                          SourceLocation OpLoc, Expr *SubExpr) {
12734   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12735     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12736       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12737         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12738         << Bop->getSourceRange() << OpLoc;
12739       SuggestParentheses(S, Bop->getOperatorLoc(),
12740         S.PDiag(diag::note_precedence_silence)
12741           << Bop->getOpcodeStr(),
12742         Bop->getSourceRange());
12743     }
12744   }
12745 }
12746 
12747 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12748                                     Expr *SubExpr, StringRef Shift) {
12749   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12750     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12751       StringRef Op = Bop->getOpcodeStr();
12752       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12753           << Bop->getSourceRange() << OpLoc << Shift << Op;
12754       SuggestParentheses(S, Bop->getOperatorLoc(),
12755           S.PDiag(diag::note_precedence_silence) << Op,
12756           Bop->getSourceRange());
12757     }
12758   }
12759 }
12760 
12761 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12762                                  Expr *LHSExpr, Expr *RHSExpr) {
12763   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12764   if (!OCE)
12765     return;
12766 
12767   FunctionDecl *FD = OCE->getDirectCallee();
12768   if (!FD || !FD->isOverloadedOperator())
12769     return;
12770 
12771   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12772   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12773     return;
12774 
12775   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12776       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12777       << (Kind == OO_LessLess);
12778   SuggestParentheses(S, OCE->getOperatorLoc(),
12779                      S.PDiag(diag::note_precedence_silence)
12780                          << (Kind == OO_LessLess ? "<<" : ">>"),
12781                      OCE->getSourceRange());
12782   SuggestParentheses(
12783       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12784       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12785 }
12786 
12787 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12788 /// precedence.
12789 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12790                                     SourceLocation OpLoc, Expr *LHSExpr,
12791                                     Expr *RHSExpr){
12792   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12793   if (BinaryOperator::isBitwiseOp(Opc))
12794     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12795 
12796   // Diagnose "arg1 & arg2 | arg3"
12797   if ((Opc == BO_Or || Opc == BO_Xor) &&
12798       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12799     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12800     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12801   }
12802 
12803   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12804   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12805   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12806     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12807     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12808   }
12809 
12810   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12811       || Opc == BO_Shr) {
12812     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12813     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12814     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12815   }
12816 
12817   // Warn on overloaded shift operators and comparisons, such as:
12818   // cout << 5 == 4;
12819   if (BinaryOperator::isComparisonOp(Opc))
12820     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12821 }
12822 
12823 // Binary Operators.  'Tok' is the token for the operator.
12824 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12825                             tok::TokenKind Kind,
12826                             Expr *LHSExpr, Expr *RHSExpr) {
12827   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12828   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12829   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12830 
12831   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12832   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12833 
12834   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12835 }
12836 
12837 /// Build an overloaded binary operator expression in the given scope.
12838 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12839                                        BinaryOperatorKind Opc,
12840                                        Expr *LHS, Expr *RHS) {
12841   switch (Opc) {
12842   case BO_Assign:
12843   case BO_DivAssign:
12844   case BO_RemAssign:
12845   case BO_SubAssign:
12846   case BO_AndAssign:
12847   case BO_OrAssign:
12848   case BO_XorAssign:
12849     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12850     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12851     break;
12852   default:
12853     break;
12854   }
12855 
12856   // Find all of the overloaded operators visible from this
12857   // point. We perform both an operator-name lookup from the local
12858   // scope and an argument-dependent lookup based on the types of
12859   // the arguments.
12860   UnresolvedSet<16> Functions;
12861   OverloadedOperatorKind OverOp
12862     = BinaryOperator::getOverloadedOperator(Opc);
12863   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12864     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12865                                    RHS->getType(), Functions);
12866 
12867   // Build the (potentially-overloaded, potentially-dependent)
12868   // binary operation.
12869   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12870 }
12871 
12872 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12873                             BinaryOperatorKind Opc,
12874                             Expr *LHSExpr, Expr *RHSExpr) {
12875   ExprResult LHS, RHS;
12876   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12877   if (!LHS.isUsable() || !RHS.isUsable())
12878     return ExprError();
12879   LHSExpr = LHS.get();
12880   RHSExpr = RHS.get();
12881 
12882   // We want to end up calling one of checkPseudoObjectAssignment
12883   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12884   // both expressions are overloadable or either is type-dependent),
12885   // or CreateBuiltinBinOp (in any other case).  We also want to get
12886   // any placeholder types out of the way.
12887 
12888   // Handle pseudo-objects in the LHS.
12889   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12890     // Assignments with a pseudo-object l-value need special analysis.
12891     if (pty->getKind() == BuiltinType::PseudoObject &&
12892         BinaryOperator::isAssignmentOp(Opc))
12893       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12894 
12895     // Don't resolve overloads if the other type is overloadable.
12896     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12897       // We can't actually test that if we still have a placeholder,
12898       // though.  Fortunately, none of the exceptions we see in that
12899       // code below are valid when the LHS is an overload set.  Note
12900       // that an overload set can be dependently-typed, but it never
12901       // instantiates to having an overloadable type.
12902       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12903       if (resolvedRHS.isInvalid()) return ExprError();
12904       RHSExpr = resolvedRHS.get();
12905 
12906       if (RHSExpr->isTypeDependent() ||
12907           RHSExpr->getType()->isOverloadableType())
12908         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12909     }
12910 
12911     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12912     // template, diagnose the missing 'template' keyword instead of diagnosing
12913     // an invalid use of a bound member function.
12914     //
12915     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12916     // to C++1z [over.over]/1.4, but we already checked for that case above.
12917     if (Opc == BO_LT && inTemplateInstantiation() &&
12918         (pty->getKind() == BuiltinType::BoundMember ||
12919          pty->getKind() == BuiltinType::Overload)) {
12920       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12921       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12922           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12923             return isa<FunctionTemplateDecl>(ND);
12924           })) {
12925         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12926                                 : OE->getNameLoc(),
12927              diag::err_template_kw_missing)
12928           << OE->getName().getAsString() << "";
12929         return ExprError();
12930       }
12931     }
12932 
12933     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12934     if (LHS.isInvalid()) return ExprError();
12935     LHSExpr = LHS.get();
12936   }
12937 
12938   // Handle pseudo-objects in the RHS.
12939   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12940     // An overload in the RHS can potentially be resolved by the type
12941     // being assigned to.
12942     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12943       if (getLangOpts().CPlusPlus &&
12944           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12945            LHSExpr->getType()->isOverloadableType()))
12946         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12947 
12948       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12949     }
12950 
12951     // Don't resolve overloads if the other type is overloadable.
12952     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12953         LHSExpr->getType()->isOverloadableType())
12954       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12955 
12956     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12957     if (!resolvedRHS.isUsable()) return ExprError();
12958     RHSExpr = resolvedRHS.get();
12959   }
12960 
12961   if (getLangOpts().CPlusPlus) {
12962     // If either expression is type-dependent, always build an
12963     // overloaded op.
12964     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12965       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12966 
12967     // Otherwise, build an overloaded op if either expression has an
12968     // overloadable type.
12969     if (LHSExpr->getType()->isOverloadableType() ||
12970         RHSExpr->getType()->isOverloadableType())
12971       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12972   }
12973 
12974   // Build a built-in binary operation.
12975   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12976 }
12977 
12978 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12979   if (T.isNull() || T->isDependentType())
12980     return false;
12981 
12982   if (!T->isPromotableIntegerType())
12983     return true;
12984 
12985   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12986 }
12987 
12988 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12989                                       UnaryOperatorKind Opc,
12990                                       Expr *InputExpr) {
12991   ExprResult Input = InputExpr;
12992   ExprValueKind VK = VK_RValue;
12993   ExprObjectKind OK = OK_Ordinary;
12994   QualType resultType;
12995   bool CanOverflow = false;
12996 
12997   bool ConvertHalfVec = false;
12998   if (getLangOpts().OpenCL) {
12999     QualType Ty = InputExpr->getType();
13000     // The only legal unary operation for atomics is '&'.
13001     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13002     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13003     // only with a builtin functions and therefore should be disallowed here.
13004         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13005         || Ty->isBlockPointerType())) {
13006       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13007                        << InputExpr->getType()
13008                        << Input.get()->getSourceRange());
13009     }
13010   }
13011   switch (Opc) {
13012   case UO_PreInc:
13013   case UO_PreDec:
13014   case UO_PostInc:
13015   case UO_PostDec:
13016     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13017                                                 OpLoc,
13018                                                 Opc == UO_PreInc ||
13019                                                 Opc == UO_PostInc,
13020                                                 Opc == UO_PreInc ||
13021                                                 Opc == UO_PreDec);
13022     CanOverflow = isOverflowingIntegerType(Context, resultType);
13023     break;
13024   case UO_AddrOf:
13025     resultType = CheckAddressOfOperand(Input, OpLoc);
13026     CheckAddressOfNoDeref(InputExpr);
13027     RecordModifiableNonNullParam(*this, InputExpr);
13028     break;
13029   case UO_Deref: {
13030     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13031     if (Input.isInvalid()) return ExprError();
13032     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13033     break;
13034   }
13035   case UO_Plus:
13036   case UO_Minus:
13037     CanOverflow = Opc == UO_Minus &&
13038                   isOverflowingIntegerType(Context, Input.get()->getType());
13039     Input = UsualUnaryConversions(Input.get());
13040     if (Input.isInvalid()) return ExprError();
13041     // Unary plus and minus require promoting an operand of half vector to a
13042     // float vector and truncating the result back to a half vector. For now, we
13043     // do this only when HalfArgsAndReturns is set (that is, when the target is
13044     // arm or arm64).
13045     ConvertHalfVec =
13046         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13047 
13048     // If the operand is a half vector, promote it to a float vector.
13049     if (ConvertHalfVec)
13050       Input = convertVector(Input.get(), Context.FloatTy, *this);
13051     resultType = Input.get()->getType();
13052     if (resultType->isDependentType())
13053       break;
13054     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13055       break;
13056     else if (resultType->isVectorType() &&
13057              // The z vector extensions don't allow + or - with bool vectors.
13058              (!Context.getLangOpts().ZVector ||
13059               resultType->getAs<VectorType>()->getVectorKind() !=
13060               VectorType::AltiVecBool))
13061       break;
13062     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13063              Opc == UO_Plus &&
13064              resultType->isPointerType())
13065       break;
13066 
13067     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13068       << resultType << Input.get()->getSourceRange());
13069 
13070   case UO_Not: // bitwise complement
13071     Input = UsualUnaryConversions(Input.get());
13072     if (Input.isInvalid())
13073       return ExprError();
13074     resultType = Input.get()->getType();
13075 
13076     if (resultType->isDependentType())
13077       break;
13078     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13079     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13080       // C99 does not support '~' for complex conjugation.
13081       Diag(OpLoc, diag::ext_integer_complement_complex)
13082           << resultType << Input.get()->getSourceRange();
13083     else if (resultType->hasIntegerRepresentation())
13084       break;
13085     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13086       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13087       // on vector float types.
13088       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13089       if (!T->isIntegerType())
13090         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13091                           << resultType << Input.get()->getSourceRange());
13092     } else {
13093       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13094                        << resultType << Input.get()->getSourceRange());
13095     }
13096     break;
13097 
13098   case UO_LNot: // logical negation
13099     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13100     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13101     if (Input.isInvalid()) return ExprError();
13102     resultType = Input.get()->getType();
13103 
13104     // Though we still have to promote half FP to float...
13105     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13106       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13107       resultType = Context.FloatTy;
13108     }
13109 
13110     if (resultType->isDependentType())
13111       break;
13112     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13113       // C99 6.5.3.3p1: ok, fallthrough;
13114       if (Context.getLangOpts().CPlusPlus) {
13115         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13116         // operand contextually converted to bool.
13117         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13118                                   ScalarTypeToBooleanCastKind(resultType));
13119       } else if (Context.getLangOpts().OpenCL &&
13120                  Context.getLangOpts().OpenCLVersion < 120) {
13121         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13122         // operate on scalar float types.
13123         if (!resultType->isIntegerType() && !resultType->isPointerType())
13124           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13125                            << resultType << Input.get()->getSourceRange());
13126       }
13127     } else if (resultType->isExtVectorType()) {
13128       if (Context.getLangOpts().OpenCL &&
13129           Context.getLangOpts().OpenCLVersion < 120) {
13130         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13131         // operate on vector float types.
13132         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13133         if (!T->isIntegerType())
13134           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13135                            << resultType << Input.get()->getSourceRange());
13136       }
13137       // Vector logical not returns the signed variant of the operand type.
13138       resultType = GetSignedVectorType(resultType);
13139       break;
13140     } else {
13141       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13142       //        type in C++. We should allow that here too.
13143       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13144         << resultType << Input.get()->getSourceRange());
13145     }
13146 
13147     // LNot always has type int. C99 6.5.3.3p5.
13148     // In C++, it's bool. C++ 5.3.1p8
13149     resultType = Context.getLogicalOperationType();
13150     break;
13151   case UO_Real:
13152   case UO_Imag:
13153     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13154     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13155     // complex l-values to ordinary l-values and all other values to r-values.
13156     if (Input.isInvalid()) return ExprError();
13157     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13158       if (Input.get()->getValueKind() != VK_RValue &&
13159           Input.get()->getObjectKind() == OK_Ordinary)
13160         VK = Input.get()->getValueKind();
13161     } else if (!getLangOpts().CPlusPlus) {
13162       // In C, a volatile scalar is read by __imag. In C++, it is not.
13163       Input = DefaultLvalueConversion(Input.get());
13164     }
13165     break;
13166   case UO_Extension:
13167     resultType = Input.get()->getType();
13168     VK = Input.get()->getValueKind();
13169     OK = Input.get()->getObjectKind();
13170     break;
13171   case UO_Coawait:
13172     // It's unnecessary to represent the pass-through operator co_await in the
13173     // AST; just return the input expression instead.
13174     assert(!Input.get()->getType()->isDependentType() &&
13175                    "the co_await expression must be non-dependant before "
13176                    "building operator co_await");
13177     return Input;
13178   }
13179   if (resultType.isNull() || Input.isInvalid())
13180     return ExprError();
13181 
13182   // Check for array bounds violations in the operand of the UnaryOperator,
13183   // except for the '*' and '&' operators that have to be handled specially
13184   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13185   // that are explicitly defined as valid by the standard).
13186   if (Opc != UO_AddrOf && Opc != UO_Deref)
13187     CheckArrayAccess(Input.get());
13188 
13189   auto *UO = new (Context)
13190       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13191 
13192   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13193       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13194     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13195 
13196   // Convert the result back to a half vector.
13197   if (ConvertHalfVec)
13198     return convertVector(UO, Context.HalfTy, *this);
13199   return UO;
13200 }
13201 
13202 /// Determine whether the given expression is a qualified member
13203 /// access expression, of a form that could be turned into a pointer to member
13204 /// with the address-of operator.
13205 bool Sema::isQualifiedMemberAccess(Expr *E) {
13206   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13207     if (!DRE->getQualifier())
13208       return false;
13209 
13210     ValueDecl *VD = DRE->getDecl();
13211     if (!VD->isCXXClassMember())
13212       return false;
13213 
13214     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13215       return true;
13216     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13217       return Method->isInstance();
13218 
13219     return false;
13220   }
13221 
13222   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13223     if (!ULE->getQualifier())
13224       return false;
13225 
13226     for (NamedDecl *D : ULE->decls()) {
13227       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13228         if (Method->isInstance())
13229           return true;
13230       } else {
13231         // Overload set does not contain methods.
13232         break;
13233       }
13234     }
13235 
13236     return false;
13237   }
13238 
13239   return false;
13240 }
13241 
13242 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13243                               UnaryOperatorKind Opc, Expr *Input) {
13244   // First things first: handle placeholders so that the
13245   // overloaded-operator check considers the right type.
13246   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13247     // Increment and decrement of pseudo-object references.
13248     if (pty->getKind() == BuiltinType::PseudoObject &&
13249         UnaryOperator::isIncrementDecrementOp(Opc))
13250       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13251 
13252     // extension is always a builtin operator.
13253     if (Opc == UO_Extension)
13254       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13255 
13256     // & gets special logic for several kinds of placeholder.
13257     // The builtin code knows what to do.
13258     if (Opc == UO_AddrOf &&
13259         (pty->getKind() == BuiltinType::Overload ||
13260          pty->getKind() == BuiltinType::UnknownAny ||
13261          pty->getKind() == BuiltinType::BoundMember))
13262       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13263 
13264     // Anything else needs to be handled now.
13265     ExprResult Result = CheckPlaceholderExpr(Input);
13266     if (Result.isInvalid()) return ExprError();
13267     Input = Result.get();
13268   }
13269 
13270   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13271       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13272       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13273     // Find all of the overloaded operators visible from this
13274     // point. We perform both an operator-name lookup from the local
13275     // scope and an argument-dependent lookup based on the types of
13276     // the arguments.
13277     UnresolvedSet<16> Functions;
13278     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13279     if (S && OverOp != OO_None)
13280       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13281                                    Functions);
13282 
13283     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13284   }
13285 
13286   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13287 }
13288 
13289 // Unary Operators.  'Tok' is the token for the operator.
13290 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13291                               tok::TokenKind Op, Expr *Input) {
13292   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13293 }
13294 
13295 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13296 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13297                                 LabelDecl *TheDecl) {
13298   TheDecl->markUsed(Context);
13299   // Create the AST node.  The address of a label always has type 'void*'.
13300   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13301                                      Context.getPointerType(Context.VoidTy));
13302 }
13303 
13304 void Sema::ActOnStartStmtExpr() {
13305   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13306 }
13307 
13308 void Sema::ActOnStmtExprError() {
13309   // Note that function is also called by TreeTransform when leaving a
13310   // StmtExpr scope without rebuilding anything.
13311 
13312   DiscardCleanupsInEvaluationContext();
13313   PopExpressionEvaluationContext();
13314 }
13315 
13316 ExprResult
13317 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13318                     SourceLocation RPLoc) { // "({..})"
13319   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13320   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13321 
13322   if (hasAnyUnrecoverableErrorsInThisFunction())
13323     DiscardCleanupsInEvaluationContext();
13324   assert(!Cleanup.exprNeedsCleanups() &&
13325          "cleanups within StmtExpr not correctly bound!");
13326   PopExpressionEvaluationContext();
13327 
13328   // FIXME: there are a variety of strange constraints to enforce here, for
13329   // example, it is not possible to goto into a stmt expression apparently.
13330   // More semantic analysis is needed.
13331 
13332   // If there are sub-stmts in the compound stmt, take the type of the last one
13333   // as the type of the stmtexpr.
13334   QualType Ty = Context.VoidTy;
13335   bool StmtExprMayBindToTemp = false;
13336   if (!Compound->body_empty()) {
13337     if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
13338       if (const Expr *Value = LastStmt->getExprStmt()) {
13339         StmtExprMayBindToTemp = true;
13340         Ty = Value->getType();
13341       }
13342     }
13343   }
13344 
13345   // FIXME: Check that expression type is complete/non-abstract; statement
13346   // expressions are not lvalues.
13347   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13348   if (StmtExprMayBindToTemp)
13349     return MaybeBindToTemporary(ResStmtExpr);
13350   return ResStmtExpr;
13351 }
13352 
13353 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13354   if (ER.isInvalid())
13355     return ExprError();
13356 
13357   // Do function/array conversion on the last expression, but not
13358   // lvalue-to-rvalue.  However, initialize an unqualified type.
13359   ER = DefaultFunctionArrayConversion(ER.get());
13360   if (ER.isInvalid())
13361     return ExprError();
13362   Expr *E = ER.get();
13363 
13364   if (E->isTypeDependent())
13365     return E;
13366 
13367   // In ARC, if the final expression ends in a consume, splice
13368   // the consume out and bind it later.  In the alternate case
13369   // (when dealing with a retainable type), the result
13370   // initialization will create a produce.  In both cases the
13371   // result will be +1, and we'll need to balance that out with
13372   // a bind.
13373   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13374   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13375     return Cast->getSubExpr();
13376 
13377   // FIXME: Provide a better location for the initialization.
13378   return PerformCopyInitialization(
13379       InitializedEntity::InitializeStmtExprResult(
13380           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13381       SourceLocation(), E);
13382 }
13383 
13384 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13385                                       TypeSourceInfo *TInfo,
13386                                       ArrayRef<OffsetOfComponent> Components,
13387                                       SourceLocation RParenLoc) {
13388   QualType ArgTy = TInfo->getType();
13389   bool Dependent = ArgTy->isDependentType();
13390   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13391 
13392   // We must have at least one component that refers to the type, and the first
13393   // one is known to be a field designator.  Verify that the ArgTy represents
13394   // a struct/union/class.
13395   if (!Dependent && !ArgTy->isRecordType())
13396     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13397                        << ArgTy << TypeRange);
13398 
13399   // Type must be complete per C99 7.17p3 because a declaring a variable
13400   // with an incomplete type would be ill-formed.
13401   if (!Dependent
13402       && RequireCompleteType(BuiltinLoc, ArgTy,
13403                              diag::err_offsetof_incomplete_type, TypeRange))
13404     return ExprError();
13405 
13406   bool DidWarnAboutNonPOD = false;
13407   QualType CurrentType = ArgTy;
13408   SmallVector<OffsetOfNode, 4> Comps;
13409   SmallVector<Expr*, 4> Exprs;
13410   for (const OffsetOfComponent &OC : Components) {
13411     if (OC.isBrackets) {
13412       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13413       if (!CurrentType->isDependentType()) {
13414         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13415         if(!AT)
13416           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13417                            << CurrentType);
13418         CurrentType = AT->getElementType();
13419       } else
13420         CurrentType = Context.DependentTy;
13421 
13422       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13423       if (IdxRval.isInvalid())
13424         return ExprError();
13425       Expr *Idx = IdxRval.get();
13426 
13427       // The expression must be an integral expression.
13428       // FIXME: An integral constant expression?
13429       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13430           !Idx->getType()->isIntegerType())
13431         return ExprError(
13432             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13433             << Idx->getSourceRange());
13434 
13435       // Record this array index.
13436       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13437       Exprs.push_back(Idx);
13438       continue;
13439     }
13440 
13441     // Offset of a field.
13442     if (CurrentType->isDependentType()) {
13443       // We have the offset of a field, but we can't look into the dependent
13444       // type. Just record the identifier of the field.
13445       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13446       CurrentType = Context.DependentTy;
13447       continue;
13448     }
13449 
13450     // We need to have a complete type to look into.
13451     if (RequireCompleteType(OC.LocStart, CurrentType,
13452                             diag::err_offsetof_incomplete_type))
13453       return ExprError();
13454 
13455     // Look for the designated field.
13456     const RecordType *RC = CurrentType->getAs<RecordType>();
13457     if (!RC)
13458       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13459                        << CurrentType);
13460     RecordDecl *RD = RC->getDecl();
13461 
13462     // C++ [lib.support.types]p5:
13463     //   The macro offsetof accepts a restricted set of type arguments in this
13464     //   International Standard. type shall be a POD structure or a POD union
13465     //   (clause 9).
13466     // C++11 [support.types]p4:
13467     //   If type is not a standard-layout class (Clause 9), the results are
13468     //   undefined.
13469     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13470       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13471       unsigned DiagID =
13472         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13473                             : diag::ext_offsetof_non_pod_type;
13474 
13475       if (!IsSafe && !DidWarnAboutNonPOD &&
13476           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13477                               PDiag(DiagID)
13478                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13479                               << CurrentType))
13480         DidWarnAboutNonPOD = true;
13481     }
13482 
13483     // Look for the field.
13484     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13485     LookupQualifiedName(R, RD);
13486     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13487     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13488     if (!MemberDecl) {
13489       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13490         MemberDecl = IndirectMemberDecl->getAnonField();
13491     }
13492 
13493     if (!MemberDecl)
13494       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13495                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13496                                                               OC.LocEnd));
13497 
13498     // C99 7.17p3:
13499     //   (If the specified member is a bit-field, the behavior is undefined.)
13500     //
13501     // We diagnose this as an error.
13502     if (MemberDecl->isBitField()) {
13503       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13504         << MemberDecl->getDeclName()
13505         << SourceRange(BuiltinLoc, RParenLoc);
13506       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13507       return ExprError();
13508     }
13509 
13510     RecordDecl *Parent = MemberDecl->getParent();
13511     if (IndirectMemberDecl)
13512       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13513 
13514     // If the member was found in a base class, introduce OffsetOfNodes for
13515     // the base class indirections.
13516     CXXBasePaths Paths;
13517     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13518                       Paths)) {
13519       if (Paths.getDetectedVirtual()) {
13520         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13521           << MemberDecl->getDeclName()
13522           << SourceRange(BuiltinLoc, RParenLoc);
13523         return ExprError();
13524       }
13525 
13526       CXXBasePath &Path = Paths.front();
13527       for (const CXXBasePathElement &B : Path)
13528         Comps.push_back(OffsetOfNode(B.Base));
13529     }
13530 
13531     if (IndirectMemberDecl) {
13532       for (auto *FI : IndirectMemberDecl->chain()) {
13533         assert(isa<FieldDecl>(FI));
13534         Comps.push_back(OffsetOfNode(OC.LocStart,
13535                                      cast<FieldDecl>(FI), OC.LocEnd));
13536       }
13537     } else
13538       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13539 
13540     CurrentType = MemberDecl->getType().getNonReferenceType();
13541   }
13542 
13543   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13544                               Comps, Exprs, RParenLoc);
13545 }
13546 
13547 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13548                                       SourceLocation BuiltinLoc,
13549                                       SourceLocation TypeLoc,
13550                                       ParsedType ParsedArgTy,
13551                                       ArrayRef<OffsetOfComponent> Components,
13552                                       SourceLocation RParenLoc) {
13553 
13554   TypeSourceInfo *ArgTInfo;
13555   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13556   if (ArgTy.isNull())
13557     return ExprError();
13558 
13559   if (!ArgTInfo)
13560     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13561 
13562   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13563 }
13564 
13565 
13566 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13567                                  Expr *CondExpr,
13568                                  Expr *LHSExpr, Expr *RHSExpr,
13569                                  SourceLocation RPLoc) {
13570   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13571 
13572   ExprValueKind VK = VK_RValue;
13573   ExprObjectKind OK = OK_Ordinary;
13574   QualType resType;
13575   bool ValueDependent = false;
13576   bool CondIsTrue = false;
13577   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13578     resType = Context.DependentTy;
13579     ValueDependent = true;
13580   } else {
13581     // The conditional expression is required to be a constant expression.
13582     llvm::APSInt condEval(32);
13583     ExprResult CondICE
13584       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13585           diag::err_typecheck_choose_expr_requires_constant, false);
13586     if (CondICE.isInvalid())
13587       return ExprError();
13588     CondExpr = CondICE.get();
13589     CondIsTrue = condEval.getZExtValue();
13590 
13591     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13592     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13593 
13594     resType = ActiveExpr->getType();
13595     ValueDependent = ActiveExpr->isValueDependent();
13596     VK = ActiveExpr->getValueKind();
13597     OK = ActiveExpr->getObjectKind();
13598   }
13599 
13600   return new (Context)
13601       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13602                  CondIsTrue, resType->isDependentType(), ValueDependent);
13603 }
13604 
13605 //===----------------------------------------------------------------------===//
13606 // Clang Extensions.
13607 //===----------------------------------------------------------------------===//
13608 
13609 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13610 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13611   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13612 
13613   if (LangOpts.CPlusPlus) {
13614     Decl *ManglingContextDecl;
13615     if (MangleNumberingContext *MCtx =
13616             getCurrentMangleNumberContext(Block->getDeclContext(),
13617                                           ManglingContextDecl)) {
13618       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13619       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13620     }
13621   }
13622 
13623   PushBlockScope(CurScope, Block);
13624   CurContext->addDecl(Block);
13625   if (CurScope)
13626     PushDeclContext(CurScope, Block);
13627   else
13628     CurContext = Block;
13629 
13630   getCurBlock()->HasImplicitReturnType = true;
13631 
13632   // Enter a new evaluation context to insulate the block from any
13633   // cleanups from the enclosing full-expression.
13634   PushExpressionEvaluationContext(
13635       ExpressionEvaluationContext::PotentiallyEvaluated);
13636 }
13637 
13638 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13639                                Scope *CurScope) {
13640   assert(ParamInfo.getIdentifier() == nullptr &&
13641          "block-id should have no identifier!");
13642   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13643   BlockScopeInfo *CurBlock = getCurBlock();
13644 
13645   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13646   QualType T = Sig->getType();
13647 
13648   // FIXME: We should allow unexpanded parameter packs here, but that would,
13649   // in turn, make the block expression contain unexpanded parameter packs.
13650   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13651     // Drop the parameters.
13652     FunctionProtoType::ExtProtoInfo EPI;
13653     EPI.HasTrailingReturn = false;
13654     EPI.TypeQuals.addConst();
13655     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13656     Sig = Context.getTrivialTypeSourceInfo(T);
13657   }
13658 
13659   // GetTypeForDeclarator always produces a function type for a block
13660   // literal signature.  Furthermore, it is always a FunctionProtoType
13661   // unless the function was written with a typedef.
13662   assert(T->isFunctionType() &&
13663          "GetTypeForDeclarator made a non-function block signature");
13664 
13665   // Look for an explicit signature in that function type.
13666   FunctionProtoTypeLoc ExplicitSignature;
13667 
13668   if ((ExplicitSignature =
13669            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13670 
13671     // Check whether that explicit signature was synthesized by
13672     // GetTypeForDeclarator.  If so, don't save that as part of the
13673     // written signature.
13674     if (ExplicitSignature.getLocalRangeBegin() ==
13675         ExplicitSignature.getLocalRangeEnd()) {
13676       // This would be much cheaper if we stored TypeLocs instead of
13677       // TypeSourceInfos.
13678       TypeLoc Result = ExplicitSignature.getReturnLoc();
13679       unsigned Size = Result.getFullDataSize();
13680       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13681       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13682 
13683       ExplicitSignature = FunctionProtoTypeLoc();
13684     }
13685   }
13686 
13687   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13688   CurBlock->FunctionType = T;
13689 
13690   const FunctionType *Fn = T->getAs<FunctionType>();
13691   QualType RetTy = Fn->getReturnType();
13692   bool isVariadic =
13693     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13694 
13695   CurBlock->TheDecl->setIsVariadic(isVariadic);
13696 
13697   // Context.DependentTy is used as a placeholder for a missing block
13698   // return type.  TODO:  what should we do with declarators like:
13699   //   ^ * { ... }
13700   // If the answer is "apply template argument deduction"....
13701   if (RetTy != Context.DependentTy) {
13702     CurBlock->ReturnType = RetTy;
13703     CurBlock->TheDecl->setBlockMissingReturnType(false);
13704     CurBlock->HasImplicitReturnType = false;
13705   }
13706 
13707   // Push block parameters from the declarator if we had them.
13708   SmallVector<ParmVarDecl*, 8> Params;
13709   if (ExplicitSignature) {
13710     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13711       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13712       if (Param->getIdentifier() == nullptr &&
13713           !Param->isImplicit() &&
13714           !Param->isInvalidDecl() &&
13715           !getLangOpts().CPlusPlus)
13716         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13717       Params.push_back(Param);
13718     }
13719 
13720   // Fake up parameter variables if we have a typedef, like
13721   //   ^ fntype { ... }
13722   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13723     for (const auto &I : Fn->param_types()) {
13724       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13725           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13726       Params.push_back(Param);
13727     }
13728   }
13729 
13730   // Set the parameters on the block decl.
13731   if (!Params.empty()) {
13732     CurBlock->TheDecl->setParams(Params);
13733     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13734                              /*CheckParameterNames=*/false);
13735   }
13736 
13737   // Finally we can process decl attributes.
13738   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13739 
13740   // Put the parameter variables in scope.
13741   for (auto AI : CurBlock->TheDecl->parameters()) {
13742     AI->setOwningFunction(CurBlock->TheDecl);
13743 
13744     // If this has an identifier, add it to the scope stack.
13745     if (AI->getIdentifier()) {
13746       CheckShadow(CurBlock->TheScope, AI);
13747 
13748       PushOnScopeChains(AI, CurBlock->TheScope);
13749     }
13750   }
13751 }
13752 
13753 /// ActOnBlockError - If there is an error parsing a block, this callback
13754 /// is invoked to pop the information about the block from the action impl.
13755 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13756   // Leave the expression-evaluation context.
13757   DiscardCleanupsInEvaluationContext();
13758   PopExpressionEvaluationContext();
13759 
13760   // Pop off CurBlock, handle nested blocks.
13761   PopDeclContext();
13762   PopFunctionScopeInfo();
13763 }
13764 
13765 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13766 /// literal was successfully completed.  ^(int x){...}
13767 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13768                                     Stmt *Body, Scope *CurScope) {
13769   // If blocks are disabled, emit an error.
13770   if (!LangOpts.Blocks)
13771     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13772 
13773   // Leave the expression-evaluation context.
13774   if (hasAnyUnrecoverableErrorsInThisFunction())
13775     DiscardCleanupsInEvaluationContext();
13776   assert(!Cleanup.exprNeedsCleanups() &&
13777          "cleanups within block not correctly bound!");
13778   PopExpressionEvaluationContext();
13779 
13780   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13781   BlockDecl *BD = BSI->TheDecl;
13782 
13783   if (BSI->HasImplicitReturnType)
13784     deduceClosureReturnType(*BSI);
13785 
13786   PopDeclContext();
13787 
13788   QualType RetTy = Context.VoidTy;
13789   if (!BSI->ReturnType.isNull())
13790     RetTy = BSI->ReturnType;
13791 
13792   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13793   QualType BlockTy;
13794 
13795   // Set the captured variables on the block.
13796   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13797   SmallVector<BlockDecl::Capture, 4> Captures;
13798   for (Capture &Cap : BSI->Captures) {
13799     if (Cap.isThisCapture())
13800       continue;
13801     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13802                               Cap.isNested(), Cap.getInitExpr());
13803     Captures.push_back(NewCap);
13804   }
13805   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13806 
13807   // If the user wrote a function type in some form, try to use that.
13808   if (!BSI->FunctionType.isNull()) {
13809     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13810 
13811     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13812     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13813 
13814     // Turn protoless block types into nullary block types.
13815     if (isa<FunctionNoProtoType>(FTy)) {
13816       FunctionProtoType::ExtProtoInfo EPI;
13817       EPI.ExtInfo = Ext;
13818       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13819 
13820     // Otherwise, if we don't need to change anything about the function type,
13821     // preserve its sugar structure.
13822     } else if (FTy->getReturnType() == RetTy &&
13823                (!NoReturn || FTy->getNoReturnAttr())) {
13824       BlockTy = BSI->FunctionType;
13825 
13826     // Otherwise, make the minimal modifications to the function type.
13827     } else {
13828       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13829       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13830       EPI.TypeQuals = Qualifiers();
13831       EPI.ExtInfo = Ext;
13832       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13833     }
13834 
13835   // If we don't have a function type, just build one from nothing.
13836   } else {
13837     FunctionProtoType::ExtProtoInfo EPI;
13838     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13839     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13840   }
13841 
13842   DiagnoseUnusedParameters(BD->parameters());
13843   BlockTy = Context.getBlockPointerType(BlockTy);
13844 
13845   // If needed, diagnose invalid gotos and switches in the block.
13846   if (getCurFunction()->NeedsScopeChecking() &&
13847       !PP.isCodeCompletionEnabled())
13848     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13849 
13850   BD->setBody(cast<CompoundStmt>(Body));
13851 
13852   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13853     DiagnoseUnguardedAvailabilityViolations(BD);
13854 
13855   // Try to apply the named return value optimization. We have to check again
13856   // if we can do this, though, because blocks keep return statements around
13857   // to deduce an implicit return type.
13858   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13859       !BD->isDependentContext())
13860     computeNRVO(Body, BSI);
13861 
13862   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13863   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13864   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13865 
13866   // If the block isn't obviously global, i.e. it captures anything at
13867   // all, then we need to do a few things in the surrounding context:
13868   if (Result->getBlockDecl()->hasCaptures()) {
13869     // First, this expression has a new cleanup object.
13870     ExprCleanupObjects.push_back(Result->getBlockDecl());
13871     Cleanup.setExprNeedsCleanups(true);
13872 
13873     // It also gets a branch-protected scope if any of the captured
13874     // variables needs destruction.
13875     for (const auto &CI : Result->getBlockDecl()->captures()) {
13876       const VarDecl *var = CI.getVariable();
13877       if (var->getType().isDestructedType() != QualType::DK_none) {
13878         setFunctionHasBranchProtectedScope();
13879         break;
13880       }
13881     }
13882   }
13883 
13884   if (getCurFunction())
13885     getCurFunction()->addBlock(BD);
13886 
13887   return Result;
13888 }
13889 
13890 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13891                             SourceLocation RPLoc) {
13892   TypeSourceInfo *TInfo;
13893   GetTypeFromParser(Ty, &TInfo);
13894   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13895 }
13896 
13897 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13898                                 Expr *E, TypeSourceInfo *TInfo,
13899                                 SourceLocation RPLoc) {
13900   Expr *OrigExpr = E;
13901   bool IsMS = false;
13902 
13903   // CUDA device code does not support varargs.
13904   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13905     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13906       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13907       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13908         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13909     }
13910   }
13911 
13912   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13913   // as Microsoft ABI on an actual Microsoft platform, where
13914   // __builtin_ms_va_list and __builtin_va_list are the same.)
13915   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13916       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13917     QualType MSVaListType = Context.getBuiltinMSVaListType();
13918     if (Context.hasSameType(MSVaListType, E->getType())) {
13919       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13920         return ExprError();
13921       IsMS = true;
13922     }
13923   }
13924 
13925   // Get the va_list type
13926   QualType VaListType = Context.getBuiltinVaListType();
13927   if (!IsMS) {
13928     if (VaListType->isArrayType()) {
13929       // Deal with implicit array decay; for example, on x86-64,
13930       // va_list is an array, but it's supposed to decay to
13931       // a pointer for va_arg.
13932       VaListType = Context.getArrayDecayedType(VaListType);
13933       // Make sure the input expression also decays appropriately.
13934       ExprResult Result = UsualUnaryConversions(E);
13935       if (Result.isInvalid())
13936         return ExprError();
13937       E = Result.get();
13938     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13939       // If va_list is a record type and we are compiling in C++ mode,
13940       // check the argument using reference binding.
13941       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13942           Context, Context.getLValueReferenceType(VaListType), false);
13943       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13944       if (Init.isInvalid())
13945         return ExprError();
13946       E = Init.getAs<Expr>();
13947     } else {
13948       // Otherwise, the va_list argument must be an l-value because
13949       // it is modified by va_arg.
13950       if (!E->isTypeDependent() &&
13951           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13952         return ExprError();
13953     }
13954   }
13955 
13956   if (!IsMS && !E->isTypeDependent() &&
13957       !Context.hasSameType(VaListType, E->getType()))
13958     return ExprError(
13959         Diag(E->getBeginLoc(),
13960              diag::err_first_argument_to_va_arg_not_of_type_va_list)
13961         << OrigExpr->getType() << E->getSourceRange());
13962 
13963   if (!TInfo->getType()->isDependentType()) {
13964     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13965                             diag::err_second_parameter_to_va_arg_incomplete,
13966                             TInfo->getTypeLoc()))
13967       return ExprError();
13968 
13969     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13970                                TInfo->getType(),
13971                                diag::err_second_parameter_to_va_arg_abstract,
13972                                TInfo->getTypeLoc()))
13973       return ExprError();
13974 
13975     if (!TInfo->getType().isPODType(Context)) {
13976       Diag(TInfo->getTypeLoc().getBeginLoc(),
13977            TInfo->getType()->isObjCLifetimeType()
13978              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13979              : diag::warn_second_parameter_to_va_arg_not_pod)
13980         << TInfo->getType()
13981         << TInfo->getTypeLoc().getSourceRange();
13982     }
13983 
13984     // Check for va_arg where arguments of the given type will be promoted
13985     // (i.e. this va_arg is guaranteed to have undefined behavior).
13986     QualType PromoteType;
13987     if (TInfo->getType()->isPromotableIntegerType()) {
13988       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13989       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13990         PromoteType = QualType();
13991     }
13992     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13993       PromoteType = Context.DoubleTy;
13994     if (!PromoteType.isNull())
13995       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13996                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13997                           << TInfo->getType()
13998                           << PromoteType
13999                           << TInfo->getTypeLoc().getSourceRange());
14000   }
14001 
14002   QualType T = TInfo->getType().getNonLValueExprType(Context);
14003   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14004 }
14005 
14006 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14007   // The type of __null will be int or long, depending on the size of
14008   // pointers on the target.
14009   QualType Ty;
14010   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14011   if (pw == Context.getTargetInfo().getIntWidth())
14012     Ty = Context.IntTy;
14013   else if (pw == Context.getTargetInfo().getLongWidth())
14014     Ty = Context.LongTy;
14015   else if (pw == Context.getTargetInfo().getLongLongWidth())
14016     Ty = Context.LongLongTy;
14017   else {
14018     llvm_unreachable("I don't know size of pointer!");
14019   }
14020 
14021   return new (Context) GNUNullExpr(Ty, TokenLoc);
14022 }
14023 
14024 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14025                                               bool Diagnose) {
14026   if (!getLangOpts().ObjC)
14027     return false;
14028 
14029   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14030   if (!PT)
14031     return false;
14032 
14033   if (!PT->isObjCIdType()) {
14034     // Check if the destination is the 'NSString' interface.
14035     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14036     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14037       return false;
14038   }
14039 
14040   // Ignore any parens, implicit casts (should only be
14041   // array-to-pointer decays), and not-so-opaque values.  The last is
14042   // important for making this trigger for property assignments.
14043   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14044   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14045     if (OV->getSourceExpr())
14046       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14047 
14048   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14049   if (!SL || !SL->isAscii())
14050     return false;
14051   if (Diagnose) {
14052     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14053         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14054     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14055   }
14056   return true;
14057 }
14058 
14059 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14060                                               const Expr *SrcExpr) {
14061   if (!DstType->isFunctionPointerType() ||
14062       !SrcExpr->getType()->isFunctionType())
14063     return false;
14064 
14065   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14066   if (!DRE)
14067     return false;
14068 
14069   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14070   if (!FD)
14071     return false;
14072 
14073   return !S.checkAddressOfFunctionIsAvailable(FD,
14074                                               /*Complain=*/true,
14075                                               SrcExpr->getBeginLoc());
14076 }
14077 
14078 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14079                                     SourceLocation Loc,
14080                                     QualType DstType, QualType SrcType,
14081                                     Expr *SrcExpr, AssignmentAction Action,
14082                                     bool *Complained) {
14083   if (Complained)
14084     *Complained = false;
14085 
14086   // Decode the result (notice that AST's are still created for extensions).
14087   bool CheckInferredResultType = false;
14088   bool isInvalid = false;
14089   unsigned DiagKind = 0;
14090   FixItHint Hint;
14091   ConversionFixItGenerator ConvHints;
14092   bool MayHaveConvFixit = false;
14093   bool MayHaveFunctionDiff = false;
14094   const ObjCInterfaceDecl *IFace = nullptr;
14095   const ObjCProtocolDecl *PDecl = nullptr;
14096 
14097   switch (ConvTy) {
14098   case Compatible:
14099       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14100       return false;
14101 
14102   case PointerToInt:
14103     DiagKind = diag::ext_typecheck_convert_pointer_int;
14104     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14105     MayHaveConvFixit = true;
14106     break;
14107   case IntToPointer:
14108     DiagKind = diag::ext_typecheck_convert_int_pointer;
14109     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14110     MayHaveConvFixit = true;
14111     break;
14112   case IncompatiblePointer:
14113     if (Action == AA_Passing_CFAudited)
14114       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14115     else if (SrcType->isFunctionPointerType() &&
14116              DstType->isFunctionPointerType())
14117       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14118     else
14119       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14120 
14121     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14122       SrcType->isObjCObjectPointerType();
14123     if (Hint.isNull() && !CheckInferredResultType) {
14124       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14125     }
14126     else if (CheckInferredResultType) {
14127       SrcType = SrcType.getUnqualifiedType();
14128       DstType = DstType.getUnqualifiedType();
14129     }
14130     MayHaveConvFixit = true;
14131     break;
14132   case IncompatiblePointerSign:
14133     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14134     break;
14135   case FunctionVoidPointer:
14136     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14137     break;
14138   case IncompatiblePointerDiscardsQualifiers: {
14139     // Perform array-to-pointer decay if necessary.
14140     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14141 
14142     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14143     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14144     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14145       DiagKind = diag::err_typecheck_incompatible_address_space;
14146       break;
14147 
14148     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14149       DiagKind = diag::err_typecheck_incompatible_ownership;
14150       break;
14151     }
14152 
14153     llvm_unreachable("unknown error case for discarding qualifiers!");
14154     // fallthrough
14155   }
14156   case CompatiblePointerDiscardsQualifiers:
14157     // If the qualifiers lost were because we were applying the
14158     // (deprecated) C++ conversion from a string literal to a char*
14159     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14160     // Ideally, this check would be performed in
14161     // checkPointerTypesForAssignment. However, that would require a
14162     // bit of refactoring (so that the second argument is an
14163     // expression, rather than a type), which should be done as part
14164     // of a larger effort to fix checkPointerTypesForAssignment for
14165     // C++ semantics.
14166     if (getLangOpts().CPlusPlus &&
14167         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14168       return false;
14169     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14170     break;
14171   case IncompatibleNestedPointerQualifiers:
14172     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14173     break;
14174   case IntToBlockPointer:
14175     DiagKind = diag::err_int_to_block_pointer;
14176     break;
14177   case IncompatibleBlockPointer:
14178     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14179     break;
14180   case IncompatibleObjCQualifiedId: {
14181     if (SrcType->isObjCQualifiedIdType()) {
14182       const ObjCObjectPointerType *srcOPT =
14183                 SrcType->getAs<ObjCObjectPointerType>();
14184       for (auto *srcProto : srcOPT->quals()) {
14185         PDecl = srcProto;
14186         break;
14187       }
14188       if (const ObjCInterfaceType *IFaceT =
14189             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14190         IFace = IFaceT->getDecl();
14191     }
14192     else if (DstType->isObjCQualifiedIdType()) {
14193       const ObjCObjectPointerType *dstOPT =
14194         DstType->getAs<ObjCObjectPointerType>();
14195       for (auto *dstProto : dstOPT->quals()) {
14196         PDecl = dstProto;
14197         break;
14198       }
14199       if (const ObjCInterfaceType *IFaceT =
14200             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14201         IFace = IFaceT->getDecl();
14202     }
14203     DiagKind = diag::warn_incompatible_qualified_id;
14204     break;
14205   }
14206   case IncompatibleVectors:
14207     DiagKind = diag::warn_incompatible_vectors;
14208     break;
14209   case IncompatibleObjCWeakRef:
14210     DiagKind = diag::err_arc_weak_unavailable_assign;
14211     break;
14212   case Incompatible:
14213     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14214       if (Complained)
14215         *Complained = true;
14216       return true;
14217     }
14218 
14219     DiagKind = diag::err_typecheck_convert_incompatible;
14220     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14221     MayHaveConvFixit = true;
14222     isInvalid = true;
14223     MayHaveFunctionDiff = true;
14224     break;
14225   }
14226 
14227   QualType FirstType, SecondType;
14228   switch (Action) {
14229   case AA_Assigning:
14230   case AA_Initializing:
14231     // The destination type comes first.
14232     FirstType = DstType;
14233     SecondType = SrcType;
14234     break;
14235 
14236   case AA_Returning:
14237   case AA_Passing:
14238   case AA_Passing_CFAudited:
14239   case AA_Converting:
14240   case AA_Sending:
14241   case AA_Casting:
14242     // The source type comes first.
14243     FirstType = SrcType;
14244     SecondType = DstType;
14245     break;
14246   }
14247 
14248   PartialDiagnostic FDiag = PDiag(DiagKind);
14249   if (Action == AA_Passing_CFAudited)
14250     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14251   else
14252     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14253 
14254   // If we can fix the conversion, suggest the FixIts.
14255   assert(ConvHints.isNull() || Hint.isNull());
14256   if (!ConvHints.isNull()) {
14257     for (FixItHint &H : ConvHints.Hints)
14258       FDiag << H;
14259   } else {
14260     FDiag << Hint;
14261   }
14262   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14263 
14264   if (MayHaveFunctionDiff)
14265     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14266 
14267   Diag(Loc, FDiag);
14268   if (DiagKind == diag::warn_incompatible_qualified_id &&
14269       PDecl && IFace && !IFace->hasDefinition())
14270       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14271         << IFace << PDecl;
14272 
14273   if (SecondType == Context.OverloadTy)
14274     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14275                               FirstType, /*TakingAddress=*/true);
14276 
14277   if (CheckInferredResultType)
14278     EmitRelatedResultTypeNote(SrcExpr);
14279 
14280   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14281     EmitRelatedResultTypeNoteForReturn(DstType);
14282 
14283   if (Complained)
14284     *Complained = true;
14285   return isInvalid;
14286 }
14287 
14288 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14289                                                  llvm::APSInt *Result) {
14290   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14291   public:
14292     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14293       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14294     }
14295   } Diagnoser;
14296 
14297   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14298 }
14299 
14300 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14301                                                  llvm::APSInt *Result,
14302                                                  unsigned DiagID,
14303                                                  bool AllowFold) {
14304   class IDDiagnoser : public VerifyICEDiagnoser {
14305     unsigned DiagID;
14306 
14307   public:
14308     IDDiagnoser(unsigned DiagID)
14309       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14310 
14311     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14312       S.Diag(Loc, DiagID) << SR;
14313     }
14314   } Diagnoser(DiagID);
14315 
14316   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14317 }
14318 
14319 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14320                                             SourceRange SR) {
14321   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14322 }
14323 
14324 ExprResult
14325 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14326                                       VerifyICEDiagnoser &Diagnoser,
14327                                       bool AllowFold) {
14328   SourceLocation DiagLoc = E->getBeginLoc();
14329 
14330   if (getLangOpts().CPlusPlus11) {
14331     // C++11 [expr.const]p5:
14332     //   If an expression of literal class type is used in a context where an
14333     //   integral constant expression is required, then that class type shall
14334     //   have a single non-explicit conversion function to an integral or
14335     //   unscoped enumeration type
14336     ExprResult Converted;
14337     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14338     public:
14339       CXX11ConvertDiagnoser(bool Silent)
14340           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14341                                 Silent, true) {}
14342 
14343       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14344                                            QualType T) override {
14345         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14346       }
14347 
14348       SemaDiagnosticBuilder diagnoseIncomplete(
14349           Sema &S, SourceLocation Loc, QualType T) override {
14350         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14351       }
14352 
14353       SemaDiagnosticBuilder diagnoseExplicitConv(
14354           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14355         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14356       }
14357 
14358       SemaDiagnosticBuilder noteExplicitConv(
14359           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14360         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14361                  << ConvTy->isEnumeralType() << ConvTy;
14362       }
14363 
14364       SemaDiagnosticBuilder diagnoseAmbiguous(
14365           Sema &S, SourceLocation Loc, QualType T) override {
14366         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14367       }
14368 
14369       SemaDiagnosticBuilder noteAmbiguous(
14370           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14371         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14372                  << ConvTy->isEnumeralType() << ConvTy;
14373       }
14374 
14375       SemaDiagnosticBuilder diagnoseConversion(
14376           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14377         llvm_unreachable("conversion functions are permitted");
14378       }
14379     } ConvertDiagnoser(Diagnoser.Suppress);
14380 
14381     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14382                                                     ConvertDiagnoser);
14383     if (Converted.isInvalid())
14384       return Converted;
14385     E = Converted.get();
14386     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14387       return ExprError();
14388   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14389     // An ICE must be of integral or unscoped enumeration type.
14390     if (!Diagnoser.Suppress)
14391       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14392     return ExprError();
14393   }
14394 
14395   if (!isa<ConstantExpr>(E))
14396     E = ConstantExpr::Create(Context, E);
14397 
14398   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14399   // in the non-ICE case.
14400   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14401     if (Result)
14402       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14403     return E;
14404   }
14405 
14406   Expr::EvalResult EvalResult;
14407   SmallVector<PartialDiagnosticAt, 8> Notes;
14408   EvalResult.Diag = &Notes;
14409 
14410   // Try to evaluate the expression, and produce diagnostics explaining why it's
14411   // not a constant expression as a side-effect.
14412   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14413                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14414 
14415   // In C++11, we can rely on diagnostics being produced for any expression
14416   // which is not a constant expression. If no diagnostics were produced, then
14417   // this is a constant expression.
14418   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14419     if (Result)
14420       *Result = EvalResult.Val.getInt();
14421     return E;
14422   }
14423 
14424   // If our only note is the usual "invalid subexpression" note, just point
14425   // the caret at its location rather than producing an essentially
14426   // redundant note.
14427   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14428         diag::note_invalid_subexpr_in_const_expr) {
14429     DiagLoc = Notes[0].first;
14430     Notes.clear();
14431   }
14432 
14433   if (!Folded || !AllowFold) {
14434     if (!Diagnoser.Suppress) {
14435       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14436       for (const PartialDiagnosticAt &Note : Notes)
14437         Diag(Note.first, Note.second);
14438     }
14439 
14440     return ExprError();
14441   }
14442 
14443   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14444   for (const PartialDiagnosticAt &Note : Notes)
14445     Diag(Note.first, Note.second);
14446 
14447   if (Result)
14448     *Result = EvalResult.Val.getInt();
14449   return E;
14450 }
14451 
14452 namespace {
14453   // Handle the case where we conclude a expression which we speculatively
14454   // considered to be unevaluated is actually evaluated.
14455   class TransformToPE : public TreeTransform<TransformToPE> {
14456     typedef TreeTransform<TransformToPE> BaseTransform;
14457 
14458   public:
14459     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14460 
14461     // Make sure we redo semantic analysis
14462     bool AlwaysRebuild() { return true; }
14463 
14464     // We need to special-case DeclRefExprs referring to FieldDecls which
14465     // are not part of a member pointer formation; normal TreeTransforming
14466     // doesn't catch this case because of the way we represent them in the AST.
14467     // FIXME: This is a bit ugly; is it really the best way to handle this
14468     // case?
14469     //
14470     // Error on DeclRefExprs referring to FieldDecls.
14471     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14472       if (isa<FieldDecl>(E->getDecl()) &&
14473           !SemaRef.isUnevaluatedContext())
14474         return SemaRef.Diag(E->getLocation(),
14475                             diag::err_invalid_non_static_member_use)
14476             << E->getDecl() << E->getSourceRange();
14477 
14478       return BaseTransform::TransformDeclRefExpr(E);
14479     }
14480 
14481     // Exception: filter out member pointer formation
14482     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14483       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14484         return E;
14485 
14486       return BaseTransform::TransformUnaryOperator(E);
14487     }
14488 
14489     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14490       // Lambdas never need to be transformed.
14491       return E;
14492     }
14493   };
14494 }
14495 
14496 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14497   assert(isUnevaluatedContext() &&
14498          "Should only transform unevaluated expressions");
14499   ExprEvalContexts.back().Context =
14500       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14501   if (isUnevaluatedContext())
14502     return E;
14503   return TransformToPE(*this).TransformExpr(E);
14504 }
14505 
14506 void
14507 Sema::PushExpressionEvaluationContext(
14508     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14509     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14510   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14511                                 LambdaContextDecl, ExprContext);
14512   Cleanup.reset();
14513   if (!MaybeODRUseExprs.empty())
14514     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14515 }
14516 
14517 void
14518 Sema::PushExpressionEvaluationContext(
14519     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14520     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14521   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14522   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14523 }
14524 
14525 namespace {
14526 
14527 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14528   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14529   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14530     if (E->getOpcode() == UO_Deref)
14531       return CheckPossibleDeref(S, E->getSubExpr());
14532   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14533     return CheckPossibleDeref(S, E->getBase());
14534   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14535     return CheckPossibleDeref(S, E->getBase());
14536   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14537     QualType Inner;
14538     QualType Ty = E->getType();
14539     if (const auto *Ptr = Ty->getAs<PointerType>())
14540       Inner = Ptr->getPointeeType();
14541     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14542       Inner = Arr->getElementType();
14543     else
14544       return nullptr;
14545 
14546     if (Inner->hasAttr(attr::NoDeref))
14547       return E;
14548   }
14549   return nullptr;
14550 }
14551 
14552 } // namespace
14553 
14554 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14555   for (const Expr *E : Rec.PossibleDerefs) {
14556     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14557     if (DeclRef) {
14558       const ValueDecl *Decl = DeclRef->getDecl();
14559       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14560           << Decl->getName() << E->getSourceRange();
14561       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14562     } else {
14563       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14564           << E->getSourceRange();
14565     }
14566   }
14567   Rec.PossibleDerefs.clear();
14568 }
14569 
14570 void Sema::PopExpressionEvaluationContext() {
14571   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14572   unsigned NumTypos = Rec.NumTypos;
14573 
14574   if (!Rec.Lambdas.empty()) {
14575     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14576     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14577         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14578       unsigned D;
14579       if (Rec.isUnevaluated()) {
14580         // C++11 [expr.prim.lambda]p2:
14581         //   A lambda-expression shall not appear in an unevaluated operand
14582         //   (Clause 5).
14583         D = diag::err_lambda_unevaluated_operand;
14584       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14585         // C++1y [expr.const]p2:
14586         //   A conditional-expression e is a core constant expression unless the
14587         //   evaluation of e, following the rules of the abstract machine, would
14588         //   evaluate [...] a lambda-expression.
14589         D = diag::err_lambda_in_constant_expression;
14590       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14591         // C++17 [expr.prim.lamda]p2:
14592         // A lambda-expression shall not appear [...] in a template-argument.
14593         D = diag::err_lambda_in_invalid_context;
14594       } else
14595         llvm_unreachable("Couldn't infer lambda error message.");
14596 
14597       for (const auto *L : Rec.Lambdas)
14598         Diag(L->getBeginLoc(), D);
14599     } else {
14600       // Mark the capture expressions odr-used. This was deferred
14601       // during lambda expression creation.
14602       for (auto *Lambda : Rec.Lambdas) {
14603         for (auto *C : Lambda->capture_inits())
14604           MarkDeclarationsReferencedInExpr(C);
14605       }
14606     }
14607   }
14608 
14609   WarnOnPendingNoDerefs(Rec);
14610 
14611   // When are coming out of an unevaluated context, clear out any
14612   // temporaries that we may have created as part of the evaluation of
14613   // the expression in that context: they aren't relevant because they
14614   // will never be constructed.
14615   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14616     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14617                              ExprCleanupObjects.end());
14618     Cleanup = Rec.ParentCleanup;
14619     CleanupVarDeclMarking();
14620     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14621   // Otherwise, merge the contexts together.
14622   } else {
14623     Cleanup.mergeFrom(Rec.ParentCleanup);
14624     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14625                             Rec.SavedMaybeODRUseExprs.end());
14626   }
14627 
14628   // Pop the current expression evaluation context off the stack.
14629   ExprEvalContexts.pop_back();
14630 
14631   // The global expression evaluation context record is never popped.
14632   ExprEvalContexts.back().NumTypos += NumTypos;
14633 }
14634 
14635 void Sema::DiscardCleanupsInEvaluationContext() {
14636   ExprCleanupObjects.erase(
14637          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14638          ExprCleanupObjects.end());
14639   Cleanup.reset();
14640   MaybeODRUseExprs.clear();
14641 }
14642 
14643 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14644   ExprResult Result = CheckPlaceholderExpr(E);
14645   if (Result.isInvalid())
14646     return ExprError();
14647   E = Result.get();
14648   if (!E->getType()->isVariablyModifiedType())
14649     return E;
14650   return TransformToPotentiallyEvaluated(E);
14651 }
14652 
14653 /// Are we within a context in which some evaluation could be performed (be it
14654 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14655 /// captured by C++'s idea of an "unevaluated context".
14656 static bool isEvaluatableContext(Sema &SemaRef) {
14657   switch (SemaRef.ExprEvalContexts.back().Context) {
14658     case Sema::ExpressionEvaluationContext::Unevaluated:
14659     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14660       // Expressions in this context are never evaluated.
14661       return false;
14662 
14663     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14664     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14665     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14666     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14667       // Expressions in this context could be evaluated.
14668       return true;
14669 
14670     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14671       // Referenced declarations will only be used if the construct in the
14672       // containing expression is used, at which point we'll be given another
14673       // turn to mark them.
14674       return false;
14675   }
14676   llvm_unreachable("Invalid context");
14677 }
14678 
14679 /// Are we within a context in which references to resolved functions or to
14680 /// variables result in odr-use?
14681 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14682   // An expression in a template is not really an expression until it's been
14683   // instantiated, so it doesn't trigger odr-use.
14684   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14685     return false;
14686 
14687   switch (SemaRef.ExprEvalContexts.back().Context) {
14688     case Sema::ExpressionEvaluationContext::Unevaluated:
14689     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14690     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14691     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14692       return false;
14693 
14694     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14695     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14696       return true;
14697 
14698     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14699       return false;
14700   }
14701   llvm_unreachable("Invalid context");
14702 }
14703 
14704 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14705   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14706   return Func->isConstexpr() &&
14707          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14708 }
14709 
14710 /// Mark a function referenced, and check whether it is odr-used
14711 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14712 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14713                                   bool MightBeOdrUse) {
14714   assert(Func && "No function?");
14715 
14716   Func->setReferenced();
14717 
14718   // C++11 [basic.def.odr]p3:
14719   //   A function whose name appears as a potentially-evaluated expression is
14720   //   odr-used if it is the unique lookup result or the selected member of a
14721   //   set of overloaded functions [...].
14722   //
14723   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14724   // can just check that here.
14725   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14726 
14727   // Determine whether we require a function definition to exist, per
14728   // C++11 [temp.inst]p3:
14729   //   Unless a function template specialization has been explicitly
14730   //   instantiated or explicitly specialized, the function template
14731   //   specialization is implicitly instantiated when the specialization is
14732   //   referenced in a context that requires a function definition to exist.
14733   //
14734   // That is either when this is an odr-use, or when a usage of a constexpr
14735   // function occurs within an evaluatable context.
14736   bool NeedDefinition =
14737       OdrUse || (isEvaluatableContext(*this) &&
14738                  isImplicitlyDefinableConstexprFunction(Func));
14739 
14740   // C++14 [temp.expl.spec]p6:
14741   //   If a template [...] is explicitly specialized then that specialization
14742   //   shall be declared before the first use of that specialization that would
14743   //   cause an implicit instantiation to take place, in every translation unit
14744   //   in which such a use occurs
14745   if (NeedDefinition &&
14746       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14747        Func->getMemberSpecializationInfo()))
14748     checkSpecializationVisibility(Loc, Func);
14749 
14750   // C++14 [except.spec]p17:
14751   //   An exception-specification is considered to be needed when:
14752   //   - the function is odr-used or, if it appears in an unevaluated operand,
14753   //     would be odr-used if the expression were potentially-evaluated;
14754   //
14755   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14756   // function is a pure virtual function we're calling, and in that case the
14757   // function was selected by overload resolution and we need to resolve its
14758   // exception specification for a different reason.
14759   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14760   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14761     ResolveExceptionSpec(Loc, FPT);
14762 
14763   // If we don't need to mark the function as used, and we don't need to
14764   // try to provide a definition, there's nothing more to do.
14765   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14766       (!NeedDefinition || Func->getBody()))
14767     return;
14768 
14769   // Note that this declaration has been used.
14770   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14771     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14772     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14773       if (Constructor->isDefaultConstructor()) {
14774         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14775           return;
14776         DefineImplicitDefaultConstructor(Loc, Constructor);
14777       } else if (Constructor->isCopyConstructor()) {
14778         DefineImplicitCopyConstructor(Loc, Constructor);
14779       } else if (Constructor->isMoveConstructor()) {
14780         DefineImplicitMoveConstructor(Loc, Constructor);
14781       }
14782     } else if (Constructor->getInheritedConstructor()) {
14783       DefineInheritingConstructor(Loc, Constructor);
14784     }
14785   } else if (CXXDestructorDecl *Destructor =
14786                  dyn_cast<CXXDestructorDecl>(Func)) {
14787     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14788     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14789       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14790         return;
14791       DefineImplicitDestructor(Loc, Destructor);
14792     }
14793     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14794       MarkVTableUsed(Loc, Destructor->getParent());
14795   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14796     if (MethodDecl->isOverloadedOperator() &&
14797         MethodDecl->getOverloadedOperator() == OO_Equal) {
14798       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14799       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14800         if (MethodDecl->isCopyAssignmentOperator())
14801           DefineImplicitCopyAssignment(Loc, MethodDecl);
14802         else if (MethodDecl->isMoveAssignmentOperator())
14803           DefineImplicitMoveAssignment(Loc, MethodDecl);
14804       }
14805     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14806                MethodDecl->getParent()->isLambda()) {
14807       CXXConversionDecl *Conversion =
14808           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14809       if (Conversion->isLambdaToBlockPointerConversion())
14810         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14811       else
14812         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14813     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14814       MarkVTableUsed(Loc, MethodDecl->getParent());
14815   }
14816 
14817   // Recursive functions should be marked when used from another function.
14818   // FIXME: Is this really right?
14819   if (CurContext == Func) return;
14820 
14821   // Implicit instantiation of function templates and member functions of
14822   // class templates.
14823   if (Func->isImplicitlyInstantiable()) {
14824     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14825     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14826     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14827     if (FirstInstantiation) {
14828       PointOfInstantiation = Loc;
14829       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14830     } else if (TSK != TSK_ImplicitInstantiation) {
14831       // Use the point of use as the point of instantiation, instead of the
14832       // point of explicit instantiation (which we track as the actual point of
14833       // instantiation). This gives better backtraces in diagnostics.
14834       PointOfInstantiation = Loc;
14835     }
14836 
14837     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14838         Func->isConstexpr()) {
14839       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14840           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14841           CodeSynthesisContexts.size())
14842         PendingLocalImplicitInstantiations.push_back(
14843             std::make_pair(Func, PointOfInstantiation));
14844       else if (Func->isConstexpr())
14845         // Do not defer instantiations of constexpr functions, to avoid the
14846         // expression evaluator needing to call back into Sema if it sees a
14847         // call to such a function.
14848         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14849       else {
14850         Func->setInstantiationIsPending(true);
14851         PendingInstantiations.push_back(std::make_pair(Func,
14852                                                        PointOfInstantiation));
14853         // Notify the consumer that a function was implicitly instantiated.
14854         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14855       }
14856     }
14857   } else {
14858     // Walk redefinitions, as some of them may be instantiable.
14859     for (auto i : Func->redecls()) {
14860       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14861         MarkFunctionReferenced(Loc, i, OdrUse);
14862     }
14863   }
14864 
14865   if (!OdrUse) return;
14866 
14867   // Keep track of used but undefined functions.
14868   if (!Func->isDefined()) {
14869     if (mightHaveNonExternalLinkage(Func))
14870       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14871     else if (Func->getMostRecentDecl()->isInlined() &&
14872              !LangOpts.GNUInline &&
14873              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14874       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14875     else if (isExternalWithNoLinkageType(Func))
14876       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14877   }
14878 
14879   Func->markUsed(Context);
14880 
14881   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
14882     checkOpenMPDeviceFunction(Loc, Func);
14883 }
14884 
14885 static void
14886 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14887                                    ValueDecl *var, DeclContext *DC) {
14888   DeclContext *VarDC = var->getDeclContext();
14889 
14890   //  If the parameter still belongs to the translation unit, then
14891   //  we're actually just using one parameter in the declaration of
14892   //  the next.
14893   if (isa<ParmVarDecl>(var) &&
14894       isa<TranslationUnitDecl>(VarDC))
14895     return;
14896 
14897   // For C code, don't diagnose about capture if we're not actually in code
14898   // right now; it's impossible to write a non-constant expression outside of
14899   // function context, so we'll get other (more useful) diagnostics later.
14900   //
14901   // For C++, things get a bit more nasty... it would be nice to suppress this
14902   // diagnostic for certain cases like using a local variable in an array bound
14903   // for a member of a local class, but the correct predicate is not obvious.
14904   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14905     return;
14906 
14907   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14908   unsigned ContextKind = 3; // unknown
14909   if (isa<CXXMethodDecl>(VarDC) &&
14910       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14911     ContextKind = 2;
14912   } else if (isa<FunctionDecl>(VarDC)) {
14913     ContextKind = 0;
14914   } else if (isa<BlockDecl>(VarDC)) {
14915     ContextKind = 1;
14916   }
14917 
14918   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14919     << var << ValueKind << ContextKind << VarDC;
14920   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14921       << var;
14922 
14923   // FIXME: Add additional diagnostic info about class etc. which prevents
14924   // capture.
14925 }
14926 
14927 
14928 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14929                                       bool &SubCapturesAreNested,
14930                                       QualType &CaptureType,
14931                                       QualType &DeclRefType) {
14932    // Check whether we've already captured it.
14933   if (CSI->CaptureMap.count(Var)) {
14934     // If we found a capture, any subcaptures are nested.
14935     SubCapturesAreNested = true;
14936 
14937     // Retrieve the capture type for this variable.
14938     CaptureType = CSI->getCapture(Var).getCaptureType();
14939 
14940     // Compute the type of an expression that refers to this variable.
14941     DeclRefType = CaptureType.getNonReferenceType();
14942 
14943     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14944     // are mutable in the sense that user can change their value - they are
14945     // private instances of the captured declarations.
14946     const Capture &Cap = CSI->getCapture(Var);
14947     if (Cap.isCopyCapture() &&
14948         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14949         !(isa<CapturedRegionScopeInfo>(CSI) &&
14950           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14951       DeclRefType.addConst();
14952     return true;
14953   }
14954   return false;
14955 }
14956 
14957 // Only block literals, captured statements, and lambda expressions can
14958 // capture; other scopes don't work.
14959 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14960                                  SourceLocation Loc,
14961                                  const bool Diagnose, Sema &S) {
14962   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14963     return getLambdaAwareParentOfDeclContext(DC);
14964   else if (Var->hasLocalStorage()) {
14965     if (Diagnose)
14966        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14967   }
14968   return nullptr;
14969 }
14970 
14971 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14972 // certain types of variables (unnamed, variably modified types etc.)
14973 // so check for eligibility.
14974 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14975                                  SourceLocation Loc,
14976                                  const bool Diagnose, Sema &S) {
14977 
14978   bool IsBlock = isa<BlockScopeInfo>(CSI);
14979   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14980 
14981   // Lambdas are not allowed to capture unnamed variables
14982   // (e.g. anonymous unions).
14983   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14984   // assuming that's the intent.
14985   if (IsLambda && !Var->getDeclName()) {
14986     if (Diagnose) {
14987       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14988       S.Diag(Var->getLocation(), diag::note_declared_at);
14989     }
14990     return false;
14991   }
14992 
14993   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14994   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14995     if (Diagnose) {
14996       S.Diag(Loc, diag::err_ref_vm_type);
14997       S.Diag(Var->getLocation(), diag::note_previous_decl)
14998         << Var->getDeclName();
14999     }
15000     return false;
15001   }
15002   // Prohibit structs with flexible array members too.
15003   // We cannot capture what is in the tail end of the struct.
15004   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15005     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15006       if (Diagnose) {
15007         if (IsBlock)
15008           S.Diag(Loc, diag::err_ref_flexarray_type);
15009         else
15010           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15011             << Var->getDeclName();
15012         S.Diag(Var->getLocation(), diag::note_previous_decl)
15013           << Var->getDeclName();
15014       }
15015       return false;
15016     }
15017   }
15018   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15019   // Lambdas and captured statements are not allowed to capture __block
15020   // variables; they don't support the expected semantics.
15021   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15022     if (Diagnose) {
15023       S.Diag(Loc, diag::err_capture_block_variable)
15024         << Var->getDeclName() << !IsLambda;
15025       S.Diag(Var->getLocation(), diag::note_previous_decl)
15026         << Var->getDeclName();
15027     }
15028     return false;
15029   }
15030   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15031   if (S.getLangOpts().OpenCL && IsBlock &&
15032       Var->getType()->isBlockPointerType()) {
15033     if (Diagnose)
15034       S.Diag(Loc, diag::err_opencl_block_ref_block);
15035     return false;
15036   }
15037 
15038   return true;
15039 }
15040 
15041 // Returns true if the capture by block was successful.
15042 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15043                                  SourceLocation Loc,
15044                                  const bool BuildAndDiagnose,
15045                                  QualType &CaptureType,
15046                                  QualType &DeclRefType,
15047                                  const bool Nested,
15048                                  Sema &S) {
15049   Expr *CopyExpr = nullptr;
15050   bool ByRef = false;
15051 
15052   // Blocks are not allowed to capture arrays, excepting OpenCL.
15053   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15054   // (decayed to pointers).
15055   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15056     if (BuildAndDiagnose) {
15057       S.Diag(Loc, diag::err_ref_array_type);
15058       S.Diag(Var->getLocation(), diag::note_previous_decl)
15059       << Var->getDeclName();
15060     }
15061     return false;
15062   }
15063 
15064   // Forbid the block-capture of autoreleasing variables.
15065   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15066     if (BuildAndDiagnose) {
15067       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15068         << /*block*/ 0;
15069       S.Diag(Var->getLocation(), diag::note_previous_decl)
15070         << Var->getDeclName();
15071     }
15072     return false;
15073   }
15074 
15075   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15076   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15077     // This function finds out whether there is an AttributedType of kind
15078     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15079     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15080     // rather than being added implicitly by the compiler.
15081     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15082       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15083         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15084           return true;
15085 
15086         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15087         Ty = AttrTy->getModifiedType();
15088       }
15089 
15090       return false;
15091     };
15092 
15093     QualType PointeeTy = PT->getPointeeType();
15094 
15095     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
15096         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15097         !IsObjCOwnershipAttributedType(PointeeTy)) {
15098       if (BuildAndDiagnose) {
15099         SourceLocation VarLoc = Var->getLocation();
15100         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15101         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15102       }
15103     }
15104   }
15105 
15106   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15107   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15108       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15109     // Block capture by reference does not change the capture or
15110     // declaration reference types.
15111     ByRef = true;
15112   } else {
15113     // Block capture by copy introduces 'const'.
15114     CaptureType = CaptureType.getNonReferenceType().withConst();
15115     DeclRefType = CaptureType;
15116 
15117     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15118       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15119         // The capture logic needs the destructor, so make sure we mark it.
15120         // Usually this is unnecessary because most local variables have
15121         // their destructors marked at declaration time, but parameters are
15122         // an exception because it's technically only the call site that
15123         // actually requires the destructor.
15124         if (isa<ParmVarDecl>(Var))
15125           S.FinalizeVarWithDestructor(Var, Record);
15126 
15127         // Enter a new evaluation context to insulate the copy
15128         // full-expression.
15129         EnterExpressionEvaluationContext scope(
15130             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
15131 
15132         // According to the blocks spec, the capture of a variable from
15133         // the stack requires a const copy constructor.  This is not true
15134         // of the copy/move done to move a __block variable to the heap.
15135         Expr *DeclRef = new (S.Context) DeclRefExpr(
15136             S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15137 
15138         ExprResult Result
15139           = S.PerformCopyInitialization(
15140               InitializedEntity::InitializeBlock(Var->getLocation(),
15141                                                   CaptureType, false),
15142               Loc, DeclRef);
15143 
15144         // Build a full-expression copy expression if initialization
15145         // succeeded and used a non-trivial constructor.  Recover from
15146         // errors by pretending that the copy isn't necessary.
15147         if (!Result.isInvalid() &&
15148             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15149                 ->isTrivial()) {
15150           Result = S.MaybeCreateExprWithCleanups(Result);
15151           CopyExpr = Result.get();
15152         }
15153       }
15154     }
15155   }
15156 
15157   // Actually capture the variable.
15158   if (BuildAndDiagnose)
15159     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15160                     SourceLocation(), CaptureType, CopyExpr);
15161 
15162   return true;
15163 
15164 }
15165 
15166 
15167 /// Capture the given variable in the captured region.
15168 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15169                                     VarDecl *Var,
15170                                     SourceLocation Loc,
15171                                     const bool BuildAndDiagnose,
15172                                     QualType &CaptureType,
15173                                     QualType &DeclRefType,
15174                                     const bool RefersToCapturedVariable,
15175                                     Sema &S) {
15176   // By default, capture variables by reference.
15177   bool ByRef = true;
15178   // Using an LValue reference type is consistent with Lambdas (see below).
15179   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15180     if (S.isOpenMPCapturedDecl(Var)) {
15181       bool HasConst = DeclRefType.isConstQualified();
15182       DeclRefType = DeclRefType.getUnqualifiedType();
15183       // Don't lose diagnostics about assignments to const.
15184       if (HasConst)
15185         DeclRefType.addConst();
15186     }
15187     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15188   }
15189 
15190   if (ByRef)
15191     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15192   else
15193     CaptureType = DeclRefType;
15194 
15195   Expr *CopyExpr = nullptr;
15196   if (BuildAndDiagnose) {
15197     // The current implementation assumes that all variables are captured
15198     // by references. Since there is no capture by copy, no expression
15199     // evaluation will be needed.
15200     RecordDecl *RD = RSI->TheRecordDecl;
15201 
15202     FieldDecl *Field
15203       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15204                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15205                           nullptr, false, ICIS_NoInit);
15206     Field->setImplicit(true);
15207     Field->setAccess(AS_private);
15208     RD->addDecl(Field);
15209     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15210       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15211 
15212     CopyExpr = new (S.Context) DeclRefExpr(
15213         S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15214     Var->setReferenced(true);
15215     Var->markUsed(S.Context);
15216   }
15217 
15218   // Actually capture the variable.
15219   if (BuildAndDiagnose)
15220     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15221                     SourceLocation(), CaptureType, CopyExpr);
15222 
15223 
15224   return true;
15225 }
15226 
15227 /// Create a field within the lambda class for the variable
15228 /// being captured.
15229 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
15230                                     QualType FieldType, QualType DeclRefType,
15231                                     SourceLocation Loc,
15232                                     bool RefersToCapturedVariable) {
15233   CXXRecordDecl *Lambda = LSI->Lambda;
15234 
15235   // Build the non-static data member.
15236   FieldDecl *Field
15237     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15238                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15239                         nullptr, false, ICIS_NoInit);
15240   // If the variable being captured has an invalid type, mark the lambda class
15241   // as invalid as well.
15242   if (!FieldType->isDependentType()) {
15243     if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15244       Lambda->setInvalidDecl();
15245       Field->setInvalidDecl();
15246     } else {
15247       NamedDecl *Def;
15248       FieldType->isIncompleteType(&Def);
15249       if (Def && Def->isInvalidDecl()) {
15250         Lambda->setInvalidDecl();
15251         Field->setInvalidDecl();
15252       }
15253     }
15254   }
15255   Field->setImplicit(true);
15256   Field->setAccess(AS_private);
15257   Lambda->addDecl(Field);
15258 }
15259 
15260 /// Capture the given variable in the lambda.
15261 static bool captureInLambda(LambdaScopeInfo *LSI,
15262                             VarDecl *Var,
15263                             SourceLocation Loc,
15264                             const bool BuildAndDiagnose,
15265                             QualType &CaptureType,
15266                             QualType &DeclRefType,
15267                             const bool RefersToCapturedVariable,
15268                             const Sema::TryCaptureKind Kind,
15269                             SourceLocation EllipsisLoc,
15270                             const bool IsTopScope,
15271                             Sema &S) {
15272 
15273   // Determine whether we are capturing by reference or by value.
15274   bool ByRef = false;
15275   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15276     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15277   } else {
15278     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15279   }
15280 
15281   // Compute the type of the field that will capture this variable.
15282   if (ByRef) {
15283     // C++11 [expr.prim.lambda]p15:
15284     //   An entity is captured by reference if it is implicitly or
15285     //   explicitly captured but not captured by copy. It is
15286     //   unspecified whether additional unnamed non-static data
15287     //   members are declared in the closure type for entities
15288     //   captured by reference.
15289     //
15290     // FIXME: It is not clear whether we want to build an lvalue reference
15291     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15292     // to do the former, while EDG does the latter. Core issue 1249 will
15293     // clarify, but for now we follow GCC because it's a more permissive and
15294     // easily defensible position.
15295     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15296   } else {
15297     // C++11 [expr.prim.lambda]p14:
15298     //   For each entity captured by copy, an unnamed non-static
15299     //   data member is declared in the closure type. The
15300     //   declaration order of these members is unspecified. The type
15301     //   of such a data member is the type of the corresponding
15302     //   captured entity if the entity is not a reference to an
15303     //   object, or the referenced type otherwise. [Note: If the
15304     //   captured entity is a reference to a function, the
15305     //   corresponding data member is also a reference to a
15306     //   function. - end note ]
15307     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15308       if (!RefType->getPointeeType()->isFunctionType())
15309         CaptureType = RefType->getPointeeType();
15310     }
15311 
15312     // Forbid the lambda copy-capture of autoreleasing variables.
15313     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15314       if (BuildAndDiagnose) {
15315         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15316         S.Diag(Var->getLocation(), diag::note_previous_decl)
15317           << Var->getDeclName();
15318       }
15319       return false;
15320     }
15321 
15322     // Make sure that by-copy captures are of a complete and non-abstract type.
15323     if (BuildAndDiagnose) {
15324       if (!CaptureType->isDependentType() &&
15325           S.RequireCompleteType(Loc, CaptureType,
15326                                 diag::err_capture_of_incomplete_type,
15327                                 Var->getDeclName()))
15328         return false;
15329 
15330       if (S.RequireNonAbstractType(Loc, CaptureType,
15331                                    diag::err_capture_of_abstract_type))
15332         return false;
15333     }
15334   }
15335 
15336   // Capture this variable in the lambda.
15337   if (BuildAndDiagnose)
15338     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15339                             RefersToCapturedVariable);
15340 
15341   // Compute the type of a reference to this captured variable.
15342   if (ByRef)
15343     DeclRefType = CaptureType.getNonReferenceType();
15344   else {
15345     // C++ [expr.prim.lambda]p5:
15346     //   The closure type for a lambda-expression has a public inline
15347     //   function call operator [...]. This function call operator is
15348     //   declared const (9.3.1) if and only if the lambda-expression's
15349     //   parameter-declaration-clause is not followed by mutable.
15350     DeclRefType = CaptureType.getNonReferenceType();
15351     if (!LSI->Mutable && !CaptureType->isReferenceType())
15352       DeclRefType.addConst();
15353   }
15354 
15355   // Add the capture.
15356   if (BuildAndDiagnose)
15357     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15358                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15359 
15360   return true;
15361 }
15362 
15363 bool Sema::tryCaptureVariable(
15364     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15365     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15366     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15367   // An init-capture is notionally from the context surrounding its
15368   // declaration, but its parent DC is the lambda class.
15369   DeclContext *VarDC = Var->getDeclContext();
15370   if (Var->isInitCapture())
15371     VarDC = VarDC->getParent();
15372 
15373   DeclContext *DC = CurContext;
15374   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15375       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15376   // We need to sync up the Declaration Context with the
15377   // FunctionScopeIndexToStopAt
15378   if (FunctionScopeIndexToStopAt) {
15379     unsigned FSIndex = FunctionScopes.size() - 1;
15380     while (FSIndex != MaxFunctionScopesIndex) {
15381       DC = getLambdaAwareParentOfDeclContext(DC);
15382       --FSIndex;
15383     }
15384   }
15385 
15386 
15387   // If the variable is declared in the current context, there is no need to
15388   // capture it.
15389   if (VarDC == DC) return true;
15390 
15391   // Capture global variables if it is required to use private copy of this
15392   // variable.
15393   bool IsGlobal = !Var->hasLocalStorage();
15394   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15395     return true;
15396   Var = Var->getCanonicalDecl();
15397 
15398   // Walk up the stack to determine whether we can capture the variable,
15399   // performing the "simple" checks that don't depend on type. We stop when
15400   // we've either hit the declared scope of the variable or find an existing
15401   // capture of that variable.  We start from the innermost capturing-entity
15402   // (the DC) and ensure that all intervening capturing-entities
15403   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15404   // declcontext can either capture the variable or have already captured
15405   // the variable.
15406   CaptureType = Var->getType();
15407   DeclRefType = CaptureType.getNonReferenceType();
15408   bool Nested = false;
15409   bool Explicit = (Kind != TryCapture_Implicit);
15410   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15411   do {
15412     // Only block literals, captured statements, and lambda expressions can
15413     // capture; other scopes don't work.
15414     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15415                                                               ExprLoc,
15416                                                               BuildAndDiagnose,
15417                                                               *this);
15418     // We need to check for the parent *first* because, if we *have*
15419     // private-captured a global variable, we need to recursively capture it in
15420     // intermediate blocks, lambdas, etc.
15421     if (!ParentDC) {
15422       if (IsGlobal) {
15423         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15424         break;
15425       }
15426       return true;
15427     }
15428 
15429     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15430     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15431 
15432 
15433     // Check whether we've already captured it.
15434     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15435                                              DeclRefType)) {
15436       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15437       break;
15438     }
15439     // If we are instantiating a generic lambda call operator body,
15440     // we do not want to capture new variables.  What was captured
15441     // during either a lambdas transformation or initial parsing
15442     // should be used.
15443     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15444       if (BuildAndDiagnose) {
15445         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15446         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15447           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15448           Diag(Var->getLocation(), diag::note_previous_decl)
15449              << Var->getDeclName();
15450           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15451         } else
15452           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15453       }
15454       return true;
15455     }
15456     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15457     // certain types of variables (unnamed, variably modified types etc.)
15458     // so check for eligibility.
15459     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15460        return true;
15461 
15462     // Try to capture variable-length arrays types.
15463     if (Var->getType()->isVariablyModifiedType()) {
15464       // We're going to walk down into the type and look for VLA
15465       // expressions.
15466       QualType QTy = Var->getType();
15467       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15468         QTy = PVD->getOriginalType();
15469       captureVariablyModifiedType(Context, QTy, CSI);
15470     }
15471 
15472     if (getLangOpts().OpenMP) {
15473       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15474         // OpenMP private variables should not be captured in outer scope, so
15475         // just break here. Similarly, global variables that are captured in a
15476         // target region should not be captured outside the scope of the region.
15477         if (RSI->CapRegionKind == CR_OpenMP) {
15478           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15479           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15480                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15481           // When we detect target captures we are looking from inside the
15482           // target region, therefore we need to propagate the capture from the
15483           // enclosing region. Therefore, the capture is not initially nested.
15484           if (IsTargetCap)
15485             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15486 
15487           if (IsTargetCap || IsOpenMPPrivateDecl) {
15488             Nested = !IsTargetCap;
15489             DeclRefType = DeclRefType.getUnqualifiedType();
15490             CaptureType = Context.getLValueReferenceType(DeclRefType);
15491             break;
15492           }
15493         }
15494       }
15495     }
15496     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15497       // No capture-default, and this is not an explicit capture
15498       // so cannot capture this variable.
15499       if (BuildAndDiagnose) {
15500         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15501         Diag(Var->getLocation(), diag::note_previous_decl)
15502           << Var->getDeclName();
15503         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15504           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15505                diag::note_lambda_decl);
15506         // FIXME: If we error out because an outer lambda can not implicitly
15507         // capture a variable that an inner lambda explicitly captures, we
15508         // should have the inner lambda do the explicit capture - because
15509         // it makes for cleaner diagnostics later.  This would purely be done
15510         // so that the diagnostic does not misleadingly claim that a variable
15511         // can not be captured by a lambda implicitly even though it is captured
15512         // explicitly.  Suggestion:
15513         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15514         //    at the function head
15515         //  - cache the StartingDeclContext - this must be a lambda
15516         //  - captureInLambda in the innermost lambda the variable.
15517       }
15518       return true;
15519     }
15520 
15521     FunctionScopesIndex--;
15522     DC = ParentDC;
15523     Explicit = false;
15524   } while (!VarDC->Equals(DC));
15525 
15526   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15527   // computing the type of the capture at each step, checking type-specific
15528   // requirements, and adding captures if requested.
15529   // If the variable had already been captured previously, we start capturing
15530   // at the lambda nested within that one.
15531   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15532        ++I) {
15533     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15534 
15535     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15536       if (!captureInBlock(BSI, Var, ExprLoc,
15537                           BuildAndDiagnose, CaptureType,
15538                           DeclRefType, Nested, *this))
15539         return true;
15540       Nested = true;
15541     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15542       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15543                                    BuildAndDiagnose, CaptureType,
15544                                    DeclRefType, Nested, *this))
15545         return true;
15546       Nested = true;
15547     } else {
15548       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15549       if (!captureInLambda(LSI, Var, ExprLoc,
15550                            BuildAndDiagnose, CaptureType,
15551                            DeclRefType, Nested, Kind, EllipsisLoc,
15552                             /*IsTopScope*/I == N - 1, *this))
15553         return true;
15554       Nested = true;
15555     }
15556   }
15557   return false;
15558 }
15559 
15560 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15561                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15562   QualType CaptureType;
15563   QualType DeclRefType;
15564   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15565                             /*BuildAndDiagnose=*/true, CaptureType,
15566                             DeclRefType, nullptr);
15567 }
15568 
15569 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15570   QualType CaptureType;
15571   QualType DeclRefType;
15572   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15573                              /*BuildAndDiagnose=*/false, CaptureType,
15574                              DeclRefType, nullptr);
15575 }
15576 
15577 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15578   QualType CaptureType;
15579   QualType DeclRefType;
15580 
15581   // Determine whether we can capture this variable.
15582   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15583                          /*BuildAndDiagnose=*/false, CaptureType,
15584                          DeclRefType, nullptr))
15585     return QualType();
15586 
15587   return DeclRefType;
15588 }
15589 
15590 
15591 
15592 // If either the type of the variable or the initializer is dependent,
15593 // return false. Otherwise, determine whether the variable is a constant
15594 // expression. Use this if you need to know if a variable that might or
15595 // might not be dependent is truly a constant expression.
15596 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15597     ASTContext &Context) {
15598 
15599   if (Var->getType()->isDependentType())
15600     return false;
15601   const VarDecl *DefVD = nullptr;
15602   Var->getAnyInitializer(DefVD);
15603   if (!DefVD)
15604     return false;
15605   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15606   Expr *Init = cast<Expr>(Eval->Value);
15607   if (Init->isValueDependent())
15608     return false;
15609   return IsVariableAConstantExpression(Var, Context);
15610 }
15611 
15612 
15613 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15614   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15615   // an object that satisfies the requirements for appearing in a
15616   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15617   // is immediately applied."  This function handles the lvalue-to-rvalue
15618   // conversion part.
15619   MaybeODRUseExprs.erase(E->IgnoreParens());
15620 
15621   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15622   // to a variable that is a constant expression, and if so, identify it as
15623   // a reference to a variable that does not involve an odr-use of that
15624   // variable.
15625   if (LambdaScopeInfo *LSI = getCurLambda()) {
15626     Expr *SansParensExpr = E->IgnoreParens();
15627     VarDecl *Var = nullptr;
15628     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15629       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15630     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15631       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15632 
15633     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15634       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15635   }
15636 }
15637 
15638 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15639   Res = CorrectDelayedTyposInExpr(Res);
15640 
15641   if (!Res.isUsable())
15642     return Res;
15643 
15644   // If a constant-expression is a reference to a variable where we delay
15645   // deciding whether it is an odr-use, just assume we will apply the
15646   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15647   // (a non-type template argument), we have special handling anyway.
15648   UpdateMarkingForLValueToRValue(Res.get());
15649   return Res;
15650 }
15651 
15652 void Sema::CleanupVarDeclMarking() {
15653   for (Expr *E : MaybeODRUseExprs) {
15654     VarDecl *Var;
15655     SourceLocation Loc;
15656     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15657       Var = cast<VarDecl>(DRE->getDecl());
15658       Loc = DRE->getLocation();
15659     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15660       Var = cast<VarDecl>(ME->getMemberDecl());
15661       Loc = ME->getMemberLoc();
15662     } else {
15663       llvm_unreachable("Unexpected expression");
15664     }
15665 
15666     MarkVarDeclODRUsed(Var, Loc, *this,
15667                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15668   }
15669 
15670   MaybeODRUseExprs.clear();
15671 }
15672 
15673 
15674 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15675                                     VarDecl *Var, Expr *E) {
15676   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15677          "Invalid Expr argument to DoMarkVarDeclReferenced");
15678   Var->setReferenced();
15679 
15680   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15681 
15682   bool OdrUseContext = isOdrUseContext(SemaRef);
15683   bool UsableInConstantExpr =
15684       Var->isUsableInConstantExpressions(SemaRef.Context);
15685   bool NeedDefinition =
15686       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15687 
15688   VarTemplateSpecializationDecl *VarSpec =
15689       dyn_cast<VarTemplateSpecializationDecl>(Var);
15690   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15691          "Can't instantiate a partial template specialization.");
15692 
15693   // If this might be a member specialization of a static data member, check
15694   // the specialization is visible. We already did the checks for variable
15695   // template specializations when we created them.
15696   if (NeedDefinition && TSK != TSK_Undeclared &&
15697       !isa<VarTemplateSpecializationDecl>(Var))
15698     SemaRef.checkSpecializationVisibility(Loc, Var);
15699 
15700   // Perform implicit instantiation of static data members, static data member
15701   // templates of class templates, and variable template specializations. Delay
15702   // instantiations of variable templates, except for those that could be used
15703   // in a constant expression.
15704   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15705     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15706     // instantiation declaration if a variable is usable in a constant
15707     // expression (among other cases).
15708     bool TryInstantiating =
15709         TSK == TSK_ImplicitInstantiation ||
15710         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15711 
15712     if (TryInstantiating) {
15713       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15714       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15715       if (FirstInstantiation) {
15716         PointOfInstantiation = Loc;
15717         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15718       }
15719 
15720       bool InstantiationDependent = false;
15721       bool IsNonDependent =
15722           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15723                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15724                   : true;
15725 
15726       // Do not instantiate specializations that are still type-dependent.
15727       if (IsNonDependent) {
15728         if (UsableInConstantExpr) {
15729           // Do not defer instantiations of variables that could be used in a
15730           // constant expression.
15731           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15732         } else if (FirstInstantiation ||
15733                    isa<VarTemplateSpecializationDecl>(Var)) {
15734           // FIXME: For a specialization of a variable template, we don't
15735           // distinguish between "declaration and type implicitly instantiated"
15736           // and "implicit instantiation of definition requested", so we have
15737           // no direct way to avoid enqueueing the pending instantiation
15738           // multiple times.
15739           SemaRef.PendingInstantiations
15740               .push_back(std::make_pair(Var, PointOfInstantiation));
15741         }
15742       }
15743     }
15744   }
15745 
15746   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15747   // the requirements for appearing in a constant expression (5.19) and, if
15748   // it is an object, the lvalue-to-rvalue conversion (4.1)
15749   // is immediately applied."  We check the first part here, and
15750   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15751   // Note that we use the C++11 definition everywhere because nothing in
15752   // C++03 depends on whether we get the C++03 version correct. The second
15753   // part does not apply to references, since they are not objects.
15754   if (OdrUseContext && E &&
15755       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15756     // A reference initialized by a constant expression can never be
15757     // odr-used, so simply ignore it.
15758     if (!Var->getType()->isReferenceType() ||
15759         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15760       SemaRef.MaybeODRUseExprs.insert(E);
15761   } else if (OdrUseContext) {
15762     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15763                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15764   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15765     // If this is a dependent context, we don't need to mark variables as
15766     // odr-used, but we may still need to track them for lambda capture.
15767     // FIXME: Do we also need to do this inside dependent typeid expressions
15768     // (which are modeled as unevaluated at this point)?
15769     const bool RefersToEnclosingScope =
15770         (SemaRef.CurContext != Var->getDeclContext() &&
15771          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15772     if (RefersToEnclosingScope) {
15773       LambdaScopeInfo *const LSI =
15774           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15775       if (LSI && (!LSI->CallOperator ||
15776                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15777         // If a variable could potentially be odr-used, defer marking it so
15778         // until we finish analyzing the full expression for any
15779         // lvalue-to-rvalue
15780         // or discarded value conversions that would obviate odr-use.
15781         // Add it to the list of potential captures that will be analyzed
15782         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15783         // unless the variable is a reference that was initialized by a constant
15784         // expression (this will never need to be captured or odr-used).
15785         assert(E && "Capture variable should be used in an expression.");
15786         if (!Var->getType()->isReferenceType() ||
15787             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15788           LSI->addPotentialCapture(E->IgnoreParens());
15789       }
15790     }
15791   }
15792 }
15793 
15794 /// Mark a variable referenced, and check whether it is odr-used
15795 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15796 /// used directly for normal expressions referring to VarDecl.
15797 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15798   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15799 }
15800 
15801 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15802                                Decl *D, Expr *E, bool MightBeOdrUse) {
15803   if (SemaRef.isInOpenMPDeclareTargetContext())
15804     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15805 
15806   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15807     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15808     return;
15809   }
15810 
15811   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15812 
15813   // If this is a call to a method via a cast, also mark the method in the
15814   // derived class used in case codegen can devirtualize the call.
15815   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15816   if (!ME)
15817     return;
15818   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15819   if (!MD)
15820     return;
15821   // Only attempt to devirtualize if this is truly a virtual call.
15822   bool IsVirtualCall = MD->isVirtual() &&
15823                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15824   if (!IsVirtualCall)
15825     return;
15826 
15827   // If it's possible to devirtualize the call, mark the called function
15828   // referenced.
15829   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15830       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15831   if (DM)
15832     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15833 }
15834 
15835 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15836 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15837   // TODO: update this with DR# once a defect report is filed.
15838   // C++11 defect. The address of a pure member should not be an ODR use, even
15839   // if it's a qualified reference.
15840   bool OdrUse = true;
15841   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15842     if (Method->isVirtual() &&
15843         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15844       OdrUse = false;
15845   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15846 }
15847 
15848 /// Perform reference-marking and odr-use handling for a MemberExpr.
15849 void Sema::MarkMemberReferenced(MemberExpr *E) {
15850   // C++11 [basic.def.odr]p2:
15851   //   A non-overloaded function whose name appears as a potentially-evaluated
15852   //   expression or a member of a set of candidate functions, if selected by
15853   //   overload resolution when referred to from a potentially-evaluated
15854   //   expression, is odr-used, unless it is a pure virtual function and its
15855   //   name is not explicitly qualified.
15856   bool MightBeOdrUse = true;
15857   if (E->performsVirtualDispatch(getLangOpts())) {
15858     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15859       if (Method->isPure())
15860         MightBeOdrUse = false;
15861   }
15862   SourceLocation Loc =
15863       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15864   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15865 }
15866 
15867 /// Perform marking for a reference to an arbitrary declaration.  It
15868 /// marks the declaration referenced, and performs odr-use checking for
15869 /// functions and variables. This method should not be used when building a
15870 /// normal expression which refers to a variable.
15871 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15872                                  bool MightBeOdrUse) {
15873   if (MightBeOdrUse) {
15874     if (auto *VD = dyn_cast<VarDecl>(D)) {
15875       MarkVariableReferenced(Loc, VD);
15876       return;
15877     }
15878   }
15879   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15880     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15881     return;
15882   }
15883   D->setReferenced();
15884 }
15885 
15886 namespace {
15887   // Mark all of the declarations used by a type as referenced.
15888   // FIXME: Not fully implemented yet! We need to have a better understanding
15889   // of when we're entering a context we should not recurse into.
15890   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15891   // TreeTransforms rebuilding the type in a new context. Rather than
15892   // duplicating the TreeTransform logic, we should consider reusing it here.
15893   // Currently that causes problems when rebuilding LambdaExprs.
15894   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15895     Sema &S;
15896     SourceLocation Loc;
15897 
15898   public:
15899     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15900 
15901     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15902 
15903     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15904   };
15905 }
15906 
15907 bool MarkReferencedDecls::TraverseTemplateArgument(
15908     const TemplateArgument &Arg) {
15909   {
15910     // A non-type template argument is a constant-evaluated context.
15911     EnterExpressionEvaluationContext Evaluated(
15912         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15913     if (Arg.getKind() == TemplateArgument::Declaration) {
15914       if (Decl *D = Arg.getAsDecl())
15915         S.MarkAnyDeclReferenced(Loc, D, true);
15916     } else if (Arg.getKind() == TemplateArgument::Expression) {
15917       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15918     }
15919   }
15920 
15921   return Inherited::TraverseTemplateArgument(Arg);
15922 }
15923 
15924 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15925   MarkReferencedDecls Marker(*this, Loc);
15926   Marker.TraverseType(T);
15927 }
15928 
15929 namespace {
15930   /// Helper class that marks all of the declarations referenced by
15931   /// potentially-evaluated subexpressions as "referenced".
15932   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15933     Sema &S;
15934     bool SkipLocalVariables;
15935 
15936   public:
15937     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15938 
15939     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15940       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15941 
15942     void VisitDeclRefExpr(DeclRefExpr *E) {
15943       // If we were asked not to visit local variables, don't.
15944       if (SkipLocalVariables) {
15945         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15946           if (VD->hasLocalStorage())
15947             return;
15948       }
15949 
15950       S.MarkDeclRefReferenced(E);
15951     }
15952 
15953     void VisitMemberExpr(MemberExpr *E) {
15954       S.MarkMemberReferenced(E);
15955       Inherited::VisitMemberExpr(E);
15956     }
15957 
15958     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15959       S.MarkFunctionReferenced(
15960           E->getBeginLoc(),
15961           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15962       Visit(E->getSubExpr());
15963     }
15964 
15965     void VisitCXXNewExpr(CXXNewExpr *E) {
15966       if (E->getOperatorNew())
15967         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
15968       if (E->getOperatorDelete())
15969         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15970       Inherited::VisitCXXNewExpr(E);
15971     }
15972 
15973     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15974       if (E->getOperatorDelete())
15975         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15976       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15977       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15978         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15979         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
15980       }
15981 
15982       Inherited::VisitCXXDeleteExpr(E);
15983     }
15984 
15985     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15986       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
15987       Inherited::VisitCXXConstructExpr(E);
15988     }
15989 
15990     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15991       Visit(E->getExpr());
15992     }
15993 
15994     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15995       Inherited::VisitImplicitCastExpr(E);
15996 
15997       if (E->getCastKind() == CK_LValueToRValue)
15998         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15999     }
16000   };
16001 }
16002 
16003 /// Mark any declarations that appear within this expression or any
16004 /// potentially-evaluated subexpressions as "referenced".
16005 ///
16006 /// \param SkipLocalVariables If true, don't mark local variables as
16007 /// 'referenced'.
16008 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16009                                             bool SkipLocalVariables) {
16010   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16011 }
16012 
16013 /// Emit a diagnostic that describes an effect on the run-time behavior
16014 /// of the program being compiled.
16015 ///
16016 /// This routine emits the given diagnostic when the code currently being
16017 /// type-checked is "potentially evaluated", meaning that there is a
16018 /// possibility that the code will actually be executable. Code in sizeof()
16019 /// expressions, code used only during overload resolution, etc., are not
16020 /// potentially evaluated. This routine will suppress such diagnostics or,
16021 /// in the absolutely nutty case of potentially potentially evaluated
16022 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16023 /// later.
16024 ///
16025 /// This routine should be used for all diagnostics that describe the run-time
16026 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16027 /// Failure to do so will likely result in spurious diagnostics or failures
16028 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16029 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16030                                const PartialDiagnostic &PD) {
16031   switch (ExprEvalContexts.back().Context) {
16032   case ExpressionEvaluationContext::Unevaluated:
16033   case ExpressionEvaluationContext::UnevaluatedList:
16034   case ExpressionEvaluationContext::UnevaluatedAbstract:
16035   case ExpressionEvaluationContext::DiscardedStatement:
16036     // The argument will never be evaluated, so don't complain.
16037     break;
16038 
16039   case ExpressionEvaluationContext::ConstantEvaluated:
16040     // Relevant diagnostics should be produced by constant evaluation.
16041     break;
16042 
16043   case ExpressionEvaluationContext::PotentiallyEvaluated:
16044   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16045     if (Statement && getCurFunctionOrMethodDecl()) {
16046       FunctionScopes.back()->PossiblyUnreachableDiags.
16047         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
16048       return true;
16049     }
16050 
16051     // The initializer of a constexpr variable or of the first declaration of a
16052     // static data member is not syntactically a constant evaluated constant,
16053     // but nonetheless is always required to be a constant expression, so we
16054     // can skip diagnosing.
16055     // FIXME: Using the mangling context here is a hack.
16056     if (auto *VD = dyn_cast_or_null<VarDecl>(
16057             ExprEvalContexts.back().ManglingContextDecl)) {
16058       if (VD->isConstexpr() ||
16059           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16060         break;
16061       // FIXME: For any other kind of variable, we should build a CFG for its
16062       // initializer and check whether the context in question is reachable.
16063     }
16064 
16065     Diag(Loc, PD);
16066     return true;
16067   }
16068 
16069   return false;
16070 }
16071 
16072 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16073                                CallExpr *CE, FunctionDecl *FD) {
16074   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16075     return false;
16076 
16077   // If we're inside a decltype's expression, don't check for a valid return
16078   // type or construct temporaries until we know whether this is the last call.
16079   if (ExprEvalContexts.back().ExprContext ==
16080       ExpressionEvaluationContextRecord::EK_Decltype) {
16081     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16082     return false;
16083   }
16084 
16085   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16086     FunctionDecl *FD;
16087     CallExpr *CE;
16088 
16089   public:
16090     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16091       : FD(FD), CE(CE) { }
16092 
16093     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16094       if (!FD) {
16095         S.Diag(Loc, diag::err_call_incomplete_return)
16096           << T << CE->getSourceRange();
16097         return;
16098       }
16099 
16100       S.Diag(Loc, diag::err_call_function_incomplete_return)
16101         << CE->getSourceRange() << FD->getDeclName() << T;
16102       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16103           << FD->getDeclName();
16104     }
16105   } Diagnoser(FD, CE);
16106 
16107   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16108     return true;
16109 
16110   return false;
16111 }
16112 
16113 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16114 // will prevent this condition from triggering, which is what we want.
16115 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16116   SourceLocation Loc;
16117 
16118   unsigned diagnostic = diag::warn_condition_is_assignment;
16119   bool IsOrAssign = false;
16120 
16121   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16122     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16123       return;
16124 
16125     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16126 
16127     // Greylist some idioms by putting them into a warning subcategory.
16128     if (ObjCMessageExpr *ME
16129           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16130       Selector Sel = ME->getSelector();
16131 
16132       // self = [<foo> init...]
16133       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16134         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16135 
16136       // <foo> = [<bar> nextObject]
16137       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16138         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16139     }
16140 
16141     Loc = Op->getOperatorLoc();
16142   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16143     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16144       return;
16145 
16146     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16147     Loc = Op->getOperatorLoc();
16148   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16149     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16150   else {
16151     // Not an assignment.
16152     return;
16153   }
16154 
16155   Diag(Loc, diagnostic) << E->getSourceRange();
16156 
16157   SourceLocation Open = E->getBeginLoc();
16158   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16159   Diag(Loc, diag::note_condition_assign_silence)
16160         << FixItHint::CreateInsertion(Open, "(")
16161         << FixItHint::CreateInsertion(Close, ")");
16162 
16163   if (IsOrAssign)
16164     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16165       << FixItHint::CreateReplacement(Loc, "!=");
16166   else
16167     Diag(Loc, diag::note_condition_assign_to_comparison)
16168       << FixItHint::CreateReplacement(Loc, "==");
16169 }
16170 
16171 /// Redundant parentheses over an equality comparison can indicate
16172 /// that the user intended an assignment used as condition.
16173 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16174   // Don't warn if the parens came from a macro.
16175   SourceLocation parenLoc = ParenE->getBeginLoc();
16176   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16177     return;
16178   // Don't warn for dependent expressions.
16179   if (ParenE->isTypeDependent())
16180     return;
16181 
16182   Expr *E = ParenE->IgnoreParens();
16183 
16184   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16185     if (opE->getOpcode() == BO_EQ &&
16186         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16187                                                            == Expr::MLV_Valid) {
16188       SourceLocation Loc = opE->getOperatorLoc();
16189 
16190       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16191       SourceRange ParenERange = ParenE->getSourceRange();
16192       Diag(Loc, diag::note_equality_comparison_silence)
16193         << FixItHint::CreateRemoval(ParenERange.getBegin())
16194         << FixItHint::CreateRemoval(ParenERange.getEnd());
16195       Diag(Loc, diag::note_equality_comparison_to_assign)
16196         << FixItHint::CreateReplacement(Loc, "=");
16197     }
16198 }
16199 
16200 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16201                                        bool IsConstexpr) {
16202   DiagnoseAssignmentAsCondition(E);
16203   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16204     DiagnoseEqualityWithExtraParens(parenE);
16205 
16206   ExprResult result = CheckPlaceholderExpr(E);
16207   if (result.isInvalid()) return ExprError();
16208   E = result.get();
16209 
16210   if (!E->isTypeDependent()) {
16211     if (getLangOpts().CPlusPlus)
16212       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16213 
16214     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16215     if (ERes.isInvalid())
16216       return ExprError();
16217     E = ERes.get();
16218 
16219     QualType T = E->getType();
16220     if (!T->isScalarType()) { // C99 6.8.4.1p1
16221       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16222         << T << E->getSourceRange();
16223       return ExprError();
16224     }
16225     CheckBoolLikeConversion(E, Loc);
16226   }
16227 
16228   return E;
16229 }
16230 
16231 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16232                                            Expr *SubExpr, ConditionKind CK) {
16233   // Empty conditions are valid in for-statements.
16234   if (!SubExpr)
16235     return ConditionResult();
16236 
16237   ExprResult Cond;
16238   switch (CK) {
16239   case ConditionKind::Boolean:
16240     Cond = CheckBooleanCondition(Loc, SubExpr);
16241     break;
16242 
16243   case ConditionKind::ConstexprIf:
16244     Cond = CheckBooleanCondition(Loc, SubExpr, true);
16245     break;
16246 
16247   case ConditionKind::Switch:
16248     Cond = CheckSwitchCondition(Loc, SubExpr);
16249     break;
16250   }
16251   if (Cond.isInvalid())
16252     return ConditionError();
16253 
16254   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16255   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16256   if (!FullExpr.get())
16257     return ConditionError();
16258 
16259   return ConditionResult(*this, nullptr, FullExpr,
16260                          CK == ConditionKind::ConstexprIf);
16261 }
16262 
16263 namespace {
16264   /// A visitor for rebuilding a call to an __unknown_any expression
16265   /// to have an appropriate type.
16266   struct RebuildUnknownAnyFunction
16267     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16268 
16269     Sema &S;
16270 
16271     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16272 
16273     ExprResult VisitStmt(Stmt *S) {
16274       llvm_unreachable("unexpected statement!");
16275     }
16276 
16277     ExprResult VisitExpr(Expr *E) {
16278       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16279         << E->getSourceRange();
16280       return ExprError();
16281     }
16282 
16283     /// Rebuild an expression which simply semantically wraps another
16284     /// expression which it shares the type and value kind of.
16285     template <class T> ExprResult rebuildSugarExpr(T *E) {
16286       ExprResult SubResult = Visit(E->getSubExpr());
16287       if (SubResult.isInvalid()) return ExprError();
16288 
16289       Expr *SubExpr = SubResult.get();
16290       E->setSubExpr(SubExpr);
16291       E->setType(SubExpr->getType());
16292       E->setValueKind(SubExpr->getValueKind());
16293       assert(E->getObjectKind() == OK_Ordinary);
16294       return E;
16295     }
16296 
16297     ExprResult VisitParenExpr(ParenExpr *E) {
16298       return rebuildSugarExpr(E);
16299     }
16300 
16301     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16302       return rebuildSugarExpr(E);
16303     }
16304 
16305     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16306       ExprResult SubResult = Visit(E->getSubExpr());
16307       if (SubResult.isInvalid()) return ExprError();
16308 
16309       Expr *SubExpr = SubResult.get();
16310       E->setSubExpr(SubExpr);
16311       E->setType(S.Context.getPointerType(SubExpr->getType()));
16312       assert(E->getValueKind() == VK_RValue);
16313       assert(E->getObjectKind() == OK_Ordinary);
16314       return E;
16315     }
16316 
16317     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16318       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16319 
16320       E->setType(VD->getType());
16321 
16322       assert(E->getValueKind() == VK_RValue);
16323       if (S.getLangOpts().CPlusPlus &&
16324           !(isa<CXXMethodDecl>(VD) &&
16325             cast<CXXMethodDecl>(VD)->isInstance()))
16326         E->setValueKind(VK_LValue);
16327 
16328       return E;
16329     }
16330 
16331     ExprResult VisitMemberExpr(MemberExpr *E) {
16332       return resolveDecl(E, E->getMemberDecl());
16333     }
16334 
16335     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16336       return resolveDecl(E, E->getDecl());
16337     }
16338   };
16339 }
16340 
16341 /// Given a function expression of unknown-any type, try to rebuild it
16342 /// to have a function type.
16343 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16344   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16345   if (Result.isInvalid()) return ExprError();
16346   return S.DefaultFunctionArrayConversion(Result.get());
16347 }
16348 
16349 namespace {
16350   /// A visitor for rebuilding an expression of type __unknown_anytype
16351   /// into one which resolves the type directly on the referring
16352   /// expression.  Strict preservation of the original source
16353   /// structure is not a goal.
16354   struct RebuildUnknownAnyExpr
16355     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16356 
16357     Sema &S;
16358 
16359     /// The current destination type.
16360     QualType DestType;
16361 
16362     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16363       : S(S), DestType(CastType) {}
16364 
16365     ExprResult VisitStmt(Stmt *S) {
16366       llvm_unreachable("unexpected statement!");
16367     }
16368 
16369     ExprResult VisitExpr(Expr *E) {
16370       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16371         << E->getSourceRange();
16372       return ExprError();
16373     }
16374 
16375     ExprResult VisitCallExpr(CallExpr *E);
16376     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16377 
16378     /// Rebuild an expression which simply semantically wraps another
16379     /// expression which it shares the type and value kind of.
16380     template <class T> ExprResult rebuildSugarExpr(T *E) {
16381       ExprResult SubResult = Visit(E->getSubExpr());
16382       if (SubResult.isInvalid()) return ExprError();
16383       Expr *SubExpr = SubResult.get();
16384       E->setSubExpr(SubExpr);
16385       E->setType(SubExpr->getType());
16386       E->setValueKind(SubExpr->getValueKind());
16387       assert(E->getObjectKind() == OK_Ordinary);
16388       return E;
16389     }
16390 
16391     ExprResult VisitParenExpr(ParenExpr *E) {
16392       return rebuildSugarExpr(E);
16393     }
16394 
16395     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16396       return rebuildSugarExpr(E);
16397     }
16398 
16399     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16400       const PointerType *Ptr = DestType->getAs<PointerType>();
16401       if (!Ptr) {
16402         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16403           << E->getSourceRange();
16404         return ExprError();
16405       }
16406 
16407       if (isa<CallExpr>(E->getSubExpr())) {
16408         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16409           << E->getSourceRange();
16410         return ExprError();
16411       }
16412 
16413       assert(E->getValueKind() == VK_RValue);
16414       assert(E->getObjectKind() == OK_Ordinary);
16415       E->setType(DestType);
16416 
16417       // Build the sub-expression as if it were an object of the pointee type.
16418       DestType = Ptr->getPointeeType();
16419       ExprResult SubResult = Visit(E->getSubExpr());
16420       if (SubResult.isInvalid()) return ExprError();
16421       E->setSubExpr(SubResult.get());
16422       return E;
16423     }
16424 
16425     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16426 
16427     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16428 
16429     ExprResult VisitMemberExpr(MemberExpr *E) {
16430       return resolveDecl(E, E->getMemberDecl());
16431     }
16432 
16433     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16434       return resolveDecl(E, E->getDecl());
16435     }
16436   };
16437 }
16438 
16439 /// Rebuilds a call expression which yielded __unknown_anytype.
16440 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16441   Expr *CalleeExpr = E->getCallee();
16442 
16443   enum FnKind {
16444     FK_MemberFunction,
16445     FK_FunctionPointer,
16446     FK_BlockPointer
16447   };
16448 
16449   FnKind Kind;
16450   QualType CalleeType = CalleeExpr->getType();
16451   if (CalleeType == S.Context.BoundMemberTy) {
16452     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16453     Kind = FK_MemberFunction;
16454     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16455   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16456     CalleeType = Ptr->getPointeeType();
16457     Kind = FK_FunctionPointer;
16458   } else {
16459     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16460     Kind = FK_BlockPointer;
16461   }
16462   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16463 
16464   // Verify that this is a legal result type of a function.
16465   if (DestType->isArrayType() || DestType->isFunctionType()) {
16466     unsigned diagID = diag::err_func_returning_array_function;
16467     if (Kind == FK_BlockPointer)
16468       diagID = diag::err_block_returning_array_function;
16469 
16470     S.Diag(E->getExprLoc(), diagID)
16471       << DestType->isFunctionType() << DestType;
16472     return ExprError();
16473   }
16474 
16475   // Otherwise, go ahead and set DestType as the call's result.
16476   E->setType(DestType.getNonLValueExprType(S.Context));
16477   E->setValueKind(Expr::getValueKindForType(DestType));
16478   assert(E->getObjectKind() == OK_Ordinary);
16479 
16480   // Rebuild the function type, replacing the result type with DestType.
16481   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16482   if (Proto) {
16483     // __unknown_anytype(...) is a special case used by the debugger when
16484     // it has no idea what a function's signature is.
16485     //
16486     // We want to build this call essentially under the K&R
16487     // unprototyped rules, but making a FunctionNoProtoType in C++
16488     // would foul up all sorts of assumptions.  However, we cannot
16489     // simply pass all arguments as variadic arguments, nor can we
16490     // portably just call the function under a non-variadic type; see
16491     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16492     // However, it turns out that in practice it is generally safe to
16493     // call a function declared as "A foo(B,C,D);" under the prototype
16494     // "A foo(B,C,D,...);".  The only known exception is with the
16495     // Windows ABI, where any variadic function is implicitly cdecl
16496     // regardless of its normal CC.  Therefore we change the parameter
16497     // types to match the types of the arguments.
16498     //
16499     // This is a hack, but it is far superior to moving the
16500     // corresponding target-specific code from IR-gen to Sema/AST.
16501 
16502     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16503     SmallVector<QualType, 8> ArgTypes;
16504     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16505       ArgTypes.reserve(E->getNumArgs());
16506       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16507         Expr *Arg = E->getArg(i);
16508         QualType ArgType = Arg->getType();
16509         if (E->isLValue()) {
16510           ArgType = S.Context.getLValueReferenceType(ArgType);
16511         } else if (E->isXValue()) {
16512           ArgType = S.Context.getRValueReferenceType(ArgType);
16513         }
16514         ArgTypes.push_back(ArgType);
16515       }
16516       ParamTypes = ArgTypes;
16517     }
16518     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16519                                          Proto->getExtProtoInfo());
16520   } else {
16521     DestType = S.Context.getFunctionNoProtoType(DestType,
16522                                                 FnType->getExtInfo());
16523   }
16524 
16525   // Rebuild the appropriate pointer-to-function type.
16526   switch (Kind) {
16527   case FK_MemberFunction:
16528     // Nothing to do.
16529     break;
16530 
16531   case FK_FunctionPointer:
16532     DestType = S.Context.getPointerType(DestType);
16533     break;
16534 
16535   case FK_BlockPointer:
16536     DestType = S.Context.getBlockPointerType(DestType);
16537     break;
16538   }
16539 
16540   // Finally, we can recurse.
16541   ExprResult CalleeResult = Visit(CalleeExpr);
16542   if (!CalleeResult.isUsable()) return ExprError();
16543   E->setCallee(CalleeResult.get());
16544 
16545   // Bind a temporary if necessary.
16546   return S.MaybeBindToTemporary(E);
16547 }
16548 
16549 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16550   // Verify that this is a legal result type of a call.
16551   if (DestType->isArrayType() || DestType->isFunctionType()) {
16552     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16553       << DestType->isFunctionType() << DestType;
16554     return ExprError();
16555   }
16556 
16557   // Rewrite the method result type if available.
16558   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16559     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16560     Method->setReturnType(DestType);
16561   }
16562 
16563   // Change the type of the message.
16564   E->setType(DestType.getNonReferenceType());
16565   E->setValueKind(Expr::getValueKindForType(DestType));
16566 
16567   return S.MaybeBindToTemporary(E);
16568 }
16569 
16570 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16571   // The only case we should ever see here is a function-to-pointer decay.
16572   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16573     assert(E->getValueKind() == VK_RValue);
16574     assert(E->getObjectKind() == OK_Ordinary);
16575 
16576     E->setType(DestType);
16577 
16578     // Rebuild the sub-expression as the pointee (function) type.
16579     DestType = DestType->castAs<PointerType>()->getPointeeType();
16580 
16581     ExprResult Result = Visit(E->getSubExpr());
16582     if (!Result.isUsable()) return ExprError();
16583 
16584     E->setSubExpr(Result.get());
16585     return E;
16586   } else if (E->getCastKind() == CK_LValueToRValue) {
16587     assert(E->getValueKind() == VK_RValue);
16588     assert(E->getObjectKind() == OK_Ordinary);
16589 
16590     assert(isa<BlockPointerType>(E->getType()));
16591 
16592     E->setType(DestType);
16593 
16594     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16595     DestType = S.Context.getLValueReferenceType(DestType);
16596 
16597     ExprResult Result = Visit(E->getSubExpr());
16598     if (!Result.isUsable()) return ExprError();
16599 
16600     E->setSubExpr(Result.get());
16601     return E;
16602   } else {
16603     llvm_unreachable("Unhandled cast type!");
16604   }
16605 }
16606 
16607 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16608   ExprValueKind ValueKind = VK_LValue;
16609   QualType Type = DestType;
16610 
16611   // We know how to make this work for certain kinds of decls:
16612 
16613   //  - functions
16614   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16615     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16616       DestType = Ptr->getPointeeType();
16617       ExprResult Result = resolveDecl(E, VD);
16618       if (Result.isInvalid()) return ExprError();
16619       return S.ImpCastExprToType(Result.get(), Type,
16620                                  CK_FunctionToPointerDecay, VK_RValue);
16621     }
16622 
16623     if (!Type->isFunctionType()) {
16624       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16625         << VD << E->getSourceRange();
16626       return ExprError();
16627     }
16628     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16629       // We must match the FunctionDecl's type to the hack introduced in
16630       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16631       // type. See the lengthy commentary in that routine.
16632       QualType FDT = FD->getType();
16633       const FunctionType *FnType = FDT->castAs<FunctionType>();
16634       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16635       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16636       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16637         SourceLocation Loc = FD->getLocation();
16638         FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
16639                                       FD->getDeclContext(),
16640                                       Loc, Loc, FD->getNameInfo().getName(),
16641                                       DestType, FD->getTypeSourceInfo(),
16642                                       SC_None, false/*isInlineSpecified*/,
16643                                       FD->hasPrototype(),
16644                                       false/*isConstexprSpecified*/);
16645 
16646         if (FD->getQualifier())
16647           NewFD->setQualifierInfo(FD->getQualifierLoc());
16648 
16649         SmallVector<ParmVarDecl*, 16> Params;
16650         for (const auto &AI : FT->param_types()) {
16651           ParmVarDecl *Param =
16652             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16653           Param->setScopeInfo(0, Params.size());
16654           Params.push_back(Param);
16655         }
16656         NewFD->setParams(Params);
16657         DRE->setDecl(NewFD);
16658         VD = DRE->getDecl();
16659       }
16660     }
16661 
16662     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16663       if (MD->isInstance()) {
16664         ValueKind = VK_RValue;
16665         Type = S.Context.BoundMemberTy;
16666       }
16667 
16668     // Function references aren't l-values in C.
16669     if (!S.getLangOpts().CPlusPlus)
16670       ValueKind = VK_RValue;
16671 
16672   //  - variables
16673   } else if (isa<VarDecl>(VD)) {
16674     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16675       Type = RefTy->getPointeeType();
16676     } else if (Type->isFunctionType()) {
16677       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16678         << VD << E->getSourceRange();
16679       return ExprError();
16680     }
16681 
16682   //  - nothing else
16683   } else {
16684     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16685       << VD << E->getSourceRange();
16686     return ExprError();
16687   }
16688 
16689   // Modifying the declaration like this is friendly to IR-gen but
16690   // also really dangerous.
16691   VD->setType(DestType);
16692   E->setType(Type);
16693   E->setValueKind(ValueKind);
16694   return E;
16695 }
16696 
16697 /// Check a cast of an unknown-any type.  We intentionally only
16698 /// trigger this for C-style casts.
16699 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16700                                      Expr *CastExpr, CastKind &CastKind,
16701                                      ExprValueKind &VK, CXXCastPath &Path) {
16702   // The type we're casting to must be either void or complete.
16703   if (!CastType->isVoidType() &&
16704       RequireCompleteType(TypeRange.getBegin(), CastType,
16705                           diag::err_typecheck_cast_to_incomplete))
16706     return ExprError();
16707 
16708   // Rewrite the casted expression from scratch.
16709   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16710   if (!result.isUsable()) return ExprError();
16711 
16712   CastExpr = result.get();
16713   VK = CastExpr->getValueKind();
16714   CastKind = CK_NoOp;
16715 
16716   return CastExpr;
16717 }
16718 
16719 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16720   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16721 }
16722 
16723 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16724                                     Expr *arg, QualType &paramType) {
16725   // If the syntactic form of the argument is not an explicit cast of
16726   // any sort, just do default argument promotion.
16727   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16728   if (!castArg) {
16729     ExprResult result = DefaultArgumentPromotion(arg);
16730     if (result.isInvalid()) return ExprError();
16731     paramType = result.get()->getType();
16732     return result;
16733   }
16734 
16735   // Otherwise, use the type that was written in the explicit cast.
16736   assert(!arg->hasPlaceholderType());
16737   paramType = castArg->getTypeAsWritten();
16738 
16739   // Copy-initialize a parameter of that type.
16740   InitializedEntity entity =
16741     InitializedEntity::InitializeParameter(Context, paramType,
16742                                            /*consumed*/ false);
16743   return PerformCopyInitialization(entity, callLoc, arg);
16744 }
16745 
16746 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16747   Expr *orig = E;
16748   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16749   while (true) {
16750     E = E->IgnoreParenImpCasts();
16751     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16752       E = call->getCallee();
16753       diagID = diag::err_uncasted_call_of_unknown_any;
16754     } else {
16755       break;
16756     }
16757   }
16758 
16759   SourceLocation loc;
16760   NamedDecl *d;
16761   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16762     loc = ref->getLocation();
16763     d = ref->getDecl();
16764   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16765     loc = mem->getMemberLoc();
16766     d = mem->getMemberDecl();
16767   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16768     diagID = diag::err_uncasted_call_of_unknown_any;
16769     loc = msg->getSelectorStartLoc();
16770     d = msg->getMethodDecl();
16771     if (!d) {
16772       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16773         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16774         << orig->getSourceRange();
16775       return ExprError();
16776     }
16777   } else {
16778     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16779       << E->getSourceRange();
16780     return ExprError();
16781   }
16782 
16783   S.Diag(loc, diagID) << d << orig->getSourceRange();
16784 
16785   // Never recoverable.
16786   return ExprError();
16787 }
16788 
16789 /// Check for operands with placeholder types and complain if found.
16790 /// Returns ExprError() if there was an error and no recovery was possible.
16791 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16792   if (!getLangOpts().CPlusPlus) {
16793     // C cannot handle TypoExpr nodes on either side of a binop because it
16794     // doesn't handle dependent types properly, so make sure any TypoExprs have
16795     // been dealt with before checking the operands.
16796     ExprResult Result = CorrectDelayedTyposInExpr(E);
16797     if (!Result.isUsable()) return ExprError();
16798     E = Result.get();
16799   }
16800 
16801   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16802   if (!placeholderType) return E;
16803 
16804   switch (placeholderType->getKind()) {
16805 
16806   // Overloaded expressions.
16807   case BuiltinType::Overload: {
16808     // Try to resolve a single function template specialization.
16809     // This is obligatory.
16810     ExprResult Result = E;
16811     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16812       return Result;
16813 
16814     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16815     // leaves Result unchanged on failure.
16816     Result = E;
16817     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16818       return Result;
16819 
16820     // If that failed, try to recover with a call.
16821     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16822                          /*complain*/ true);
16823     return Result;
16824   }
16825 
16826   // Bound member functions.
16827   case BuiltinType::BoundMember: {
16828     ExprResult result = E;
16829     const Expr *BME = E->IgnoreParens();
16830     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16831     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16832     if (isa<CXXPseudoDestructorExpr>(BME)) {
16833       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16834     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16835       if (ME->getMemberNameInfo().getName().getNameKind() ==
16836           DeclarationName::CXXDestructorName)
16837         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16838     }
16839     tryToRecoverWithCall(result, PD,
16840                          /*complain*/ true);
16841     return result;
16842   }
16843 
16844   // ARC unbridged casts.
16845   case BuiltinType::ARCUnbridgedCast: {
16846     Expr *realCast = stripARCUnbridgedCast(E);
16847     diagnoseARCUnbridgedCast(realCast);
16848     return realCast;
16849   }
16850 
16851   // Expressions of unknown type.
16852   case BuiltinType::UnknownAny:
16853     return diagnoseUnknownAnyExpr(*this, E);
16854 
16855   // Pseudo-objects.
16856   case BuiltinType::PseudoObject:
16857     return checkPseudoObjectRValue(E);
16858 
16859   case BuiltinType::BuiltinFn: {
16860     // Accept __noop without parens by implicitly converting it to a call expr.
16861     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16862     if (DRE) {
16863       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16864       if (FD->getBuiltinID() == Builtin::BI__noop) {
16865         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16866                               CK_BuiltinFnToFnPtr)
16867                 .get();
16868         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16869                                 VK_RValue, SourceLocation());
16870       }
16871     }
16872 
16873     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16874     return ExprError();
16875   }
16876 
16877   // Expressions of unknown type.
16878   case BuiltinType::OMPArraySection:
16879     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16880     return ExprError();
16881 
16882   // Everything else should be impossible.
16883 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16884   case BuiltinType::Id:
16885 #include "clang/Basic/OpenCLImageTypes.def"
16886 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16887   case BuiltinType::Id:
16888 #include "clang/Basic/OpenCLExtensionTypes.def"
16889 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16890 #define PLACEHOLDER_TYPE(Id, SingletonId)
16891 #include "clang/AST/BuiltinTypes.def"
16892     break;
16893   }
16894 
16895   llvm_unreachable("invalid placeholder type!");
16896 }
16897 
16898 bool Sema::CheckCaseExpression(Expr *E) {
16899   if (E->isTypeDependent())
16900     return true;
16901   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16902     return E->getType()->isIntegralOrEnumerationType();
16903   return false;
16904 }
16905 
16906 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16907 ExprResult
16908 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16909   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16910          "Unknown Objective-C Boolean value!");
16911   QualType BoolT = Context.ObjCBuiltinBoolTy;
16912   if (!Context.getBOOLDecl()) {
16913     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16914                         Sema::LookupOrdinaryName);
16915     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16916       NamedDecl *ND = Result.getFoundDecl();
16917       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16918         Context.setBOOLDecl(TD);
16919     }
16920   }
16921   if (Context.getBOOLDecl())
16922     BoolT = Context.getBOOLType();
16923   return new (Context)
16924       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16925 }
16926 
16927 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16928     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16929     SourceLocation RParen) {
16930 
16931   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16932 
16933   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16934                            [&](const AvailabilitySpec &Spec) {
16935                              return Spec.getPlatform() == Platform;
16936                            });
16937 
16938   VersionTuple Version;
16939   if (Spec != AvailSpecs.end())
16940     Version = Spec->getVersion();
16941 
16942   // The use of `@available` in the enclosing function should be analyzed to
16943   // warn when it's used inappropriately (i.e. not if(@available)).
16944   if (getCurFunctionOrMethodDecl())
16945     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16946   else if (getCurBlock() || getCurLambda())
16947     getCurFunction()->HasPotentialAvailabilityViolations = true;
16948 
16949   return new (Context)
16950       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16951 }
16952