1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/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 
70   // See if this function is unavailable.
71   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
72       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
73     return false;
74 
75   return true;
76 }
77 
78 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
79   // Warn if this is used but marked unused.
80   if (const auto *A = D->getAttr<UnusedAttr>()) {
81     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
82     // should diagnose them.
83     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
84         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
85       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
86       if (DC && !DC->hasAttr<UnusedAttr>())
87         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
88     }
89   }
90 }
91 
92 /// Emit a note explaining that this function is deleted.
93 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
94   assert(Decl->isDeleted());
95 
96   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
97 
98   if (Method && Method->isDeleted() && Method->isDefaulted()) {
99     // If the method was explicitly defaulted, point at that declaration.
100     if (!Method->isImplicit())
101       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
102 
103     // Try to diagnose why this special member function was implicitly
104     // deleted. This might fail, if that reason no longer applies.
105     CXXSpecialMember CSM = getSpecialMember(Method);
106     if (CSM != CXXInvalid)
107       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
108 
109     return;
110   }
111 
112   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
113   if (Ctor && Ctor->isInheritingConstructor())
114     return NoteDeletedInheritingConstructor(Ctor);
115 
116   Diag(Decl->getLocation(), diag::note_availability_specified_here)
117     << Decl << true;
118 }
119 
120 /// Determine whether a FunctionDecl was ever declared with an
121 /// explicit storage class.
122 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
123   for (auto I : D->redecls()) {
124     if (I->getStorageClass() != SC_None)
125       return true;
126   }
127   return false;
128 }
129 
130 /// Check whether we're in an extern inline function and referring to a
131 /// variable or function with internal linkage (C11 6.7.4p3).
132 ///
133 /// This is only a warning because we used to silently accept this code, but
134 /// in many cases it will not behave correctly. This is not enabled in C++ mode
135 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
136 /// and so while there may still be user mistakes, most of the time we can't
137 /// prove that there are errors.
138 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
139                                                       const NamedDecl *D,
140                                                       SourceLocation Loc) {
141   // This is disabled under C++; there are too many ways for this to fire in
142   // contexts where the warning is a false positive, or where it is technically
143   // correct but benign.
144   if (S.getLangOpts().CPlusPlus)
145     return;
146 
147   // Check if this is an inlined function or method.
148   FunctionDecl *Current = S.getCurFunctionDecl();
149   if (!Current)
150     return;
151   if (!Current->isInlined())
152     return;
153   if (!Current->isExternallyVisible())
154     return;
155 
156   // Check if the decl has internal linkage.
157   if (D->getFormalLinkage() != InternalLinkage)
158     return;
159 
160   // Downgrade from ExtWarn to Extension if
161   //  (1) the supposedly external inline function is in the main file,
162   //      and probably won't be included anywhere else.
163   //  (2) the thing we're referencing is a pure function.
164   //  (3) the thing we're referencing is another inline function.
165   // This last can give us false negatives, but it's better than warning on
166   // wrappers for simple C library functions.
167   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
168   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
169   if (!DowngradeWarning && UsedFn)
170     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
171 
172   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
173                                : diag::ext_internal_in_extern_inline)
174     << /*IsVar=*/!UsedFn << D;
175 
176   S.MaybeSuggestAddingStaticToDecl(Current);
177 
178   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
179       << D;
180 }
181 
182 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
183   const FunctionDecl *First = Cur->getFirstDecl();
184 
185   // Suggest "static" on the function, if possible.
186   if (!hasAnyExplicitStorageClass(First)) {
187     SourceLocation DeclBegin = First->getSourceRange().getBegin();
188     Diag(DeclBegin, diag::note_convert_inline_to_static)
189       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
190   }
191 }
192 
193 /// Determine whether the use of this declaration is valid, and
194 /// emit any corresponding diagnostics.
195 ///
196 /// This routine diagnoses various problems with referencing
197 /// declarations that can occur when using a declaration. For example,
198 /// it might warn if a deprecated or unavailable declaration is being
199 /// used, or produce an error (and return true) if a C++0x deleted
200 /// function is being used.
201 ///
202 /// \returns true if there was an error (this declaration cannot be
203 /// referenced), false otherwise.
204 ///
205 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
206                              const ObjCInterfaceDecl *UnknownObjCClass,
207                              bool ObjCPropertyAccess,
208                              bool AvoidPartialAvailabilityChecks) {
209   SourceLocation Loc = Locs.front();
210   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
211     // If there were any diagnostics suppressed by template argument deduction,
212     // emit them now.
213     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
214     if (Pos != SuppressedDiagnostics.end()) {
215       for (const PartialDiagnosticAt &Suppressed : Pos->second)
216         Diag(Suppressed.first, Suppressed.second);
217 
218       // Clear out the list of suppressed diagnostics, so that we don't emit
219       // them again for this specialization. However, we don't obsolete this
220       // entry from the table, because we want to avoid ever emitting these
221       // diagnostics again.
222       Pos->second.clear();
223     }
224 
225     // C++ [basic.start.main]p3:
226     //   The function 'main' shall not be used within a program.
227     if (cast<FunctionDecl>(D)->isMain())
228       Diag(Loc, diag::ext_main_used);
229   }
230 
231   // See if this is an auto-typed variable whose initializer we are parsing.
232   if (ParsingInitForAutoVars.count(D)) {
233     if (isa<BindingDecl>(D)) {
234       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
235         << D->getDeclName();
236     } else {
237       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
238         << D->getDeclName() << cast<VarDecl>(D)->getType();
239     }
240     return true;
241   }
242 
243   // See if this is a deleted function.
244   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245     if (FD->isDeleted()) {
246       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
247       if (Ctor && Ctor->isInheritingConstructor())
248         Diag(Loc, diag::err_deleted_inherited_ctor_use)
249             << Ctor->getParent()
250             << Ctor->getInheritedConstructor().getConstructor()->getParent();
251       else
252         Diag(Loc, diag::err_deleted_function_use);
253       NoteDeletedFunction(FD);
254       return true;
255     }
256 
257     // If the function has a deduced return type, and we can't deduce it,
258     // then we can't use it either.
259     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
260         DeduceReturnType(FD, Loc))
261       return true;
262 
263     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
264       return true;
265   }
266 
267   auto getReferencedObjCProp = [](const NamedDecl *D) ->
268                                       const ObjCPropertyDecl * {
269     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
270       return MD->findPropertyDecl();
271     return nullptr;
272   };
273   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
274     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
275       return true;
276   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
277       return true;
278   }
279 
280   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
281   // Only the variables omp_in and omp_out are allowed in the combiner.
282   // Only the variables omp_priv and omp_orig are allowed in the
283   // initializer-clause.
284   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
285   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
286       isa<VarDecl>(D)) {
287     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
288         << getCurFunction()->HasOMPDeclareReductionCombiner;
289     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
290     return true;
291   }
292 
293   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
294                              AvoidPartialAvailabilityChecks);
295 
296   DiagnoseUnusedOfDecl(*this, D, Loc);
297 
298   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
299 
300   return false;
301 }
302 
303 /// Retrieve the message suffix that should be added to a
304 /// diagnostic complaining about the given function being deleted or
305 /// unavailable.
306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
307   std::string Message;
308   if (FD->getAvailability(&Message))
309     return ": " + Message;
310 
311   return std::string();
312 }
313 
314 /// DiagnoseSentinelCalls - This routine checks whether a call or
315 /// message-send is to a declaration with the sentinel attribute, and
316 /// if so, it checks that the requirements of the sentinel are
317 /// satisfied.
318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
319                                  ArrayRef<Expr *> Args) {
320   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
321   if (!attr)
322     return;
323 
324   // The number of formal parameters of the declaration.
325   unsigned numFormalParams;
326 
327   // The kind of declaration.  This is also an index into a %select in
328   // the diagnostic.
329   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
330 
331   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
332     numFormalParams = MD->param_size();
333     calleeType = CT_Method;
334   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
335     numFormalParams = FD->param_size();
336     calleeType = CT_Function;
337   } else if (isa<VarDecl>(D)) {
338     QualType type = cast<ValueDecl>(D)->getType();
339     const FunctionType *fn = nullptr;
340     if (const PointerType *ptr = type->getAs<PointerType>()) {
341       fn = ptr->getPointeeType()->getAs<FunctionType>();
342       if (!fn) return;
343       calleeType = CT_Function;
344     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
345       fn = ptr->getPointeeType()->castAs<FunctionType>();
346       calleeType = CT_Block;
347     } else {
348       return;
349     }
350 
351     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
352       numFormalParams = proto->getNumParams();
353     } else {
354       numFormalParams = 0;
355     }
356   } else {
357     return;
358   }
359 
360   // "nullPos" is the number of formal parameters at the end which
361   // effectively count as part of the variadic arguments.  This is
362   // useful if you would prefer to not have *any* formal parameters,
363   // but the language forces you to have at least one.
364   unsigned nullPos = attr->getNullPos();
365   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
366   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
367 
368   // The number of arguments which should follow the sentinel.
369   unsigned numArgsAfterSentinel = attr->getSentinel();
370 
371   // If there aren't enough arguments for all the formal parameters,
372   // the sentinel, and the args after the sentinel, complain.
373   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
374     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
375     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
376     return;
377   }
378 
379   // Otherwise, find the sentinel expression.
380   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
381   if (!sentinelExpr) return;
382   if (sentinelExpr->isValueDependent()) return;
383   if (Context.isSentinelNullExpr(sentinelExpr)) return;
384 
385   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
386   // or 'NULL' if those are actually defined in the context.  Only use
387   // 'nil' for ObjC methods, where it's much more likely that the
388   // variadic arguments form a list of object pointers.
389   SourceLocation MissingNilLoc
390     = getLocForEndOfToken(sentinelExpr->getLocEnd());
391   std::string NullValue;
392   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
393     NullValue = "nil";
394   else if (getLangOpts().CPlusPlus11)
395     NullValue = "nullptr";
396   else if (PP.isMacroDefined("NULL"))
397     NullValue = "NULL";
398   else
399     NullValue = "(void*) 0";
400 
401   if (MissingNilLoc.isInvalid())
402     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
403   else
404     Diag(MissingNilLoc, diag::warn_missing_sentinel)
405       << int(calleeType)
406       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
407   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
408 }
409 
410 SourceRange Sema::getExprRange(Expr *E) const {
411   return E ? E->getSourceRange() : SourceRange();
412 }
413 
414 //===----------------------------------------------------------------------===//
415 //  Standard Promotions and Conversions
416 //===----------------------------------------------------------------------===//
417 
418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
419 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
420   // Handle any placeholder expressions which made it here.
421   if (E->getType()->isPlaceholderType()) {
422     ExprResult result = CheckPlaceholderExpr(E);
423     if (result.isInvalid()) return ExprError();
424     E = result.get();
425   }
426 
427   QualType Ty = E->getType();
428   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
429 
430   if (Ty->isFunctionType()) {
431     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
432       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
433         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
434           return ExprError();
435 
436     E = ImpCastExprToType(E, Context.getPointerType(Ty),
437                           CK_FunctionToPointerDecay).get();
438   } else if (Ty->isArrayType()) {
439     // In C90 mode, arrays only promote to pointers if the array expression is
440     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
441     // type 'array of type' is converted to an expression that has type 'pointer
442     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
443     // that has type 'array of type' ...".  The relevant change is "an lvalue"
444     // (C90) to "an expression" (C99).
445     //
446     // C++ 4.2p1:
447     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
448     // T" can be converted to an rvalue of type "pointer to T".
449     //
450     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
451       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
452                             CK_ArrayToPointerDecay).get();
453   }
454   return E;
455 }
456 
457 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
458   // Check to see if we are dereferencing a null pointer.  If so,
459   // and if not volatile-qualified, this is undefined behavior that the
460   // optimizer will delete, so warn about it.  People sometimes try to use this
461   // to get a deterministic trap and are surprised by clang's behavior.  This
462   // only handles the pattern "*null", which is a very syntactic check.
463   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
464     if (UO->getOpcode() == UO_Deref &&
465         UO->getSubExpr()->IgnoreParenCasts()->
466           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
467         !UO->getType().isVolatileQualified()) {
468     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
469                           S.PDiag(diag::warn_indirection_through_null)
470                             << UO->getSubExpr()->getSourceRange());
471     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
472                         S.PDiag(diag::note_indirection_through_null));
473   }
474 }
475 
476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
477                                     SourceLocation AssignLoc,
478                                     const Expr* RHS) {
479   const ObjCIvarDecl *IV = OIRE->getDecl();
480   if (!IV)
481     return;
482 
483   DeclarationName MemberName = IV->getDeclName();
484   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
485   if (!Member || !Member->isStr("isa"))
486     return;
487 
488   const Expr *Base = OIRE->getBase();
489   QualType BaseType = Base->getType();
490   if (OIRE->isArrow())
491     BaseType = BaseType->getPointeeType();
492   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
493     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
494       ObjCInterfaceDecl *ClassDeclared = nullptr;
495       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
496       if (!ClassDeclared->getSuperClass()
497           && (*ClassDeclared->ivar_begin()) == IV) {
498         if (RHS) {
499           NamedDecl *ObjectSetClass =
500             S.LookupSingleName(S.TUScope,
501                                &S.Context.Idents.get("object_setClass"),
502                                SourceLocation(), S.LookupOrdinaryName);
503           if (ObjectSetClass) {
504             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
505             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
506             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
507             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
508                                                      AssignLoc), ",") <<
509             FixItHint::CreateInsertion(RHSLocEnd, ")");
510           }
511           else
512             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
513         } else {
514           NamedDecl *ObjectGetClass =
515             S.LookupSingleName(S.TUScope,
516                                &S.Context.Idents.get("object_getClass"),
517                                SourceLocation(), S.LookupOrdinaryName);
518           if (ObjectGetClass)
519             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
520             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
521             FixItHint::CreateReplacement(
522                                          SourceRange(OIRE->getOpLoc(),
523                                                      OIRE->getLocEnd()), ")");
524           else
525             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
526         }
527         S.Diag(IV->getLocation(), diag::note_ivar_decl);
528       }
529     }
530 }
531 
532 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
533   // Handle any placeholder expressions which made it here.
534   if (E->getType()->isPlaceholderType()) {
535     ExprResult result = CheckPlaceholderExpr(E);
536     if (result.isInvalid()) return ExprError();
537     E = result.get();
538   }
539 
540   // C++ [conv.lval]p1:
541   //   A glvalue of a non-function, non-array type T can be
542   //   converted to a prvalue.
543   if (!E->isGLValue()) return E;
544 
545   QualType T = E->getType();
546   assert(!T.isNull() && "r-value conversion on typeless expression?");
547 
548   // We don't want to throw lvalue-to-rvalue casts on top of
549   // expressions of certain types in C++.
550   if (getLangOpts().CPlusPlus &&
551       (E->getType() == Context.OverloadTy ||
552        T->isDependentType() ||
553        T->isRecordType()))
554     return E;
555 
556   // The C standard is actually really unclear on this point, and
557   // DR106 tells us what the result should be but not why.  It's
558   // generally best to say that void types just doesn't undergo
559   // lvalue-to-rvalue at all.  Note that expressions of unqualified
560   // 'void' type are never l-values, but qualified void can be.
561   if (T->isVoidType())
562     return E;
563 
564   // OpenCL usually rejects direct accesses to values of 'half' type.
565   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
566       T->isHalfType()) {
567     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
568       << 0 << T;
569     return ExprError();
570   }
571 
572   CheckForNullPointerDereference(*this, E);
573   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
574     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
575                                      &Context.Idents.get("object_getClass"),
576                                      SourceLocation(), LookupOrdinaryName);
577     if (ObjectGetClass)
578       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
579         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
580         FixItHint::CreateReplacement(
581                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
582     else
583       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
584   }
585   else if (const ObjCIvarRefExpr *OIRE =
586             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
587     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
588 
589   // C++ [conv.lval]p1:
590   //   [...] If T is a non-class type, the type of the prvalue is the
591   //   cv-unqualified version of T. Otherwise, the type of the
592   //   rvalue is T.
593   //
594   // C99 6.3.2.1p2:
595   //   If the lvalue has qualified type, the value has the unqualified
596   //   version of the type of the lvalue; otherwise, the value has the
597   //   type of the lvalue.
598   if (T.hasQualifiers())
599     T = T.getUnqualifiedType();
600 
601   // Under the MS ABI, lock down the inheritance model now.
602   if (T->isMemberPointerType() &&
603       Context.getTargetInfo().getCXXABI().isMicrosoft())
604     (void)isCompleteType(E->getExprLoc(), T);
605 
606   UpdateMarkingForLValueToRValue(E);
607 
608   // Loading a __weak object implicitly retains the value, so we need a cleanup to
609   // balance that.
610   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
611     Cleanup.setExprNeedsCleanups(true);
612 
613   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
614                                             nullptr, VK_RValue);
615 
616   // C11 6.3.2.1p2:
617   //   ... if the lvalue has atomic type, the value has the non-atomic version
618   //   of the type of the lvalue ...
619   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
620     T = Atomic->getValueType().getUnqualifiedType();
621     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
622                                    nullptr, VK_RValue);
623   }
624 
625   return Res;
626 }
627 
628 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
629   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
630   if (Res.isInvalid())
631     return ExprError();
632   Res = DefaultLvalueConversion(Res.get());
633   if (Res.isInvalid())
634     return ExprError();
635   return Res;
636 }
637 
638 /// CallExprUnaryConversions - a special case of an unary conversion
639 /// performed on a function designator of a call expression.
640 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
641   QualType Ty = E->getType();
642   ExprResult Res = E;
643   // Only do implicit cast for a function type, but not for a pointer
644   // to function type.
645   if (Ty->isFunctionType()) {
646     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
647                             CK_FunctionToPointerDecay).get();
648     if (Res.isInvalid())
649       return ExprError();
650   }
651   Res = DefaultLvalueConversion(Res.get());
652   if (Res.isInvalid())
653     return ExprError();
654   return Res.get();
655 }
656 
657 /// UsualUnaryConversions - Performs various conversions that are common to most
658 /// operators (C99 6.3). The conversions of array and function types are
659 /// sometimes suppressed. For example, the array->pointer conversion doesn't
660 /// apply if the array is an argument to the sizeof or address (&) operators.
661 /// In these instances, this routine should *not* be called.
662 ExprResult Sema::UsualUnaryConversions(Expr *E) {
663   // First, convert to an r-value.
664   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
665   if (Res.isInvalid())
666     return ExprError();
667   E = Res.get();
668 
669   QualType Ty = E->getType();
670   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
671 
672   // Half FP have to be promoted to float unless it is natively supported
673   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
674     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
675 
676   // Try to perform integral promotions if the object has a theoretically
677   // promotable type.
678   if (Ty->isIntegralOrUnscopedEnumerationType()) {
679     // C99 6.3.1.1p2:
680     //
681     //   The following may be used in an expression wherever an int or
682     //   unsigned int may be used:
683     //     - an object or expression with an integer type whose integer
684     //       conversion rank is less than or equal to the rank of int
685     //       and unsigned int.
686     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
687     //
688     //   If an int can represent all values of the original type, the
689     //   value is converted to an int; otherwise, it is converted to an
690     //   unsigned int. These are called the integer promotions. All
691     //   other types are unchanged by the integer promotions.
692 
693     QualType PTy = Context.isPromotableBitField(E);
694     if (!PTy.isNull()) {
695       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
696       return E;
697     }
698     if (Ty->isPromotableIntegerType()) {
699       QualType PT = Context.getPromotedIntegerType(Ty);
700       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
701       return E;
702     }
703   }
704   return E;
705 }
706 
707 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
708 /// do not have a prototype. Arguments that have type float or __fp16
709 /// are promoted to double. All other argument types are converted by
710 /// UsualUnaryConversions().
711 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
712   QualType Ty = E->getType();
713   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
714 
715   ExprResult Res = UsualUnaryConversions(E);
716   if (Res.isInvalid())
717     return ExprError();
718   E = Res.get();
719 
720   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
721   // promote to double.
722   // Note that default argument promotion applies only to float (and
723   // half/fp16); it does not apply to _Float16.
724   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
725   if (BTy && (BTy->getKind() == BuiltinType::Half ||
726               BTy->getKind() == BuiltinType::Float)) {
727     if (getLangOpts().OpenCL &&
728         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
729         if (BTy->getKind() == BuiltinType::Half) {
730             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
731         }
732     } else {
733       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
734     }
735   }
736 
737   // C++ performs lvalue-to-rvalue conversion as a default argument
738   // promotion, even on class types, but note:
739   //   C++11 [conv.lval]p2:
740   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
741   //     operand or a subexpression thereof the value contained in the
742   //     referenced object is not accessed. Otherwise, if the glvalue
743   //     has a class type, the conversion copy-initializes a temporary
744   //     of type T from the glvalue and the result of the conversion
745   //     is a prvalue for the temporary.
746   // FIXME: add some way to gate this entire thing for correctness in
747   // potentially potentially evaluated contexts.
748   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
749     ExprResult Temp = PerformCopyInitialization(
750                        InitializedEntity::InitializeTemporary(E->getType()),
751                                                 E->getExprLoc(), E);
752     if (Temp.isInvalid())
753       return ExprError();
754     E = Temp.get();
755   }
756 
757   return E;
758 }
759 
760 /// Determine the degree of POD-ness for an expression.
761 /// Incomplete types are considered POD, since this check can be performed
762 /// when we're in an unevaluated context.
763 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
764   if (Ty->isIncompleteType()) {
765     // C++11 [expr.call]p7:
766     //   After these conversions, if the argument does not have arithmetic,
767     //   enumeration, pointer, pointer to member, or class type, the program
768     //   is ill-formed.
769     //
770     // Since we've already performed array-to-pointer and function-to-pointer
771     // decay, the only such type in C++ is cv void. This also handles
772     // initializer lists as variadic arguments.
773     if (Ty->isVoidType())
774       return VAK_Invalid;
775 
776     if (Ty->isObjCObjectType())
777       return VAK_Invalid;
778     return VAK_Valid;
779   }
780 
781   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
782     return VAK_Invalid;
783 
784   if (Ty.isCXX98PODType(Context))
785     return VAK_Valid;
786 
787   // C++11 [expr.call]p7:
788   //   Passing a potentially-evaluated argument of class type (Clause 9)
789   //   having a non-trivial copy constructor, a non-trivial move constructor,
790   //   or a non-trivial destructor, with no corresponding parameter,
791   //   is conditionally-supported with implementation-defined semantics.
792   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
793     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
794       if (!Record->hasNonTrivialCopyConstructor() &&
795           !Record->hasNonTrivialMoveConstructor() &&
796           !Record->hasNonTrivialDestructor())
797         return VAK_ValidInCXX11;
798 
799   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
800     return VAK_Valid;
801 
802   if (Ty->isObjCObjectType())
803     return VAK_Invalid;
804 
805   if (getLangOpts().MSVCCompat)
806     return VAK_MSVCUndefined;
807 
808   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
809   // permitted to reject them. We should consider doing so.
810   return VAK_Undefined;
811 }
812 
813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
814   // Don't allow one to pass an Objective-C interface to a vararg.
815   const QualType &Ty = E->getType();
816   VarArgKind VAK = isValidVarArgType(Ty);
817 
818   // Complain about passing non-POD types through varargs.
819   switch (VAK) {
820   case VAK_ValidInCXX11:
821     DiagRuntimeBehavior(
822         E->getLocStart(), nullptr,
823         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
824           << Ty << CT);
825     LLVM_FALLTHROUGH;
826   case VAK_Valid:
827     if (Ty->isRecordType()) {
828       // This is unlikely to be what the user intended. If the class has a
829       // 'c_str' member function, the user probably meant to call that.
830       DiagRuntimeBehavior(E->getLocStart(), nullptr,
831                           PDiag(diag::warn_pass_class_arg_to_vararg)
832                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
833     }
834     break;
835 
836   case VAK_Undefined:
837   case VAK_MSVCUndefined:
838     DiagRuntimeBehavior(
839         E->getLocStart(), nullptr,
840         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
841           << getLangOpts().CPlusPlus11 << Ty << CT);
842     break;
843 
844   case VAK_Invalid:
845     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
846       Diag(E->getLocStart(),
847            diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
848     else if (Ty->isObjCObjectType())
849       DiagRuntimeBehavior(
850           E->getLocStart(), nullptr,
851           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
852             << Ty << CT);
853     else
854       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
855         << isa<InitListExpr>(E) << Ty << CT;
856     break;
857   }
858 }
859 
860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
861 /// will create a trap if the resulting type is not a POD type.
862 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
863                                                   FunctionDecl *FDecl) {
864   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
865     // Strip the unbridged-cast placeholder expression off, if applicable.
866     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
867         (CT == VariadicMethod ||
868          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
869       E = stripARCUnbridgedCast(E);
870 
871     // Otherwise, do normal placeholder checking.
872     } else {
873       ExprResult ExprRes = CheckPlaceholderExpr(E);
874       if (ExprRes.isInvalid())
875         return ExprError();
876       E = ExprRes.get();
877     }
878   }
879 
880   ExprResult ExprRes = DefaultArgumentPromotion(E);
881   if (ExprRes.isInvalid())
882     return ExprError();
883   E = ExprRes.get();
884 
885   // Diagnostics regarding non-POD argument types are
886   // emitted along with format string checking in Sema::CheckFunctionCall().
887   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
888     // Turn this into a trap.
889     CXXScopeSpec SS;
890     SourceLocation TemplateKWLoc;
891     UnqualifiedId Name;
892     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
893                        E->getLocStart());
894     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
895                                           Name, true, false);
896     if (TrapFn.isInvalid())
897       return ExprError();
898 
899     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
900                                     E->getLocStart(), None,
901                                     E->getLocEnd());
902     if (Call.isInvalid())
903       return ExprError();
904 
905     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
906                                   Call.get(), E);
907     if (Comma.isInvalid())
908       return ExprError();
909     return Comma.get();
910   }
911 
912   if (!getLangOpts().CPlusPlus &&
913       RequireCompleteType(E->getExprLoc(), E->getType(),
914                           diag::err_call_incomplete_argument))
915     return ExprError();
916 
917   return E;
918 }
919 
920 /// Converts an integer to complex float type.  Helper function of
921 /// UsualArithmeticConversions()
922 ///
923 /// \return false if the integer expression is an integer type and is
924 /// successfully converted to the complex type.
925 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
926                                                   ExprResult &ComplexExpr,
927                                                   QualType IntTy,
928                                                   QualType ComplexTy,
929                                                   bool SkipCast) {
930   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
931   if (SkipCast) return false;
932   if (IntTy->isIntegerType()) {
933     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
934     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
935     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
936                                   CK_FloatingRealToComplex);
937   } else {
938     assert(IntTy->isComplexIntegerType());
939     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
940                                   CK_IntegralComplexToFloatingComplex);
941   }
942   return false;
943 }
944 
945 /// Handle arithmetic conversion with complex types.  Helper function of
946 /// UsualArithmeticConversions()
947 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
948                                              ExprResult &RHS, QualType LHSType,
949                                              QualType RHSType,
950                                              bool IsCompAssign) {
951   // if we have an integer operand, the result is the complex type.
952   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
953                                              /*skipCast*/false))
954     return LHSType;
955   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
956                                              /*skipCast*/IsCompAssign))
957     return RHSType;
958 
959   // This handles complex/complex, complex/float, or float/complex.
960   // When both operands are complex, the shorter operand is converted to the
961   // type of the longer, and that is the type of the result. This corresponds
962   // to what is done when combining two real floating-point operands.
963   // The fun begins when size promotion occur across type domains.
964   // From H&S 6.3.4: When one operand is complex and the other is a real
965   // floating-point type, the less precise type is converted, within it's
966   // real or complex domain, to the precision of the other type. For example,
967   // when combining a "long double" with a "double _Complex", the
968   // "double _Complex" is promoted to "long double _Complex".
969 
970   // Compute the rank of the two types, regardless of whether they are complex.
971   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
972 
973   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
974   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
975   QualType LHSElementType =
976       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
977   QualType RHSElementType =
978       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
979 
980   QualType ResultType = S.Context.getComplexType(LHSElementType);
981   if (Order < 0) {
982     // Promote the precision of the LHS if not an assignment.
983     ResultType = S.Context.getComplexType(RHSElementType);
984     if (!IsCompAssign) {
985       if (LHSComplexType)
986         LHS =
987             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
988       else
989         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
990     }
991   } else if (Order > 0) {
992     // Promote the precision of the RHS.
993     if (RHSComplexType)
994       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
995     else
996       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
997   }
998   return ResultType;
999 }
1000 
1001 /// Handle arithmetic conversion from integer to float.  Helper function
1002 /// of UsualArithmeticConversions()
1003 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1004                                            ExprResult &IntExpr,
1005                                            QualType FloatTy, QualType IntTy,
1006                                            bool ConvertFloat, bool ConvertInt) {
1007   if (IntTy->isIntegerType()) {
1008     if (ConvertInt)
1009       // Convert intExpr to the lhs floating point type.
1010       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1011                                     CK_IntegralToFloating);
1012     return FloatTy;
1013   }
1014 
1015   // Convert both sides to the appropriate complex float.
1016   assert(IntTy->isComplexIntegerType());
1017   QualType result = S.Context.getComplexType(FloatTy);
1018 
1019   // _Complex int -> _Complex float
1020   if (ConvertInt)
1021     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1022                                   CK_IntegralComplexToFloatingComplex);
1023 
1024   // float -> _Complex float
1025   if (ConvertFloat)
1026     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1027                                     CK_FloatingRealToComplex);
1028 
1029   return result;
1030 }
1031 
1032 /// Handle arithmethic conversion with floating point types.  Helper
1033 /// function of UsualArithmeticConversions()
1034 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1035                                       ExprResult &RHS, QualType LHSType,
1036                                       QualType RHSType, bool IsCompAssign) {
1037   bool LHSFloat = LHSType->isRealFloatingType();
1038   bool RHSFloat = RHSType->isRealFloatingType();
1039 
1040   // If we have two real floating types, convert the smaller operand
1041   // to the bigger result.
1042   if (LHSFloat && RHSFloat) {
1043     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1044     if (order > 0) {
1045       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1046       return LHSType;
1047     }
1048 
1049     assert(order < 0 && "illegal float comparison");
1050     if (!IsCompAssign)
1051       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1052     return RHSType;
1053   }
1054 
1055   if (LHSFloat) {
1056     // Half FP has to be promoted to float unless it is natively supported
1057     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1058       LHSType = S.Context.FloatTy;
1059 
1060     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1061                                       /*convertFloat=*/!IsCompAssign,
1062                                       /*convertInt=*/ true);
1063   }
1064   assert(RHSFloat);
1065   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1066                                     /*convertInt=*/ true,
1067                                     /*convertFloat=*/!IsCompAssign);
1068 }
1069 
1070 /// Diagnose attempts to convert between __float128 and long double if
1071 /// there is no support for such conversion. Helper function of
1072 /// UsualArithmeticConversions().
1073 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1074                                       QualType RHSType) {
1075   /*  No issue converting if at least one of the types is not a floating point
1076       type or the two types have the same rank.
1077   */
1078   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1079       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1080     return false;
1081 
1082   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1083          "The remaining types must be floating point types.");
1084 
1085   auto *LHSComplex = LHSType->getAs<ComplexType>();
1086   auto *RHSComplex = RHSType->getAs<ComplexType>();
1087 
1088   QualType LHSElemType = LHSComplex ?
1089     LHSComplex->getElementType() : LHSType;
1090   QualType RHSElemType = RHSComplex ?
1091     RHSComplex->getElementType() : RHSType;
1092 
1093   // No issue if the two types have the same representation
1094   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1095       &S.Context.getFloatTypeSemantics(RHSElemType))
1096     return false;
1097 
1098   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1099                                 RHSElemType == S.Context.LongDoubleTy);
1100   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1101                             RHSElemType == S.Context.Float128Ty);
1102 
1103   // We've handled the situation where __float128 and long double have the same
1104   // representation. We allow all conversions for all possible long double types
1105   // except PPC's double double.
1106   return Float128AndLongDouble &&
1107     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1108      &llvm::APFloat::PPCDoubleDouble());
1109 }
1110 
1111 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1112 
1113 namespace {
1114 /// These helper callbacks are placed in an anonymous namespace to
1115 /// permit their use as function template parameters.
1116 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1117   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1118 }
1119 
1120 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1121   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1122                              CK_IntegralComplexCast);
1123 }
1124 }
1125 
1126 /// Handle integer arithmetic conversions.  Helper function of
1127 /// UsualArithmeticConversions()
1128 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1129 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1130                                         ExprResult &RHS, QualType LHSType,
1131                                         QualType RHSType, bool IsCompAssign) {
1132   // The rules for this case are in C99 6.3.1.8
1133   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1134   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1135   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1136   if (LHSSigned == RHSSigned) {
1137     // Same signedness; use the higher-ranked type
1138     if (order >= 0) {
1139       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1140       return LHSType;
1141     } else if (!IsCompAssign)
1142       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1143     return RHSType;
1144   } else if (order != (LHSSigned ? 1 : -1)) {
1145     // The unsigned type has greater than or equal rank to the
1146     // signed type, so use the unsigned type
1147     if (RHSSigned) {
1148       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1149       return LHSType;
1150     } else if (!IsCompAssign)
1151       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1152     return RHSType;
1153   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1154     // The two types are different widths; if we are here, that
1155     // means the signed type is larger than the unsigned type, so
1156     // use the signed type.
1157     if (LHSSigned) {
1158       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159       return LHSType;
1160     } else if (!IsCompAssign)
1161       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162     return RHSType;
1163   } else {
1164     // The signed type is higher-ranked than the unsigned type,
1165     // but isn't actually any bigger (like unsigned int and long
1166     // on most 32-bit systems).  Use the unsigned type corresponding
1167     // to the signed type.
1168     QualType result =
1169       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1170     RHS = (*doRHSCast)(S, RHS.get(), result);
1171     if (!IsCompAssign)
1172       LHS = (*doLHSCast)(S, LHS.get(), result);
1173     return result;
1174   }
1175 }
1176 
1177 /// Handle conversions with GCC complex int extension.  Helper function
1178 /// of UsualArithmeticConversions()
1179 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1180                                            ExprResult &RHS, QualType LHSType,
1181                                            QualType RHSType,
1182                                            bool IsCompAssign) {
1183   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1184   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1185 
1186   if (LHSComplexInt && RHSComplexInt) {
1187     QualType LHSEltType = LHSComplexInt->getElementType();
1188     QualType RHSEltType = RHSComplexInt->getElementType();
1189     QualType ScalarType =
1190       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1191         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1192 
1193     return S.Context.getComplexType(ScalarType);
1194   }
1195 
1196   if (LHSComplexInt) {
1197     QualType LHSEltType = LHSComplexInt->getElementType();
1198     QualType ScalarType =
1199       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1200         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1201     QualType ComplexType = S.Context.getComplexType(ScalarType);
1202     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1203                               CK_IntegralRealToComplex);
1204 
1205     return ComplexType;
1206   }
1207 
1208   assert(RHSComplexInt);
1209 
1210   QualType RHSEltType = RHSComplexInt->getElementType();
1211   QualType ScalarType =
1212     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1213       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1214   QualType ComplexType = S.Context.getComplexType(ScalarType);
1215 
1216   if (!IsCompAssign)
1217     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1218                               CK_IntegralRealToComplex);
1219   return ComplexType;
1220 }
1221 
1222 /// UsualArithmeticConversions - Performs various conversions that are common to
1223 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1224 /// routine returns the first non-arithmetic type found. The client is
1225 /// responsible for emitting appropriate error diagnostics.
1226 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1227                                           bool IsCompAssign) {
1228   if (!IsCompAssign) {
1229     LHS = UsualUnaryConversions(LHS.get());
1230     if (LHS.isInvalid())
1231       return QualType();
1232   }
1233 
1234   RHS = UsualUnaryConversions(RHS.get());
1235   if (RHS.isInvalid())
1236     return QualType();
1237 
1238   // For conversion purposes, we ignore any qualifiers.
1239   // For example, "const float" and "float" are equivalent.
1240   QualType LHSType =
1241     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1242   QualType RHSType =
1243     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1244 
1245   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1246   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1247     LHSType = AtomicLHS->getValueType();
1248 
1249   // If both types are identical, no conversion is needed.
1250   if (LHSType == RHSType)
1251     return LHSType;
1252 
1253   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1254   // The caller can deal with this (e.g. pointer + int).
1255   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1256     return QualType();
1257 
1258   // Apply unary and bitfield promotions to the LHS's type.
1259   QualType LHSUnpromotedType = LHSType;
1260   if (LHSType->isPromotableIntegerType())
1261     LHSType = Context.getPromotedIntegerType(LHSType);
1262   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1263   if (!LHSBitfieldPromoteTy.isNull())
1264     LHSType = LHSBitfieldPromoteTy;
1265   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1266     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1267 
1268   // If both types are identical, no conversion is needed.
1269   if (LHSType == RHSType)
1270     return LHSType;
1271 
1272   // At this point, we have two different arithmetic types.
1273 
1274   // Diagnose attempts to convert between __float128 and long double where
1275   // such conversions currently can't be handled.
1276   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1277     return QualType();
1278 
1279   // Handle complex types first (C99 6.3.1.8p1).
1280   if (LHSType->isComplexType() || RHSType->isComplexType())
1281     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1282                                         IsCompAssign);
1283 
1284   // Now handle "real" floating types (i.e. float, double, long double).
1285   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1286     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1287                                  IsCompAssign);
1288 
1289   // Handle GCC complex int extension.
1290   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1291     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1292                                       IsCompAssign);
1293 
1294   // Finally, we have two differing integer types.
1295   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1296            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1297 }
1298 
1299 
1300 //===----------------------------------------------------------------------===//
1301 //  Semantic Analysis for various Expression Types
1302 //===----------------------------------------------------------------------===//
1303 
1304 
1305 ExprResult
1306 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1307                                 SourceLocation DefaultLoc,
1308                                 SourceLocation RParenLoc,
1309                                 Expr *ControllingExpr,
1310                                 ArrayRef<ParsedType> ArgTypes,
1311                                 ArrayRef<Expr *> ArgExprs) {
1312   unsigned NumAssocs = ArgTypes.size();
1313   assert(NumAssocs == ArgExprs.size());
1314 
1315   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1316   for (unsigned i = 0; i < NumAssocs; ++i) {
1317     if (ArgTypes[i])
1318       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1319     else
1320       Types[i] = nullptr;
1321   }
1322 
1323   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1324                                              ControllingExpr,
1325                                              llvm::makeArrayRef(Types, NumAssocs),
1326                                              ArgExprs);
1327   delete [] Types;
1328   return ER;
1329 }
1330 
1331 ExprResult
1332 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1333                                  SourceLocation DefaultLoc,
1334                                  SourceLocation RParenLoc,
1335                                  Expr *ControllingExpr,
1336                                  ArrayRef<TypeSourceInfo *> Types,
1337                                  ArrayRef<Expr *> Exprs) {
1338   unsigned NumAssocs = Types.size();
1339   assert(NumAssocs == Exprs.size());
1340 
1341   // Decay and strip qualifiers for the controlling expression type, and handle
1342   // placeholder type replacement. See committee discussion from WG14 DR423.
1343   {
1344     EnterExpressionEvaluationContext Unevaluated(
1345         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1346     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1347     if (R.isInvalid())
1348       return ExprError();
1349     ControllingExpr = R.get();
1350   }
1351 
1352   // The controlling expression is an unevaluated operand, so side effects are
1353   // likely unintended.
1354   if (!inTemplateInstantiation() &&
1355       ControllingExpr->HasSideEffects(Context, false))
1356     Diag(ControllingExpr->getExprLoc(),
1357          diag::warn_side_effects_unevaluated_context);
1358 
1359   bool TypeErrorFound = false,
1360        IsResultDependent = ControllingExpr->isTypeDependent(),
1361        ContainsUnexpandedParameterPack
1362          = ControllingExpr->containsUnexpandedParameterPack();
1363 
1364   for (unsigned i = 0; i < NumAssocs; ++i) {
1365     if (Exprs[i]->containsUnexpandedParameterPack())
1366       ContainsUnexpandedParameterPack = true;
1367 
1368     if (Types[i]) {
1369       if (Types[i]->getType()->containsUnexpandedParameterPack())
1370         ContainsUnexpandedParameterPack = true;
1371 
1372       if (Types[i]->getType()->isDependentType()) {
1373         IsResultDependent = true;
1374       } else {
1375         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1376         // complete object type other than a variably modified type."
1377         unsigned D = 0;
1378         if (Types[i]->getType()->isIncompleteType())
1379           D = diag::err_assoc_type_incomplete;
1380         else if (!Types[i]->getType()->isObjectType())
1381           D = diag::err_assoc_type_nonobject;
1382         else if (Types[i]->getType()->isVariablyModifiedType())
1383           D = diag::err_assoc_type_variably_modified;
1384 
1385         if (D != 0) {
1386           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1387             << Types[i]->getTypeLoc().getSourceRange()
1388             << Types[i]->getType();
1389           TypeErrorFound = true;
1390         }
1391 
1392         // C11 6.5.1.1p2 "No two generic associations in the same generic
1393         // selection shall specify compatible types."
1394         for (unsigned j = i+1; j < NumAssocs; ++j)
1395           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1396               Context.typesAreCompatible(Types[i]->getType(),
1397                                          Types[j]->getType())) {
1398             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1399                  diag::err_assoc_compatible_types)
1400               << Types[j]->getTypeLoc().getSourceRange()
1401               << Types[j]->getType()
1402               << Types[i]->getType();
1403             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1404                  diag::note_compat_assoc)
1405               << Types[i]->getTypeLoc().getSourceRange()
1406               << Types[i]->getType();
1407             TypeErrorFound = true;
1408           }
1409       }
1410     }
1411   }
1412   if (TypeErrorFound)
1413     return ExprError();
1414 
1415   // If we determined that the generic selection is result-dependent, don't
1416   // try to compute the result expression.
1417   if (IsResultDependent)
1418     return new (Context) GenericSelectionExpr(
1419         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1420         ContainsUnexpandedParameterPack);
1421 
1422   SmallVector<unsigned, 1> CompatIndices;
1423   unsigned DefaultIndex = -1U;
1424   for (unsigned i = 0; i < NumAssocs; ++i) {
1425     if (!Types[i])
1426       DefaultIndex = i;
1427     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1428                                         Types[i]->getType()))
1429       CompatIndices.push_back(i);
1430   }
1431 
1432   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1433   // type compatible with at most one of the types named in its generic
1434   // association list."
1435   if (CompatIndices.size() > 1) {
1436     // We strip parens here because the controlling expression is typically
1437     // parenthesized in macro definitions.
1438     ControllingExpr = ControllingExpr->IgnoreParens();
1439     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1440       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1441       << (unsigned) CompatIndices.size();
1442     for (unsigned I : CompatIndices) {
1443       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1444            diag::note_compat_assoc)
1445         << Types[I]->getTypeLoc().getSourceRange()
1446         << Types[I]->getType();
1447     }
1448     return ExprError();
1449   }
1450 
1451   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1452   // its controlling expression shall have type compatible with exactly one of
1453   // the types named in its generic association list."
1454   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1455     // We strip parens here because the controlling expression is typically
1456     // parenthesized in macro definitions.
1457     ControllingExpr = ControllingExpr->IgnoreParens();
1458     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1459       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1460     return ExprError();
1461   }
1462 
1463   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1464   // type name that is compatible with the type of the controlling expression,
1465   // then the result expression of the generic selection is the expression
1466   // in that generic association. Otherwise, the result expression of the
1467   // generic selection is the expression in the default generic association."
1468   unsigned ResultIndex =
1469     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1470 
1471   return new (Context) GenericSelectionExpr(
1472       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1473       ContainsUnexpandedParameterPack, ResultIndex);
1474 }
1475 
1476 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1477 /// location of the token and the offset of the ud-suffix within it.
1478 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1479                                      unsigned Offset) {
1480   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1481                                         S.getLangOpts());
1482 }
1483 
1484 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1485 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1486 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1487                                                  IdentifierInfo *UDSuffix,
1488                                                  SourceLocation UDSuffixLoc,
1489                                                  ArrayRef<Expr*> Args,
1490                                                  SourceLocation LitEndLoc) {
1491   assert(Args.size() <= 2 && "too many arguments for literal operator");
1492 
1493   QualType ArgTy[2];
1494   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1495     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1496     if (ArgTy[ArgIdx]->isArrayType())
1497       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1498   }
1499 
1500   DeclarationName OpName =
1501     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1502   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1503   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1504 
1505   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1506   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1507                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1508                               /*AllowStringTemplate*/ false,
1509                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1510     return ExprError();
1511 
1512   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1513 }
1514 
1515 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1516 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1517 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1518 /// multiple tokens.  However, the common case is that StringToks points to one
1519 /// string.
1520 ///
1521 ExprResult
1522 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1523   assert(!StringToks.empty() && "Must have at least one string!");
1524 
1525   StringLiteralParser Literal(StringToks, PP);
1526   if (Literal.hadError)
1527     return ExprError();
1528 
1529   SmallVector<SourceLocation, 4> StringTokLocs;
1530   for (const Token &Tok : StringToks)
1531     StringTokLocs.push_back(Tok.getLocation());
1532 
1533   QualType CharTy = Context.CharTy;
1534   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1535   if (Literal.isWide()) {
1536     CharTy = Context.getWideCharType();
1537     Kind = StringLiteral::Wide;
1538   } else if (Literal.isUTF8()) {
1539     if (getLangOpts().Char8)
1540       CharTy = Context.Char8Ty;
1541     Kind = StringLiteral::UTF8;
1542   } else if (Literal.isUTF16()) {
1543     CharTy = Context.Char16Ty;
1544     Kind = StringLiteral::UTF16;
1545   } else if (Literal.isUTF32()) {
1546     CharTy = Context.Char32Ty;
1547     Kind = StringLiteral::UTF32;
1548   } else if (Literal.isPascal()) {
1549     CharTy = Context.UnsignedCharTy;
1550   }
1551 
1552   QualType CharTyConst = CharTy;
1553   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1554   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1555     CharTyConst.addConst();
1556 
1557   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1558 
1559   // Get an array type for the string, according to C99 6.4.5.  This includes
1560   // the nul terminator character as well as the string length for pascal
1561   // strings.
1562   QualType StrTy = Context.getConstantArrayType(
1563       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1564       ArrayType::Normal, 0);
1565 
1566   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1567   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1568                                              Kind, Literal.Pascal, StrTy,
1569                                              &StringTokLocs[0],
1570                                              StringTokLocs.size());
1571   if (Literal.getUDSuffix().empty())
1572     return Lit;
1573 
1574   // We're building a user-defined literal.
1575   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1576   SourceLocation UDSuffixLoc =
1577     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1578                    Literal.getUDSuffixOffset());
1579 
1580   // Make sure we're allowed user-defined literals here.
1581   if (!UDLScope)
1582     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1583 
1584   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1585   //   operator "" X (str, len)
1586   QualType SizeType = Context.getSizeType();
1587 
1588   DeclarationName OpName =
1589     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593   QualType ArgTy[] = {
1594     Context.getArrayDecayedType(StrTy), SizeType
1595   };
1596 
1597   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1598   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1599                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1600                                 /*AllowStringTemplate*/ true,
1601                                 /*DiagnoseMissing*/ true)) {
1602 
1603   case LOLR_Cooked: {
1604     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1605     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1606                                                     StringTokLocs[0]);
1607     Expr *Args[] = { Lit, LenArg };
1608 
1609     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1610   }
1611 
1612   case LOLR_StringTemplate: {
1613     TemplateArgumentListInfo ExplicitArgs;
1614 
1615     unsigned CharBits = Context.getIntWidth(CharTy);
1616     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1617     llvm::APSInt Value(CharBits, CharIsUnsigned);
1618 
1619     TemplateArgument TypeArg(CharTy);
1620     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1621     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1622 
1623     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1624       Value = Lit->getCodeUnit(I);
1625       TemplateArgument Arg(Context, Value, CharTy);
1626       TemplateArgumentLocInfo ArgInfo;
1627       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1628     }
1629     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1630                                     &ExplicitArgs);
1631   }
1632   case LOLR_Raw:
1633   case LOLR_Template:
1634   case LOLR_ErrorNoDiagnostic:
1635     llvm_unreachable("unexpected literal operator lookup result");
1636   case LOLR_Error:
1637     return ExprError();
1638   }
1639   llvm_unreachable("unexpected literal operator lookup result");
1640 }
1641 
1642 ExprResult
1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1644                        SourceLocation Loc,
1645                        const CXXScopeSpec *SS) {
1646   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1647   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1648 }
1649 
1650 /// BuildDeclRefExpr - Build an expression that references a
1651 /// declaration that does not require a closure capture.
1652 ExprResult
1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1654                        const DeclarationNameInfo &NameInfo,
1655                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1656                        const TemplateArgumentListInfo *TemplateArgs) {
1657   bool RefersToCapturedVariable =
1658       isa<VarDecl>(D) &&
1659       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1660 
1661   DeclRefExpr *E;
1662   if (isa<VarTemplateSpecializationDecl>(D)) {
1663     VarTemplateSpecializationDecl *VarSpec =
1664         cast<VarTemplateSpecializationDecl>(D);
1665 
1666     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1667                                         : NestedNameSpecifierLoc(),
1668                             VarSpec->getTemplateKeywordLoc(), D,
1669                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1670                             FoundD, TemplateArgs);
1671   } else {
1672     assert(!TemplateArgs && "No template arguments for non-variable"
1673                             " template specialization references");
1674     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1675                                         : NestedNameSpecifierLoc(),
1676                             SourceLocation(), D, RefersToCapturedVariable,
1677                             NameInfo, Ty, VK, FoundD);
1678   }
1679 
1680   MarkDeclRefReferenced(E);
1681 
1682   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1683       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1684       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1685     getCurFunction()->recordUseOfWeak(E);
1686 
1687   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1688   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1689     FD = IFD->getAnonField();
1690   if (FD) {
1691     UnusedPrivateFields.remove(FD);
1692     // Just in case we're building an illegal pointer-to-member.
1693     if (FD->isBitField())
1694       E->setObjectKind(OK_BitField);
1695   }
1696 
1697   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1698   // designates a bit-field.
1699   if (auto *BD = dyn_cast<BindingDecl>(D))
1700     if (auto *BE = BD->getBinding())
1701       E->setObjectKind(BE->getObjectKind());
1702 
1703   return E;
1704 }
1705 
1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1707 /// possibly a list of template arguments.
1708 ///
1709 /// If this produces template arguments, it is permitted to call
1710 /// DecomposeTemplateName.
1711 ///
1712 /// This actually loses a lot of source location information for
1713 /// non-standard name kinds; we should consider preserving that in
1714 /// some way.
1715 void
1716 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1717                              TemplateArgumentListInfo &Buffer,
1718                              DeclarationNameInfo &NameInfo,
1719                              const TemplateArgumentListInfo *&TemplateArgs) {
1720   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1721     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1722     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1723 
1724     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1725                                        Id.TemplateId->NumArgs);
1726     translateTemplateArguments(TemplateArgsPtr, Buffer);
1727 
1728     TemplateName TName = Id.TemplateId->Template.get();
1729     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1730     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1731     TemplateArgs = &Buffer;
1732   } else {
1733     NameInfo = GetNameFromUnqualifiedId(Id);
1734     TemplateArgs = nullptr;
1735   }
1736 }
1737 
1738 static void emitEmptyLookupTypoDiagnostic(
1739     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1740     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1741     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1742   DeclContext *Ctx =
1743       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1744   if (!TC) {
1745     // Emit a special diagnostic for failed member lookups.
1746     // FIXME: computing the declaration context might fail here (?)
1747     if (Ctx)
1748       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1749                                                  << SS.getRange();
1750     else
1751       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1752     return;
1753   }
1754 
1755   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1756   bool DroppedSpecifier =
1757       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1758   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1759                         ? diag::note_implicit_param_decl
1760                         : diag::note_previous_decl;
1761   if (!Ctx)
1762     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1763                          SemaRef.PDiag(NoteID));
1764   else
1765     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1766                                  << Typo << Ctx << DroppedSpecifier
1767                                  << SS.getRange(),
1768                          SemaRef.PDiag(NoteID));
1769 }
1770 
1771 /// Diagnose an empty lookup.
1772 ///
1773 /// \return false if new lookup candidates were found
1774 bool
1775 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1776                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1777                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1778                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1779   DeclarationName Name = R.getLookupName();
1780 
1781   unsigned diagnostic = diag::err_undeclared_var_use;
1782   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1783   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1784       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1785       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1786     diagnostic = diag::err_undeclared_use;
1787     diagnostic_suggest = diag::err_undeclared_use_suggest;
1788   }
1789 
1790   // If the original lookup was an unqualified lookup, fake an
1791   // unqualified lookup.  This is useful when (for example) the
1792   // original lookup would not have found something because it was a
1793   // dependent name.
1794   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1795   while (DC) {
1796     if (isa<CXXRecordDecl>(DC)) {
1797       LookupQualifiedName(R, DC);
1798 
1799       if (!R.empty()) {
1800         // Don't give errors about ambiguities in this lookup.
1801         R.suppressDiagnostics();
1802 
1803         // During a default argument instantiation the CurContext points
1804         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1805         // function parameter list, hence add an explicit check.
1806         bool isDefaultArgument =
1807             !CodeSynthesisContexts.empty() &&
1808             CodeSynthesisContexts.back().Kind ==
1809                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1810         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1811         bool isInstance = CurMethod &&
1812                           CurMethod->isInstance() &&
1813                           DC == CurMethod->getParent() && !isDefaultArgument;
1814 
1815         // Give a code modification hint to insert 'this->'.
1816         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1817         // Actually quite difficult!
1818         if (getLangOpts().MSVCCompat)
1819           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1820         if (isInstance) {
1821           Diag(R.getNameLoc(), diagnostic) << Name
1822             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1823           CheckCXXThisCapture(R.getNameLoc());
1824         } else {
1825           Diag(R.getNameLoc(), diagnostic) << Name;
1826         }
1827 
1828         // Do we really want to note all of these?
1829         for (NamedDecl *D : R)
1830           Diag(D->getLocation(), diag::note_dependent_var_use);
1831 
1832         // Return true if we are inside a default argument instantiation
1833         // and the found name refers to an instance member function, otherwise
1834         // the function calling DiagnoseEmptyLookup will try to create an
1835         // implicit member call and this is wrong for default argument.
1836         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1837           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1838           return true;
1839         }
1840 
1841         // Tell the callee to try to recover.
1842         return false;
1843       }
1844 
1845       R.clear();
1846     }
1847 
1848     // In Microsoft mode, if we are performing lookup from within a friend
1849     // function definition declared at class scope then we must set
1850     // DC to the lexical parent to be able to search into the parent
1851     // class.
1852     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1853         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1854         DC->getLexicalParent()->isRecord())
1855       DC = DC->getLexicalParent();
1856     else
1857       DC = DC->getParent();
1858   }
1859 
1860   // We didn't find anything, so try to correct for a typo.
1861   TypoCorrection Corrected;
1862   if (S && Out) {
1863     SourceLocation TypoLoc = R.getNameLoc();
1864     assert(!ExplicitTemplateArgs &&
1865            "Diagnosing an empty lookup with explicit template args!");
1866     *Out = CorrectTypoDelayed(
1867         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1868         [=](const TypoCorrection &TC) {
1869           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1870                                         diagnostic, diagnostic_suggest);
1871         },
1872         nullptr, CTK_ErrorRecovery);
1873     if (*Out)
1874       return true;
1875   } else if (S && (Corrected =
1876                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1877                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1878     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1879     bool DroppedSpecifier =
1880         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1881     R.setLookupName(Corrected.getCorrection());
1882 
1883     bool AcceptableWithRecovery = false;
1884     bool AcceptableWithoutRecovery = false;
1885     NamedDecl *ND = Corrected.getFoundDecl();
1886     if (ND) {
1887       if (Corrected.isOverloaded()) {
1888         OverloadCandidateSet OCS(R.getNameLoc(),
1889                                  OverloadCandidateSet::CSK_Normal);
1890         OverloadCandidateSet::iterator Best;
1891         for (NamedDecl *CD : Corrected) {
1892           if (FunctionTemplateDecl *FTD =
1893                    dyn_cast<FunctionTemplateDecl>(CD))
1894             AddTemplateOverloadCandidate(
1895                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1896                 Args, OCS);
1897           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1898             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1899               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1900                                    Args, OCS);
1901         }
1902         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1903         case OR_Success:
1904           ND = Best->FoundDecl;
1905           Corrected.setCorrectionDecl(ND);
1906           break;
1907         default:
1908           // FIXME: Arbitrarily pick the first declaration for the note.
1909           Corrected.setCorrectionDecl(ND);
1910           break;
1911         }
1912       }
1913       R.addDecl(ND);
1914       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1915         CXXRecordDecl *Record = nullptr;
1916         if (Corrected.getCorrectionSpecifier()) {
1917           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1918           Record = Ty->getAsCXXRecordDecl();
1919         }
1920         if (!Record)
1921           Record = cast<CXXRecordDecl>(
1922               ND->getDeclContext()->getRedeclContext());
1923         R.setNamingClass(Record);
1924       }
1925 
1926       auto *UnderlyingND = ND->getUnderlyingDecl();
1927       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1928                                isa<FunctionTemplateDecl>(UnderlyingND);
1929       // FIXME: If we ended up with a typo for a type name or
1930       // Objective-C class name, we're in trouble because the parser
1931       // is in the wrong place to recover. Suggest the typo
1932       // correction, but don't make it a fix-it since we're not going
1933       // to recover well anyway.
1934       AcceptableWithoutRecovery =
1935           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1936     } else {
1937       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1938       // because we aren't able to recover.
1939       AcceptableWithoutRecovery = true;
1940     }
1941 
1942     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1943       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1944                             ? diag::note_implicit_param_decl
1945                             : diag::note_previous_decl;
1946       if (SS.isEmpty())
1947         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1948                      PDiag(NoteID), AcceptableWithRecovery);
1949       else
1950         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1951                                   << Name << computeDeclContext(SS, false)
1952                                   << DroppedSpecifier << SS.getRange(),
1953                      PDiag(NoteID), AcceptableWithRecovery);
1954 
1955       // Tell the callee whether to try to recover.
1956       return !AcceptableWithRecovery;
1957     }
1958   }
1959   R.clear();
1960 
1961   // Emit a special diagnostic for failed member lookups.
1962   // FIXME: computing the declaration context might fail here (?)
1963   if (!SS.isEmpty()) {
1964     Diag(R.getNameLoc(), diag::err_no_member)
1965       << Name << computeDeclContext(SS, false)
1966       << SS.getRange();
1967     return true;
1968   }
1969 
1970   // Give up, we can't recover.
1971   Diag(R.getNameLoc(), diagnostic) << Name;
1972   return true;
1973 }
1974 
1975 /// In Microsoft mode, if we are inside a template class whose parent class has
1976 /// dependent base classes, and we can't resolve an unqualified identifier, then
1977 /// assume the identifier is a member of a dependent base class.  We can only
1978 /// recover successfully in static methods, instance methods, and other contexts
1979 /// where 'this' is available.  This doesn't precisely match MSVC's
1980 /// instantiation model, but it's close enough.
1981 static Expr *
1982 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1983                                DeclarationNameInfo &NameInfo,
1984                                SourceLocation TemplateKWLoc,
1985                                const TemplateArgumentListInfo *TemplateArgs) {
1986   // Only try to recover from lookup into dependent bases in static methods or
1987   // contexts where 'this' is available.
1988   QualType ThisType = S.getCurrentThisType();
1989   const CXXRecordDecl *RD = nullptr;
1990   if (!ThisType.isNull())
1991     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1992   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1993     RD = MD->getParent();
1994   if (!RD || !RD->hasAnyDependentBases())
1995     return nullptr;
1996 
1997   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1998   // is available, suggest inserting 'this->' as a fixit.
1999   SourceLocation Loc = NameInfo.getLoc();
2000   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2001   DB << NameInfo.getName() << RD;
2002 
2003   if (!ThisType.isNull()) {
2004     DB << FixItHint::CreateInsertion(Loc, "this->");
2005     return CXXDependentScopeMemberExpr::Create(
2006         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2007         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2008         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2009   }
2010 
2011   // Synthesize a fake NNS that points to the derived class.  This will
2012   // perform name lookup during template instantiation.
2013   CXXScopeSpec SS;
2014   auto *NNS =
2015       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2016   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2017   return DependentScopeDeclRefExpr::Create(
2018       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2019       TemplateArgs);
2020 }
2021 
2022 ExprResult
2023 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2024                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2025                         bool HasTrailingLParen, bool IsAddressOfOperand,
2026                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2027                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2028   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2029          "cannot be direct & operand and have a trailing lparen");
2030   if (SS.isInvalid())
2031     return ExprError();
2032 
2033   TemplateArgumentListInfo TemplateArgsBuffer;
2034 
2035   // Decompose the UnqualifiedId into the following data.
2036   DeclarationNameInfo NameInfo;
2037   const TemplateArgumentListInfo *TemplateArgs;
2038   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2039 
2040   DeclarationName Name = NameInfo.getName();
2041   IdentifierInfo *II = Name.getAsIdentifierInfo();
2042   SourceLocation NameLoc = NameInfo.getLoc();
2043 
2044   if (II && II->isEditorPlaceholder()) {
2045     // FIXME: When typed placeholders are supported we can create a typed
2046     // placeholder expression node.
2047     return ExprError();
2048   }
2049 
2050   // C++ [temp.dep.expr]p3:
2051   //   An id-expression is type-dependent if it contains:
2052   //     -- an identifier that was declared with a dependent type,
2053   //        (note: handled after lookup)
2054   //     -- a template-id that is dependent,
2055   //        (note: handled in BuildTemplateIdExpr)
2056   //     -- a conversion-function-id that specifies a dependent type,
2057   //     -- a nested-name-specifier that contains a class-name that
2058   //        names a dependent type.
2059   // Determine whether this is a member of an unknown specialization;
2060   // we need to handle these differently.
2061   bool DependentID = false;
2062   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2063       Name.getCXXNameType()->isDependentType()) {
2064     DependentID = true;
2065   } else if (SS.isSet()) {
2066     if (DeclContext *DC = computeDeclContext(SS, false)) {
2067       if (RequireCompleteDeclContext(SS, DC))
2068         return ExprError();
2069     } else {
2070       DependentID = true;
2071     }
2072   }
2073 
2074   if (DependentID)
2075     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2076                                       IsAddressOfOperand, TemplateArgs);
2077 
2078   // Perform the required lookup.
2079   LookupResult R(*this, NameInfo,
2080                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2081                      ? LookupObjCImplicitSelfParam
2082                      : LookupOrdinaryName);
2083   if (TemplateKWLoc.isValid() || TemplateArgs) {
2084     // Lookup the template name again to correctly establish the context in
2085     // which it was found. This is really unfortunate as we already did the
2086     // lookup to determine that it was a template name in the first place. If
2087     // this becomes a performance hit, we can work harder to preserve those
2088     // results until we get here but it's likely not worth it.
2089     bool MemberOfUnknownSpecialization;
2090     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2091                            MemberOfUnknownSpecialization, TemplateKWLoc))
2092       return ExprError();
2093 
2094     if (MemberOfUnknownSpecialization ||
2095         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2096       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2097                                         IsAddressOfOperand, TemplateArgs);
2098   } else {
2099     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2100     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2101 
2102     // If the result might be in a dependent base class, this is a dependent
2103     // id-expression.
2104     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2105       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2106                                         IsAddressOfOperand, TemplateArgs);
2107 
2108     // If this reference is in an Objective-C method, then we need to do
2109     // some special Objective-C lookup, too.
2110     if (IvarLookupFollowUp) {
2111       ExprResult E(LookupInObjCMethod(R, S, II, true));
2112       if (E.isInvalid())
2113         return ExprError();
2114 
2115       if (Expr *Ex = E.getAs<Expr>())
2116         return Ex;
2117     }
2118   }
2119 
2120   if (R.isAmbiguous())
2121     return ExprError();
2122 
2123   // This could be an implicitly declared function reference (legal in C90,
2124   // extension in C99, forbidden in C++).
2125   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2126     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2127     if (D) R.addDecl(D);
2128   }
2129 
2130   // Determine whether this name might be a candidate for
2131   // argument-dependent lookup.
2132   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2133 
2134   if (R.empty() && !ADL) {
2135     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2136       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2137                                                    TemplateKWLoc, TemplateArgs))
2138         return E;
2139     }
2140 
2141     // Don't diagnose an empty lookup for inline assembly.
2142     if (IsInlineAsmIdentifier)
2143       return ExprError();
2144 
2145     // If this name wasn't predeclared and if this is not a function
2146     // call, diagnose the problem.
2147     TypoExpr *TE = nullptr;
2148     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2149         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2150     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2151     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2152            "Typo correction callback misconfigured");
2153     if (CCC) {
2154       // Make sure the callback knows what the typo being diagnosed is.
2155       CCC->setTypoName(II);
2156       if (SS.isValid())
2157         CCC->setTypoNNS(SS.getScopeRep());
2158     }
2159     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2160     // a template name, but we happen to have always already looked up the name
2161     // before we get here if it must be a template name.
2162     if (DiagnoseEmptyLookup(S, SS, R,
2163                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2164                             nullptr, None, &TE)) {
2165       if (TE && KeywordReplacement) {
2166         auto &State = getTypoExprState(TE);
2167         auto BestTC = State.Consumer->getNextCorrection();
2168         if (BestTC.isKeyword()) {
2169           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2170           if (State.DiagHandler)
2171             State.DiagHandler(BestTC);
2172           KeywordReplacement->startToken();
2173           KeywordReplacement->setKind(II->getTokenID());
2174           KeywordReplacement->setIdentifierInfo(II);
2175           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2176           // Clean up the state associated with the TypoExpr, since it has
2177           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2178           clearDelayedTypo(TE);
2179           // Signal that a correction to a keyword was performed by returning a
2180           // valid-but-null ExprResult.
2181           return (Expr*)nullptr;
2182         }
2183         State.Consumer->resetCorrectionStream();
2184       }
2185       return TE ? TE : ExprError();
2186     }
2187 
2188     assert(!R.empty() &&
2189            "DiagnoseEmptyLookup returned false but added no results");
2190 
2191     // If we found an Objective-C instance variable, let
2192     // LookupInObjCMethod build the appropriate expression to
2193     // reference the ivar.
2194     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2195       R.clear();
2196       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2197       // In a hopelessly buggy code, Objective-C instance variable
2198       // lookup fails and no expression will be built to reference it.
2199       if (!E.isInvalid() && !E.get())
2200         return ExprError();
2201       return E;
2202     }
2203   }
2204 
2205   // This is guaranteed from this point on.
2206   assert(!R.empty() || ADL);
2207 
2208   // Check whether this might be a C++ implicit instance member access.
2209   // C++ [class.mfct.non-static]p3:
2210   //   When an id-expression that is not part of a class member access
2211   //   syntax and not used to form a pointer to member is used in the
2212   //   body of a non-static member function of class X, if name lookup
2213   //   resolves the name in the id-expression to a non-static non-type
2214   //   member of some class C, the id-expression is transformed into a
2215   //   class member access expression using (*this) as the
2216   //   postfix-expression to the left of the . operator.
2217   //
2218   // But we don't actually need to do this for '&' operands if R
2219   // resolved to a function or overloaded function set, because the
2220   // expression is ill-formed if it actually works out to be a
2221   // non-static member function:
2222   //
2223   // C++ [expr.ref]p4:
2224   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2225   //   [t]he expression can be used only as the left-hand operand of a
2226   //   member function call.
2227   //
2228   // There are other safeguards against such uses, but it's important
2229   // to get this right here so that we don't end up making a
2230   // spuriously dependent expression if we're inside a dependent
2231   // instance method.
2232   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2233     bool MightBeImplicitMember;
2234     if (!IsAddressOfOperand)
2235       MightBeImplicitMember = true;
2236     else if (!SS.isEmpty())
2237       MightBeImplicitMember = false;
2238     else if (R.isOverloadedResult())
2239       MightBeImplicitMember = false;
2240     else if (R.isUnresolvableResult())
2241       MightBeImplicitMember = true;
2242     else
2243       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2244                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2245                               isa<MSPropertyDecl>(R.getFoundDecl());
2246 
2247     if (MightBeImplicitMember)
2248       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2249                                              R, TemplateArgs, S);
2250   }
2251 
2252   if (TemplateArgs || TemplateKWLoc.isValid()) {
2253 
2254     // In C++1y, if this is a variable template id, then check it
2255     // in BuildTemplateIdExpr().
2256     // The single lookup result must be a variable template declaration.
2257     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2258         Id.TemplateId->Kind == TNK_Var_template) {
2259       assert(R.getAsSingle<VarTemplateDecl>() &&
2260              "There should only be one declaration found.");
2261     }
2262 
2263     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2264   }
2265 
2266   return BuildDeclarationNameExpr(SS, R, ADL);
2267 }
2268 
2269 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2270 /// declaration name, generally during template instantiation.
2271 /// There's a large number of things which don't need to be done along
2272 /// this path.
2273 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2274     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2275     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2276   DeclContext *DC = computeDeclContext(SS, false);
2277   if (!DC)
2278     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2279                                      NameInfo, /*TemplateArgs=*/nullptr);
2280 
2281   if (RequireCompleteDeclContext(SS, DC))
2282     return ExprError();
2283 
2284   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2285   LookupQualifiedName(R, DC);
2286 
2287   if (R.isAmbiguous())
2288     return ExprError();
2289 
2290   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2291     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2292                                      NameInfo, /*TemplateArgs=*/nullptr);
2293 
2294   if (R.empty()) {
2295     Diag(NameInfo.getLoc(), diag::err_no_member)
2296       << NameInfo.getName() << DC << SS.getRange();
2297     return ExprError();
2298   }
2299 
2300   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2301     // Diagnose a missing typename if this resolved unambiguously to a type in
2302     // a dependent context.  If we can recover with a type, downgrade this to
2303     // a warning in Microsoft compatibility mode.
2304     unsigned DiagID = diag::err_typename_missing;
2305     if (RecoveryTSI && getLangOpts().MSVCCompat)
2306       DiagID = diag::ext_typename_missing;
2307     SourceLocation Loc = SS.getBeginLoc();
2308     auto D = Diag(Loc, DiagID);
2309     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2310       << SourceRange(Loc, NameInfo.getEndLoc());
2311 
2312     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2313     // context.
2314     if (!RecoveryTSI)
2315       return ExprError();
2316 
2317     // Only issue the fixit if we're prepared to recover.
2318     D << FixItHint::CreateInsertion(Loc, "typename ");
2319 
2320     // Recover by pretending this was an elaborated type.
2321     QualType Ty = Context.getTypeDeclType(TD);
2322     TypeLocBuilder TLB;
2323     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2324 
2325     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2326     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2327     QTL.setElaboratedKeywordLoc(SourceLocation());
2328     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2329 
2330     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2331 
2332     return ExprEmpty();
2333   }
2334 
2335   // Defend against this resolving to an implicit member access. We usually
2336   // won't get here if this might be a legitimate a class member (we end up in
2337   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2338   // a pointer-to-member or in an unevaluated context in C++11.
2339   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2340     return BuildPossibleImplicitMemberExpr(SS,
2341                                            /*TemplateKWLoc=*/SourceLocation(),
2342                                            R, /*TemplateArgs=*/nullptr, S);
2343 
2344   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2345 }
2346 
2347 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2348 /// detected that we're currently inside an ObjC method.  Perform some
2349 /// additional lookup.
2350 ///
2351 /// Ideally, most of this would be done by lookup, but there's
2352 /// actually quite a lot of extra work involved.
2353 ///
2354 /// Returns a null sentinel to indicate trivial success.
2355 ExprResult
2356 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2357                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2358   SourceLocation Loc = Lookup.getNameLoc();
2359   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2360 
2361   // Check for error condition which is already reported.
2362   if (!CurMethod)
2363     return ExprError();
2364 
2365   // There are two cases to handle here.  1) scoped lookup could have failed,
2366   // in which case we should look for an ivar.  2) scoped lookup could have
2367   // found a decl, but that decl is outside the current instance method (i.e.
2368   // a global variable).  In these two cases, we do a lookup for an ivar with
2369   // this name, if the lookup sucedes, we replace it our current decl.
2370 
2371   // If we're in a class method, we don't normally want to look for
2372   // ivars.  But if we don't find anything else, and there's an
2373   // ivar, that's an error.
2374   bool IsClassMethod = CurMethod->isClassMethod();
2375 
2376   bool LookForIvars;
2377   if (Lookup.empty())
2378     LookForIvars = true;
2379   else if (IsClassMethod)
2380     LookForIvars = false;
2381   else
2382     LookForIvars = (Lookup.isSingleResult() &&
2383                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2384   ObjCInterfaceDecl *IFace = nullptr;
2385   if (LookForIvars) {
2386     IFace = CurMethod->getClassInterface();
2387     ObjCInterfaceDecl *ClassDeclared;
2388     ObjCIvarDecl *IV = nullptr;
2389     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2390       // Diagnose using an ivar in a class method.
2391       if (IsClassMethod)
2392         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2393                          << IV->getDeclName());
2394 
2395       // If we're referencing an invalid decl, just return this as a silent
2396       // error node.  The error diagnostic was already emitted on the decl.
2397       if (IV->isInvalidDecl())
2398         return ExprError();
2399 
2400       // Check if referencing a field with __attribute__((deprecated)).
2401       if (DiagnoseUseOfDecl(IV, Loc))
2402         return ExprError();
2403 
2404       // Diagnose the use of an ivar outside of the declaring class.
2405       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2406           !declaresSameEntity(ClassDeclared, IFace) &&
2407           !getLangOpts().DebuggerSupport)
2408         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2409 
2410       // FIXME: This should use a new expr for a direct reference, don't
2411       // turn this into Self->ivar, just return a BareIVarExpr or something.
2412       IdentifierInfo &II = Context.Idents.get("self");
2413       UnqualifiedId SelfName;
2414       SelfName.setIdentifier(&II, SourceLocation());
2415       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2416       CXXScopeSpec SelfScopeSpec;
2417       SourceLocation TemplateKWLoc;
2418       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2419                                               SelfName, false, false);
2420       if (SelfExpr.isInvalid())
2421         return ExprError();
2422 
2423       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2424       if (SelfExpr.isInvalid())
2425         return ExprError();
2426 
2427       MarkAnyDeclReferenced(Loc, IV, true);
2428 
2429       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2430       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2431           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2432         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2433 
2434       ObjCIvarRefExpr *Result = new (Context)
2435           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2436                           IV->getLocation(), SelfExpr.get(), true, true);
2437 
2438       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2439         if (!isUnevaluatedContext() &&
2440             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2441           getCurFunction()->recordUseOfWeak(Result);
2442       }
2443       if (getLangOpts().ObjCAutoRefCount) {
2444         if (CurContext->isClosure())
2445           Diag(Loc, diag::warn_implicitly_retains_self)
2446             << FixItHint::CreateInsertion(Loc, "self->");
2447       }
2448 
2449       return Result;
2450     }
2451   } else if (CurMethod->isInstanceMethod()) {
2452     // We should warn if a local variable hides an ivar.
2453     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2454       ObjCInterfaceDecl *ClassDeclared;
2455       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2456         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2457             declaresSameEntity(IFace, ClassDeclared))
2458           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2459       }
2460     }
2461   } else if (Lookup.isSingleResult() &&
2462              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2463     // If accessing a stand-alone ivar in a class method, this is an error.
2464     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2465       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2466                        << IV->getDeclName());
2467   }
2468 
2469   if (Lookup.empty() && II && AllowBuiltinCreation) {
2470     // FIXME. Consolidate this with similar code in LookupName.
2471     if (unsigned BuiltinID = II->getBuiltinID()) {
2472       if (!(getLangOpts().CPlusPlus &&
2473             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2474         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2475                                            S, Lookup.isForRedeclaration(),
2476                                            Lookup.getNameLoc());
2477         if (D) Lookup.addDecl(D);
2478       }
2479     }
2480   }
2481   // Sentinel value saying that we didn't do anything special.
2482   return ExprResult((Expr *)nullptr);
2483 }
2484 
2485 /// Cast a base object to a member's actual type.
2486 ///
2487 /// Logically this happens in three phases:
2488 ///
2489 /// * First we cast from the base type to the naming class.
2490 ///   The naming class is the class into which we were looking
2491 ///   when we found the member;  it's the qualifier type if a
2492 ///   qualifier was provided, and otherwise it's the base type.
2493 ///
2494 /// * Next we cast from the naming class to the declaring class.
2495 ///   If the member we found was brought into a class's scope by
2496 ///   a using declaration, this is that class;  otherwise it's
2497 ///   the class declaring the member.
2498 ///
2499 /// * Finally we cast from the declaring class to the "true"
2500 ///   declaring class of the member.  This conversion does not
2501 ///   obey access control.
2502 ExprResult
2503 Sema::PerformObjectMemberConversion(Expr *From,
2504                                     NestedNameSpecifier *Qualifier,
2505                                     NamedDecl *FoundDecl,
2506                                     NamedDecl *Member) {
2507   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2508   if (!RD)
2509     return From;
2510 
2511   QualType DestRecordType;
2512   QualType DestType;
2513   QualType FromRecordType;
2514   QualType FromType = From->getType();
2515   bool PointerConversions = false;
2516   if (isa<FieldDecl>(Member)) {
2517     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2518 
2519     if (FromType->getAs<PointerType>()) {
2520       DestType = Context.getPointerType(DestRecordType);
2521       FromRecordType = FromType->getPointeeType();
2522       PointerConversions = true;
2523     } else {
2524       DestType = DestRecordType;
2525       FromRecordType = FromType;
2526     }
2527   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2528     if (Method->isStatic())
2529       return From;
2530 
2531     DestType = Method->getThisType(Context);
2532     DestRecordType = DestType->getPointeeType();
2533 
2534     if (FromType->getAs<PointerType>()) {
2535       FromRecordType = FromType->getPointeeType();
2536       PointerConversions = true;
2537     } else {
2538       FromRecordType = FromType;
2539       DestType = DestRecordType;
2540     }
2541   } else {
2542     // No conversion necessary.
2543     return From;
2544   }
2545 
2546   if (DestType->isDependentType() || FromType->isDependentType())
2547     return From;
2548 
2549   // If the unqualified types are the same, no conversion is necessary.
2550   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2551     return From;
2552 
2553   SourceRange FromRange = From->getSourceRange();
2554   SourceLocation FromLoc = FromRange.getBegin();
2555 
2556   ExprValueKind VK = From->getValueKind();
2557 
2558   // C++ [class.member.lookup]p8:
2559   //   [...] Ambiguities can often be resolved by qualifying a name with its
2560   //   class name.
2561   //
2562   // If the member was a qualified name and the qualified referred to a
2563   // specific base subobject type, we'll cast to that intermediate type
2564   // first and then to the object in which the member is declared. That allows
2565   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2566   //
2567   //   class Base { public: int x; };
2568   //   class Derived1 : public Base { };
2569   //   class Derived2 : public Base { };
2570   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2571   //
2572   //   void VeryDerived::f() {
2573   //     x = 17; // error: ambiguous base subobjects
2574   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2575   //   }
2576   if (Qualifier && Qualifier->getAsType()) {
2577     QualType QType = QualType(Qualifier->getAsType(), 0);
2578     assert(QType->isRecordType() && "lookup done with non-record type");
2579 
2580     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2581 
2582     // In C++98, the qualifier type doesn't actually have to be a base
2583     // type of the object type, in which case we just ignore it.
2584     // Otherwise build the appropriate casts.
2585     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2586       CXXCastPath BasePath;
2587       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2588                                        FromLoc, FromRange, &BasePath))
2589         return ExprError();
2590 
2591       if (PointerConversions)
2592         QType = Context.getPointerType(QType);
2593       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2594                                VK, &BasePath).get();
2595 
2596       FromType = QType;
2597       FromRecordType = QRecordType;
2598 
2599       // If the qualifier type was the same as the destination type,
2600       // we're done.
2601       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2602         return From;
2603     }
2604   }
2605 
2606   bool IgnoreAccess = false;
2607 
2608   // If we actually found the member through a using declaration, cast
2609   // down to the using declaration's type.
2610   //
2611   // Pointer equality is fine here because only one declaration of a
2612   // class ever has member declarations.
2613   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2614     assert(isa<UsingShadowDecl>(FoundDecl));
2615     QualType URecordType = Context.getTypeDeclType(
2616                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2617 
2618     // We only need to do this if the naming-class to declaring-class
2619     // conversion is non-trivial.
2620     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2621       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2622       CXXCastPath BasePath;
2623       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2624                                        FromLoc, FromRange, &BasePath))
2625         return ExprError();
2626 
2627       QualType UType = URecordType;
2628       if (PointerConversions)
2629         UType = Context.getPointerType(UType);
2630       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2631                                VK, &BasePath).get();
2632       FromType = UType;
2633       FromRecordType = URecordType;
2634     }
2635 
2636     // We don't do access control for the conversion from the
2637     // declaring class to the true declaring class.
2638     IgnoreAccess = true;
2639   }
2640 
2641   CXXCastPath BasePath;
2642   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2643                                    FromLoc, FromRange, &BasePath,
2644                                    IgnoreAccess))
2645     return ExprError();
2646 
2647   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2648                            VK, &BasePath);
2649 }
2650 
2651 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2652                                       const LookupResult &R,
2653                                       bool HasTrailingLParen) {
2654   // Only when used directly as the postfix-expression of a call.
2655   if (!HasTrailingLParen)
2656     return false;
2657 
2658   // Never if a scope specifier was provided.
2659   if (SS.isSet())
2660     return false;
2661 
2662   // Only in C++ or ObjC++.
2663   if (!getLangOpts().CPlusPlus)
2664     return false;
2665 
2666   // Turn off ADL when we find certain kinds of declarations during
2667   // normal lookup:
2668   for (NamedDecl *D : R) {
2669     // C++0x [basic.lookup.argdep]p3:
2670     //     -- a declaration of a class member
2671     // Since using decls preserve this property, we check this on the
2672     // original decl.
2673     if (D->isCXXClassMember())
2674       return false;
2675 
2676     // C++0x [basic.lookup.argdep]p3:
2677     //     -- a block-scope function declaration that is not a
2678     //        using-declaration
2679     // NOTE: we also trigger this for function templates (in fact, we
2680     // don't check the decl type at all, since all other decl types
2681     // turn off ADL anyway).
2682     if (isa<UsingShadowDecl>(D))
2683       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2684     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2685       return false;
2686 
2687     // C++0x [basic.lookup.argdep]p3:
2688     //     -- a declaration that is neither a function or a function
2689     //        template
2690     // And also for builtin functions.
2691     if (isa<FunctionDecl>(D)) {
2692       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2693 
2694       // But also builtin functions.
2695       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2696         return false;
2697     } else if (!isa<FunctionTemplateDecl>(D))
2698       return false;
2699   }
2700 
2701   return true;
2702 }
2703 
2704 
2705 /// Diagnoses obvious problems with the use of the given declaration
2706 /// as an expression.  This is only actually called for lookups that
2707 /// were not overloaded, and it doesn't promise that the declaration
2708 /// will in fact be used.
2709 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2710   if (D->isInvalidDecl())
2711     return true;
2712 
2713   if (isa<TypedefNameDecl>(D)) {
2714     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2715     return true;
2716   }
2717 
2718   if (isa<ObjCInterfaceDecl>(D)) {
2719     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2720     return true;
2721   }
2722 
2723   if (isa<NamespaceDecl>(D)) {
2724     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2725     return true;
2726   }
2727 
2728   return false;
2729 }
2730 
2731 // Certain multiversion types should be treated as overloaded even when there is
2732 // only one result.
2733 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2734   assert(R.isSingleResult() && "Expected only a single result");
2735   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2736   return FD &&
2737          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2738 }
2739 
2740 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2741                                           LookupResult &R, bool NeedsADL,
2742                                           bool AcceptInvalidDecl) {
2743   // If this is a single, fully-resolved result and we don't need ADL,
2744   // just build an ordinary singleton decl ref.
2745   if (!NeedsADL && R.isSingleResult() &&
2746       !R.getAsSingle<FunctionTemplateDecl>() &&
2747       !ShouldLookupResultBeMultiVersionOverload(R))
2748     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2749                                     R.getRepresentativeDecl(), nullptr,
2750                                     AcceptInvalidDecl);
2751 
2752   // We only need to check the declaration if there's exactly one
2753   // result, because in the overloaded case the results can only be
2754   // functions and function templates.
2755   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2756       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2757     return ExprError();
2758 
2759   // Otherwise, just build an unresolved lookup expression.  Suppress
2760   // any lookup-related diagnostics; we'll hash these out later, when
2761   // we've picked a target.
2762   R.suppressDiagnostics();
2763 
2764   UnresolvedLookupExpr *ULE
2765     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2766                                    SS.getWithLocInContext(Context),
2767                                    R.getLookupNameInfo(),
2768                                    NeedsADL, R.isOverloadedResult(),
2769                                    R.begin(), R.end());
2770 
2771   return ULE;
2772 }
2773 
2774 static void
2775 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2776                                    ValueDecl *var, DeclContext *DC);
2777 
2778 /// Complete semantic analysis for a reference to the given declaration.
2779 ExprResult Sema::BuildDeclarationNameExpr(
2780     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2781     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2782     bool AcceptInvalidDecl) {
2783   assert(D && "Cannot refer to a NULL declaration");
2784   assert(!isa<FunctionTemplateDecl>(D) &&
2785          "Cannot refer unambiguously to a function template");
2786 
2787   SourceLocation Loc = NameInfo.getLoc();
2788   if (CheckDeclInExpr(*this, Loc, D))
2789     return ExprError();
2790 
2791   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2792     // Specifically diagnose references to class templates that are missing
2793     // a template argument list.
2794     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2795     return ExprError();
2796   }
2797 
2798   // Make sure that we're referring to a value.
2799   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2800   if (!VD) {
2801     Diag(Loc, diag::err_ref_non_value)
2802       << D << SS.getRange();
2803     Diag(D->getLocation(), diag::note_declared_at);
2804     return ExprError();
2805   }
2806 
2807   // Check whether this declaration can be used. Note that we suppress
2808   // this check when we're going to perform argument-dependent lookup
2809   // on this function name, because this might not be the function
2810   // that overload resolution actually selects.
2811   if (DiagnoseUseOfDecl(VD, Loc))
2812     return ExprError();
2813 
2814   // Only create DeclRefExpr's for valid Decl's.
2815   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2816     return ExprError();
2817 
2818   // Handle members of anonymous structs and unions.  If we got here,
2819   // and the reference is to a class member indirect field, then this
2820   // must be the subject of a pointer-to-member expression.
2821   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2822     if (!indirectField->isCXXClassMember())
2823       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2824                                                       indirectField);
2825 
2826   {
2827     QualType type = VD->getType();
2828     if (type.isNull())
2829       return ExprError();
2830     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2831       // C++ [except.spec]p17:
2832       //   An exception-specification is considered to be needed when:
2833       //   - in an expression, the function is the unique lookup result or
2834       //     the selected member of a set of overloaded functions.
2835       ResolveExceptionSpec(Loc, FPT);
2836       type = VD->getType();
2837     }
2838     ExprValueKind valueKind = VK_RValue;
2839 
2840     switch (D->getKind()) {
2841     // Ignore all the non-ValueDecl kinds.
2842 #define ABSTRACT_DECL(kind)
2843 #define VALUE(type, base)
2844 #define DECL(type, base) \
2845     case Decl::type:
2846 #include "clang/AST/DeclNodes.inc"
2847       llvm_unreachable("invalid value decl kind");
2848 
2849     // These shouldn't make it here.
2850     case Decl::ObjCAtDefsField:
2851     case Decl::ObjCIvar:
2852       llvm_unreachable("forming non-member reference to ivar?");
2853 
2854     // Enum constants are always r-values and never references.
2855     // Unresolved using declarations are dependent.
2856     case Decl::EnumConstant:
2857     case Decl::UnresolvedUsingValue:
2858     case Decl::OMPDeclareReduction:
2859       valueKind = VK_RValue;
2860       break;
2861 
2862     // Fields and indirect fields that got here must be for
2863     // pointer-to-member expressions; we just call them l-values for
2864     // internal consistency, because this subexpression doesn't really
2865     // exist in the high-level semantics.
2866     case Decl::Field:
2867     case Decl::IndirectField:
2868       assert(getLangOpts().CPlusPlus &&
2869              "building reference to field in C?");
2870 
2871       // These can't have reference type in well-formed programs, but
2872       // for internal consistency we do this anyway.
2873       type = type.getNonReferenceType();
2874       valueKind = VK_LValue;
2875       break;
2876 
2877     // Non-type template parameters are either l-values or r-values
2878     // depending on the type.
2879     case Decl::NonTypeTemplateParm: {
2880       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2881         type = reftype->getPointeeType();
2882         valueKind = VK_LValue; // even if the parameter is an r-value reference
2883         break;
2884       }
2885 
2886       // For non-references, we need to strip qualifiers just in case
2887       // the template parameter was declared as 'const int' or whatever.
2888       valueKind = VK_RValue;
2889       type = type.getUnqualifiedType();
2890       break;
2891     }
2892 
2893     case Decl::Var:
2894     case Decl::VarTemplateSpecialization:
2895     case Decl::VarTemplatePartialSpecialization:
2896     case Decl::Decomposition:
2897     case Decl::OMPCapturedExpr:
2898       // In C, "extern void blah;" is valid and is an r-value.
2899       if (!getLangOpts().CPlusPlus &&
2900           !type.hasQualifiers() &&
2901           type->isVoidType()) {
2902         valueKind = VK_RValue;
2903         break;
2904       }
2905       LLVM_FALLTHROUGH;
2906 
2907     case Decl::ImplicitParam:
2908     case Decl::ParmVar: {
2909       // These are always l-values.
2910       valueKind = VK_LValue;
2911       type = type.getNonReferenceType();
2912 
2913       // FIXME: Does the addition of const really only apply in
2914       // potentially-evaluated contexts? Since the variable isn't actually
2915       // captured in an unevaluated context, it seems that the answer is no.
2916       if (!isUnevaluatedContext()) {
2917         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2918         if (!CapturedType.isNull())
2919           type = CapturedType;
2920       }
2921 
2922       break;
2923     }
2924 
2925     case Decl::Binding: {
2926       // These are always lvalues.
2927       valueKind = VK_LValue;
2928       type = type.getNonReferenceType();
2929       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2930       // decides how that's supposed to work.
2931       auto *BD = cast<BindingDecl>(VD);
2932       if (BD->getDeclContext()->isFunctionOrMethod() &&
2933           BD->getDeclContext() != CurContext)
2934         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2935       break;
2936     }
2937 
2938     case Decl::Function: {
2939       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2940         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2941           type = Context.BuiltinFnTy;
2942           valueKind = VK_RValue;
2943           break;
2944         }
2945       }
2946 
2947       const FunctionType *fty = type->castAs<FunctionType>();
2948 
2949       // If we're referring to a function with an __unknown_anytype
2950       // result type, make the entire expression __unknown_anytype.
2951       if (fty->getReturnType() == Context.UnknownAnyTy) {
2952         type = Context.UnknownAnyTy;
2953         valueKind = VK_RValue;
2954         break;
2955       }
2956 
2957       // Functions are l-values in C++.
2958       if (getLangOpts().CPlusPlus) {
2959         valueKind = VK_LValue;
2960         break;
2961       }
2962 
2963       // C99 DR 316 says that, if a function type comes from a
2964       // function definition (without a prototype), that type is only
2965       // used for checking compatibility. Therefore, when referencing
2966       // the function, we pretend that we don't have the full function
2967       // type.
2968       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2969           isa<FunctionProtoType>(fty))
2970         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2971                                               fty->getExtInfo());
2972 
2973       // Functions are r-values in C.
2974       valueKind = VK_RValue;
2975       break;
2976     }
2977 
2978     case Decl::CXXDeductionGuide:
2979       llvm_unreachable("building reference to deduction guide");
2980 
2981     case Decl::MSProperty:
2982       valueKind = VK_LValue;
2983       break;
2984 
2985     case Decl::CXXMethod:
2986       // If we're referring to a method with an __unknown_anytype
2987       // result type, make the entire expression __unknown_anytype.
2988       // This should only be possible with a type written directly.
2989       if (const FunctionProtoType *proto
2990             = dyn_cast<FunctionProtoType>(VD->getType()))
2991         if (proto->getReturnType() == Context.UnknownAnyTy) {
2992           type = Context.UnknownAnyTy;
2993           valueKind = VK_RValue;
2994           break;
2995         }
2996 
2997       // C++ methods are l-values if static, r-values if non-static.
2998       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2999         valueKind = VK_LValue;
3000         break;
3001       }
3002       LLVM_FALLTHROUGH;
3003 
3004     case Decl::CXXConversion:
3005     case Decl::CXXDestructor:
3006     case Decl::CXXConstructor:
3007       valueKind = VK_RValue;
3008       break;
3009     }
3010 
3011     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3012                             TemplateArgs);
3013   }
3014 }
3015 
3016 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3017                                     SmallString<32> &Target) {
3018   Target.resize(CharByteWidth * (Source.size() + 1));
3019   char *ResultPtr = &Target[0];
3020   const llvm::UTF8 *ErrorPtr;
3021   bool success =
3022       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3023   (void)success;
3024   assert(success);
3025   Target.resize(ResultPtr - &Target[0]);
3026 }
3027 
3028 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3029                                      PredefinedExpr::IdentType IT) {
3030   // Pick the current block, lambda, captured statement or function.
3031   Decl *currentDecl = nullptr;
3032   if (const BlockScopeInfo *BSI = getCurBlock())
3033     currentDecl = BSI->TheDecl;
3034   else if (const LambdaScopeInfo *LSI = getCurLambda())
3035     currentDecl = LSI->CallOperator;
3036   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3037     currentDecl = CSI->TheCapturedDecl;
3038   else
3039     currentDecl = getCurFunctionOrMethodDecl();
3040 
3041   if (!currentDecl) {
3042     Diag(Loc, diag::ext_predef_outside_function);
3043     currentDecl = Context.getTranslationUnitDecl();
3044   }
3045 
3046   QualType ResTy;
3047   StringLiteral *SL = nullptr;
3048   if (cast<DeclContext>(currentDecl)->isDependentContext())
3049     ResTy = Context.DependentTy;
3050   else {
3051     // Pre-defined identifiers are of type char[x], where x is the length of
3052     // the string.
3053     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3054     unsigned Length = Str.length();
3055 
3056     llvm::APInt LengthI(32, Length + 1);
3057     if (IT == PredefinedExpr::LFunction) {
3058       ResTy =
3059           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3060       SmallString<32> RawChars;
3061       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3062                               Str, RawChars);
3063       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3064                                            /*IndexTypeQuals*/ 0);
3065       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3066                                  /*Pascal*/ false, ResTy, Loc);
3067     } else {
3068       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3069       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3070                                            /*IndexTypeQuals*/ 0);
3071       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3072                                  /*Pascal*/ false, ResTy, Loc);
3073     }
3074   }
3075 
3076   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3077 }
3078 
3079 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3080   PredefinedExpr::IdentType IT;
3081 
3082   switch (Kind) {
3083   default: llvm_unreachable("Unknown simple primary expr!");
3084   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3085   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3086   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3087   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3088   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3089   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3090   }
3091 
3092   return BuildPredefinedExpr(Loc, IT);
3093 }
3094 
3095 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3096   SmallString<16> CharBuffer;
3097   bool Invalid = false;
3098   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3099   if (Invalid)
3100     return ExprError();
3101 
3102   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3103                             PP, Tok.getKind());
3104   if (Literal.hadError())
3105     return ExprError();
3106 
3107   QualType Ty;
3108   if (Literal.isWide())
3109     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3110   else if (Literal.isUTF8() && getLangOpts().Char8)
3111     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3112   else if (Literal.isUTF16())
3113     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3114   else if (Literal.isUTF32())
3115     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3116   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3117     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3118   else
3119     Ty = Context.CharTy;  // 'x' -> char in C++
3120 
3121   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3122   if (Literal.isWide())
3123     Kind = CharacterLiteral::Wide;
3124   else if (Literal.isUTF16())
3125     Kind = CharacterLiteral::UTF16;
3126   else if (Literal.isUTF32())
3127     Kind = CharacterLiteral::UTF32;
3128   else if (Literal.isUTF8())
3129     Kind = CharacterLiteral::UTF8;
3130 
3131   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3132                                              Tok.getLocation());
3133 
3134   if (Literal.getUDSuffix().empty())
3135     return Lit;
3136 
3137   // We're building a user-defined literal.
3138   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3139   SourceLocation UDSuffixLoc =
3140     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3141 
3142   // Make sure we're allowed user-defined literals here.
3143   if (!UDLScope)
3144     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3145 
3146   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3147   //   operator "" X (ch)
3148   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3149                                         Lit, Tok.getLocation());
3150 }
3151 
3152 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3153   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3154   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3155                                 Context.IntTy, Loc);
3156 }
3157 
3158 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3159                                   QualType Ty, SourceLocation Loc) {
3160   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3161 
3162   using llvm::APFloat;
3163   APFloat Val(Format);
3164 
3165   APFloat::opStatus result = Literal.GetFloatValue(Val);
3166 
3167   // Overflow is always an error, but underflow is only an error if
3168   // we underflowed to zero (APFloat reports denormals as underflow).
3169   if ((result & APFloat::opOverflow) ||
3170       ((result & APFloat::opUnderflow) && Val.isZero())) {
3171     unsigned diagnostic;
3172     SmallString<20> buffer;
3173     if (result & APFloat::opOverflow) {
3174       diagnostic = diag::warn_float_overflow;
3175       APFloat::getLargest(Format).toString(buffer);
3176     } else {
3177       diagnostic = diag::warn_float_underflow;
3178       APFloat::getSmallest(Format).toString(buffer);
3179     }
3180 
3181     S.Diag(Loc, diagnostic)
3182       << Ty
3183       << StringRef(buffer.data(), buffer.size());
3184   }
3185 
3186   bool isExact = (result == APFloat::opOK);
3187   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3188 }
3189 
3190 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3191   assert(E && "Invalid expression");
3192 
3193   if (E->isValueDependent())
3194     return false;
3195 
3196   QualType QT = E->getType();
3197   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3198     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3199     return true;
3200   }
3201 
3202   llvm::APSInt ValueAPS;
3203   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3204 
3205   if (R.isInvalid())
3206     return true;
3207 
3208   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3209   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3210     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3211         << ValueAPS.toString(10) << ValueIsPositive;
3212     return true;
3213   }
3214 
3215   return false;
3216 }
3217 
3218 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3219   // Fast path for a single digit (which is quite common).  A single digit
3220   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3221   if (Tok.getLength() == 1) {
3222     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3223     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3224   }
3225 
3226   SmallString<128> SpellingBuffer;
3227   // NumericLiteralParser wants to overread by one character.  Add padding to
3228   // the buffer in case the token is copied to the buffer.  If getSpelling()
3229   // returns a StringRef to the memory buffer, it should have a null char at
3230   // the EOF, so it is also safe.
3231   SpellingBuffer.resize(Tok.getLength() + 1);
3232 
3233   // Get the spelling of the token, which eliminates trigraphs, etc.
3234   bool Invalid = false;
3235   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3236   if (Invalid)
3237     return ExprError();
3238 
3239   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3240   if (Literal.hadError)
3241     return ExprError();
3242 
3243   if (Literal.hasUDSuffix()) {
3244     // We're building a user-defined literal.
3245     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3246     SourceLocation UDSuffixLoc =
3247       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3248 
3249     // Make sure we're allowed user-defined literals here.
3250     if (!UDLScope)
3251       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3252 
3253     QualType CookedTy;
3254     if (Literal.isFloatingLiteral()) {
3255       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3256       // long double, the literal is treated as a call of the form
3257       //   operator "" X (f L)
3258       CookedTy = Context.LongDoubleTy;
3259     } else {
3260       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3261       // unsigned long long, the literal is treated as a call of the form
3262       //   operator "" X (n ULL)
3263       CookedTy = Context.UnsignedLongLongTy;
3264     }
3265 
3266     DeclarationName OpName =
3267       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3268     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3269     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3270 
3271     SourceLocation TokLoc = Tok.getLocation();
3272 
3273     // Perform literal operator lookup to determine if we're building a raw
3274     // literal or a cooked one.
3275     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3276     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3277                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3278                                   /*AllowStringTemplate*/ false,
3279                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3280     case LOLR_ErrorNoDiagnostic:
3281       // Lookup failure for imaginary constants isn't fatal, there's still the
3282       // GNU extension producing _Complex types.
3283       break;
3284     case LOLR_Error:
3285       return ExprError();
3286     case LOLR_Cooked: {
3287       Expr *Lit;
3288       if (Literal.isFloatingLiteral()) {
3289         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3290       } else {
3291         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3292         if (Literal.GetIntegerValue(ResultVal))
3293           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3294               << /* Unsigned */ 1;
3295         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3296                                      Tok.getLocation());
3297       }
3298       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3299     }
3300 
3301     case LOLR_Raw: {
3302       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3303       // literal is treated as a call of the form
3304       //   operator "" X ("n")
3305       unsigned Length = Literal.getUDSuffixOffset();
3306       QualType StrTy = Context.getConstantArrayType(
3307           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3308           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3309       Expr *Lit = StringLiteral::Create(
3310           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3311           /*Pascal*/false, StrTy, &TokLoc, 1);
3312       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3313     }
3314 
3315     case LOLR_Template: {
3316       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3317       // template), L is treated as a call fo the form
3318       //   operator "" X <'c1', 'c2', ... 'ck'>()
3319       // where n is the source character sequence c1 c2 ... ck.
3320       TemplateArgumentListInfo ExplicitArgs;
3321       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3322       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3323       llvm::APSInt Value(CharBits, CharIsUnsigned);
3324       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3325         Value = TokSpelling[I];
3326         TemplateArgument Arg(Context, Value, Context.CharTy);
3327         TemplateArgumentLocInfo ArgInfo;
3328         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3329       }
3330       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3331                                       &ExplicitArgs);
3332     }
3333     case LOLR_StringTemplate:
3334       llvm_unreachable("unexpected literal operator lookup result");
3335     }
3336   }
3337 
3338   Expr *Res;
3339 
3340   if (Literal.isFixedPointLiteral()) {
3341     QualType Ty;
3342 
3343     if (Literal.isAccum) {
3344       if (Literal.isHalf) {
3345         Ty = Context.ShortAccumTy;
3346       } else if (Literal.isLong) {
3347         Ty = Context.LongAccumTy;
3348       } else {
3349         Ty = Context.AccumTy;
3350       }
3351     } else if (Literal.isFract) {
3352       if (Literal.isHalf) {
3353         Ty = Context.ShortFractTy;
3354       } else if (Literal.isLong) {
3355         Ty = Context.LongFractTy;
3356       } else {
3357         Ty = Context.FractTy;
3358       }
3359     }
3360 
3361     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3362 
3363     bool isSigned = !Literal.isUnsigned;
3364     unsigned scale = Context.getFixedPointScale(Ty);
3365     unsigned ibits = Context.getFixedPointIBits(Ty);
3366     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3367 
3368     llvm::APInt Val(bit_width, 0, isSigned);
3369     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3370 
3371     // Do not use bit_width since some types may have padding like _Fract or
3372     // unsigned _Accums if PaddingOnUnsignedFixedPoint is set.
3373     auto MaxVal = llvm::APInt::getMaxValue(ibits + scale).zextOrSelf(bit_width);
3374     if (Literal.isFract && Val == MaxVal + 1)
3375       // Clause 6.4.4 - The value of a constant shall be in the range of
3376       // representable values for its type, with exception for constants of a
3377       // fract type with a value of exactly 1; such a constant shall denote
3378       // the maximal value for the type.
3379       --Val;
3380     else if (Val.ugt(MaxVal) || Overflowed)
3381       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3382 
3383     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3384                                               Tok.getLocation(), scale);
3385   } else if (Literal.isFloatingLiteral()) {
3386     QualType Ty;
3387     if (Literal.isHalf){
3388       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3389         Ty = Context.HalfTy;
3390       else {
3391         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3392         return ExprError();
3393       }
3394     } else if (Literal.isFloat)
3395       Ty = Context.FloatTy;
3396     else if (Literal.isLong)
3397       Ty = Context.LongDoubleTy;
3398     else if (Literal.isFloat16)
3399       Ty = Context.Float16Ty;
3400     else if (Literal.isFloat128)
3401       Ty = Context.Float128Ty;
3402     else
3403       Ty = Context.DoubleTy;
3404 
3405     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3406 
3407     if (Ty == Context.DoubleTy) {
3408       if (getLangOpts().SinglePrecisionConstants) {
3409         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3410         if (BTy->getKind() != BuiltinType::Float) {
3411           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3412         }
3413       } else if (getLangOpts().OpenCL &&
3414                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3415         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3416         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3417         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3418       }
3419     }
3420   } else if (!Literal.isIntegerLiteral()) {
3421     return ExprError();
3422   } else {
3423     QualType Ty;
3424 
3425     // 'long long' is a C99 or C++11 feature.
3426     if (!getLangOpts().C99 && Literal.isLongLong) {
3427       if (getLangOpts().CPlusPlus)
3428         Diag(Tok.getLocation(),
3429              getLangOpts().CPlusPlus11 ?
3430              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3431       else
3432         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3433     }
3434 
3435     // Get the value in the widest-possible width.
3436     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3437     llvm::APInt ResultVal(MaxWidth, 0);
3438 
3439     if (Literal.GetIntegerValue(ResultVal)) {
3440       // If this value didn't fit into uintmax_t, error and force to ull.
3441       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3442           << /* Unsigned */ 1;
3443       Ty = Context.UnsignedLongLongTy;
3444       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3445              "long long is not intmax_t?");
3446     } else {
3447       // If this value fits into a ULL, try to figure out what else it fits into
3448       // according to the rules of C99 6.4.4.1p5.
3449 
3450       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3451       // be an unsigned int.
3452       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3453 
3454       // Check from smallest to largest, picking the smallest type we can.
3455       unsigned Width = 0;
3456 
3457       // Microsoft specific integer suffixes are explicitly sized.
3458       if (Literal.MicrosoftInteger) {
3459         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3460           Width = 8;
3461           Ty = Context.CharTy;
3462         } else {
3463           Width = Literal.MicrosoftInteger;
3464           Ty = Context.getIntTypeForBitwidth(Width,
3465                                              /*Signed=*/!Literal.isUnsigned);
3466         }
3467       }
3468 
3469       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3470         // Are int/unsigned possibilities?
3471         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3472 
3473         // Does it fit in a unsigned int?
3474         if (ResultVal.isIntN(IntSize)) {
3475           // Does it fit in a signed int?
3476           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3477             Ty = Context.IntTy;
3478           else if (AllowUnsigned)
3479             Ty = Context.UnsignedIntTy;
3480           Width = IntSize;
3481         }
3482       }
3483 
3484       // Are long/unsigned long possibilities?
3485       if (Ty.isNull() && !Literal.isLongLong) {
3486         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3487 
3488         // Does it fit in a unsigned long?
3489         if (ResultVal.isIntN(LongSize)) {
3490           // Does it fit in a signed long?
3491           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3492             Ty = Context.LongTy;
3493           else if (AllowUnsigned)
3494             Ty = Context.UnsignedLongTy;
3495           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3496           // is compatible.
3497           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3498             const unsigned LongLongSize =
3499                 Context.getTargetInfo().getLongLongWidth();
3500             Diag(Tok.getLocation(),
3501                  getLangOpts().CPlusPlus
3502                      ? Literal.isLong
3503                            ? diag::warn_old_implicitly_unsigned_long_cxx
3504                            : /*C++98 UB*/ diag::
3505                                  ext_old_implicitly_unsigned_long_cxx
3506                      : diag::warn_old_implicitly_unsigned_long)
3507                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3508                                             : /*will be ill-formed*/ 1);
3509             Ty = Context.UnsignedLongTy;
3510           }
3511           Width = LongSize;
3512         }
3513       }
3514 
3515       // Check long long if needed.
3516       if (Ty.isNull()) {
3517         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3518 
3519         // Does it fit in a unsigned long long?
3520         if (ResultVal.isIntN(LongLongSize)) {
3521           // Does it fit in a signed long long?
3522           // To be compatible with MSVC, hex integer literals ending with the
3523           // LL or i64 suffix are always signed in Microsoft mode.
3524           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3525               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3526             Ty = Context.LongLongTy;
3527           else if (AllowUnsigned)
3528             Ty = Context.UnsignedLongLongTy;
3529           Width = LongLongSize;
3530         }
3531       }
3532 
3533       // If we still couldn't decide a type, we probably have something that
3534       // does not fit in a signed long long, but has no U suffix.
3535       if (Ty.isNull()) {
3536         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3537         Ty = Context.UnsignedLongLongTy;
3538         Width = Context.getTargetInfo().getLongLongWidth();
3539       }
3540 
3541       if (ResultVal.getBitWidth() != Width)
3542         ResultVal = ResultVal.trunc(Width);
3543     }
3544     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3545   }
3546 
3547   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3548   if (Literal.isImaginary) {
3549     Res = new (Context) ImaginaryLiteral(Res,
3550                                         Context.getComplexType(Res->getType()));
3551 
3552     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3553   }
3554   return Res;
3555 }
3556 
3557 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3558   assert(E && "ActOnParenExpr() missing expr");
3559   return new (Context) ParenExpr(L, R, E);
3560 }
3561 
3562 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3563                                          SourceLocation Loc,
3564                                          SourceRange ArgRange) {
3565   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3566   // scalar or vector data type argument..."
3567   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3568   // type (C99 6.2.5p18) or void.
3569   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3570     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3571       << T << ArgRange;
3572     return true;
3573   }
3574 
3575   assert((T->isVoidType() || !T->isIncompleteType()) &&
3576          "Scalar types should always be complete");
3577   return false;
3578 }
3579 
3580 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3581                                            SourceLocation Loc,
3582                                            SourceRange ArgRange,
3583                                            UnaryExprOrTypeTrait TraitKind) {
3584   // Invalid types must be hard errors for SFINAE in C++.
3585   if (S.LangOpts.CPlusPlus)
3586     return true;
3587 
3588   // C99 6.5.3.4p1:
3589   if (T->isFunctionType() &&
3590       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3591     // sizeof(function)/alignof(function) is allowed as an extension.
3592     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3593       << TraitKind << ArgRange;
3594     return false;
3595   }
3596 
3597   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3598   // this is an error (OpenCL v1.1 s6.3.k)
3599   if (T->isVoidType()) {
3600     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3601                                         : diag::ext_sizeof_alignof_void_type;
3602     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3603     return false;
3604   }
3605 
3606   return true;
3607 }
3608 
3609 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3610                                              SourceLocation Loc,
3611                                              SourceRange ArgRange,
3612                                              UnaryExprOrTypeTrait TraitKind) {
3613   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3614   // runtime doesn't allow it.
3615   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3616     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3617       << T << (TraitKind == UETT_SizeOf)
3618       << ArgRange;
3619     return true;
3620   }
3621 
3622   return false;
3623 }
3624 
3625 /// Check whether E is a pointer from a decayed array type (the decayed
3626 /// pointer type is equal to T) and emit a warning if it is.
3627 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3628                                      Expr *E) {
3629   // Don't warn if the operation changed the type.
3630   if (T != E->getType())
3631     return;
3632 
3633   // Now look for array decays.
3634   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3635   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3636     return;
3637 
3638   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3639                                              << ICE->getType()
3640                                              << ICE->getSubExpr()->getType();
3641 }
3642 
3643 /// Check the constraints on expression operands to unary type expression
3644 /// and type traits.
3645 ///
3646 /// Completes any types necessary and validates the constraints on the operand
3647 /// expression. The logic mostly mirrors the type-based overload, but may modify
3648 /// the expression as it completes the type for that expression through template
3649 /// instantiation, etc.
3650 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3651                                             UnaryExprOrTypeTrait ExprKind) {
3652   QualType ExprTy = E->getType();
3653   assert(!ExprTy->isReferenceType());
3654 
3655   if (ExprKind == UETT_VecStep)
3656     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3657                                         E->getSourceRange());
3658 
3659   // Whitelist some types as extensions
3660   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3661                                       E->getSourceRange(), ExprKind))
3662     return false;
3663 
3664   // 'alignof' applied to an expression only requires the base element type of
3665   // the expression to be complete. 'sizeof' requires the expression's type to
3666   // be complete (and will attempt to complete it if it's an array of unknown
3667   // bound).
3668   if (ExprKind == UETT_AlignOf) {
3669     if (RequireCompleteType(E->getExprLoc(),
3670                             Context.getBaseElementType(E->getType()),
3671                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3672                             E->getSourceRange()))
3673       return true;
3674   } else {
3675     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3676                                 ExprKind, E->getSourceRange()))
3677       return true;
3678   }
3679 
3680   // Completing the expression's type may have changed it.
3681   ExprTy = E->getType();
3682   assert(!ExprTy->isReferenceType());
3683 
3684   if (ExprTy->isFunctionType()) {
3685     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3686       << ExprKind << E->getSourceRange();
3687     return true;
3688   }
3689 
3690   // The operand for sizeof and alignof is in an unevaluated expression context,
3691   // so side effects could result in unintended consequences.
3692   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3693       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3694     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3695 
3696   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3697                                        E->getSourceRange(), ExprKind))
3698     return true;
3699 
3700   if (ExprKind == UETT_SizeOf) {
3701     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3702       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3703         QualType OType = PVD->getOriginalType();
3704         QualType Type = PVD->getType();
3705         if (Type->isPointerType() && OType->isArrayType()) {
3706           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3707             << Type << OType;
3708           Diag(PVD->getLocation(), diag::note_declared_at);
3709         }
3710       }
3711     }
3712 
3713     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3714     // decays into a pointer and returns an unintended result. This is most
3715     // likely a typo for "sizeof(array) op x".
3716     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3717       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3718                                BO->getLHS());
3719       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3720                                BO->getRHS());
3721     }
3722   }
3723 
3724   return false;
3725 }
3726 
3727 /// Check the constraints on operands to unary expression and type
3728 /// traits.
3729 ///
3730 /// This will complete any types necessary, and validate the various constraints
3731 /// on those operands.
3732 ///
3733 /// The UsualUnaryConversions() function is *not* called by this routine.
3734 /// C99 6.3.2.1p[2-4] all state:
3735 ///   Except when it is the operand of the sizeof operator ...
3736 ///
3737 /// C++ [expr.sizeof]p4
3738 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3739 ///   standard conversions are not applied to the operand of sizeof.
3740 ///
3741 /// This policy is followed for all of the unary trait expressions.
3742 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3743                                             SourceLocation OpLoc,
3744                                             SourceRange ExprRange,
3745                                             UnaryExprOrTypeTrait ExprKind) {
3746   if (ExprType->isDependentType())
3747     return false;
3748 
3749   // C++ [expr.sizeof]p2:
3750   //     When applied to a reference or a reference type, the result
3751   //     is the size of the referenced type.
3752   // C++11 [expr.alignof]p3:
3753   //     When alignof is applied to a reference type, the result
3754   //     shall be the alignment of the referenced type.
3755   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3756     ExprType = Ref->getPointeeType();
3757 
3758   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3759   //   When alignof or _Alignof is applied to an array type, the result
3760   //   is the alignment of the element type.
3761   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3762     ExprType = Context.getBaseElementType(ExprType);
3763 
3764   if (ExprKind == UETT_VecStep)
3765     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3766 
3767   // Whitelist some types as extensions
3768   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3769                                       ExprKind))
3770     return false;
3771 
3772   if (RequireCompleteType(OpLoc, ExprType,
3773                           diag::err_sizeof_alignof_incomplete_type,
3774                           ExprKind, ExprRange))
3775     return true;
3776 
3777   if (ExprType->isFunctionType()) {
3778     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3779       << ExprKind << ExprRange;
3780     return true;
3781   }
3782 
3783   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3784                                        ExprKind))
3785     return true;
3786 
3787   return false;
3788 }
3789 
3790 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3791   E = E->IgnoreParens();
3792 
3793   // Cannot know anything else if the expression is dependent.
3794   if (E->isTypeDependent())
3795     return false;
3796 
3797   if (E->getObjectKind() == OK_BitField) {
3798     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3799        << 1 << E->getSourceRange();
3800     return true;
3801   }
3802 
3803   ValueDecl *D = nullptr;
3804   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3805     D = DRE->getDecl();
3806   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3807     D = ME->getMemberDecl();
3808   }
3809 
3810   // If it's a field, require the containing struct to have a
3811   // complete definition so that we can compute the layout.
3812   //
3813   // This can happen in C++11 onwards, either by naming the member
3814   // in a way that is not transformed into a member access expression
3815   // (in an unevaluated operand, for instance), or by naming the member
3816   // in a trailing-return-type.
3817   //
3818   // For the record, since __alignof__ on expressions is a GCC
3819   // extension, GCC seems to permit this but always gives the
3820   // nonsensical answer 0.
3821   //
3822   // We don't really need the layout here --- we could instead just
3823   // directly check for all the appropriate alignment-lowing
3824   // attributes --- but that would require duplicating a lot of
3825   // logic that just isn't worth duplicating for such a marginal
3826   // use-case.
3827   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3828     // Fast path this check, since we at least know the record has a
3829     // definition if we can find a member of it.
3830     if (!FD->getParent()->isCompleteDefinition()) {
3831       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3832         << E->getSourceRange();
3833       return true;
3834     }
3835 
3836     // Otherwise, if it's a field, and the field doesn't have
3837     // reference type, then it must have a complete type (or be a
3838     // flexible array member, which we explicitly want to
3839     // white-list anyway), which makes the following checks trivial.
3840     if (!FD->getType()->isReferenceType())
3841       return false;
3842   }
3843 
3844   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3845 }
3846 
3847 bool Sema::CheckVecStepExpr(Expr *E) {
3848   E = E->IgnoreParens();
3849 
3850   // Cannot know anything else if the expression is dependent.
3851   if (E->isTypeDependent())
3852     return false;
3853 
3854   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3855 }
3856 
3857 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3858                                         CapturingScopeInfo *CSI) {
3859   assert(T->isVariablyModifiedType());
3860   assert(CSI != nullptr);
3861 
3862   // We're going to walk down into the type and look for VLA expressions.
3863   do {
3864     const Type *Ty = T.getTypePtr();
3865     switch (Ty->getTypeClass()) {
3866 #define TYPE(Class, Base)
3867 #define ABSTRACT_TYPE(Class, Base)
3868 #define NON_CANONICAL_TYPE(Class, Base)
3869 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3870 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3871 #include "clang/AST/TypeNodes.def"
3872       T = QualType();
3873       break;
3874     // These types are never variably-modified.
3875     case Type::Builtin:
3876     case Type::Complex:
3877     case Type::Vector:
3878     case Type::ExtVector:
3879     case Type::Record:
3880     case Type::Enum:
3881     case Type::Elaborated:
3882     case Type::TemplateSpecialization:
3883     case Type::ObjCObject:
3884     case Type::ObjCInterface:
3885     case Type::ObjCObjectPointer:
3886     case Type::ObjCTypeParam:
3887     case Type::Pipe:
3888       llvm_unreachable("type class is never variably-modified!");
3889     case Type::Adjusted:
3890       T = cast<AdjustedType>(Ty)->getOriginalType();
3891       break;
3892     case Type::Decayed:
3893       T = cast<DecayedType>(Ty)->getPointeeType();
3894       break;
3895     case Type::Pointer:
3896       T = cast<PointerType>(Ty)->getPointeeType();
3897       break;
3898     case Type::BlockPointer:
3899       T = cast<BlockPointerType>(Ty)->getPointeeType();
3900       break;
3901     case Type::LValueReference:
3902     case Type::RValueReference:
3903       T = cast<ReferenceType>(Ty)->getPointeeType();
3904       break;
3905     case Type::MemberPointer:
3906       T = cast<MemberPointerType>(Ty)->getPointeeType();
3907       break;
3908     case Type::ConstantArray:
3909     case Type::IncompleteArray:
3910       // Losing element qualification here is fine.
3911       T = cast<ArrayType>(Ty)->getElementType();
3912       break;
3913     case Type::VariableArray: {
3914       // Losing element qualification here is fine.
3915       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3916 
3917       // Unknown size indication requires no size computation.
3918       // Otherwise, evaluate and record it.
3919       if (auto Size = VAT->getSizeExpr()) {
3920         if (!CSI->isVLATypeCaptured(VAT)) {
3921           RecordDecl *CapRecord = nullptr;
3922           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3923             CapRecord = LSI->Lambda;
3924           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3925             CapRecord = CRSI->TheRecordDecl;
3926           }
3927           if (CapRecord) {
3928             auto ExprLoc = Size->getExprLoc();
3929             auto SizeType = Context.getSizeType();
3930             // Build the non-static data member.
3931             auto Field =
3932                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3933                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3934                                   /*BW*/ nullptr, /*Mutable*/ false,
3935                                   /*InitStyle*/ ICIS_NoInit);
3936             Field->setImplicit(true);
3937             Field->setAccess(AS_private);
3938             Field->setCapturedVLAType(VAT);
3939             CapRecord->addDecl(Field);
3940 
3941             CSI->addVLATypeCapture(ExprLoc, SizeType);
3942           }
3943         }
3944       }
3945       T = VAT->getElementType();
3946       break;
3947     }
3948     case Type::FunctionProto:
3949     case Type::FunctionNoProto:
3950       T = cast<FunctionType>(Ty)->getReturnType();
3951       break;
3952     case Type::Paren:
3953     case Type::TypeOf:
3954     case Type::UnaryTransform:
3955     case Type::Attributed:
3956     case Type::SubstTemplateTypeParm:
3957     case Type::PackExpansion:
3958       // Keep walking after single level desugaring.
3959       T = T.getSingleStepDesugaredType(Context);
3960       break;
3961     case Type::Typedef:
3962       T = cast<TypedefType>(Ty)->desugar();
3963       break;
3964     case Type::Decltype:
3965       T = cast<DecltypeType>(Ty)->desugar();
3966       break;
3967     case Type::Auto:
3968     case Type::DeducedTemplateSpecialization:
3969       T = cast<DeducedType>(Ty)->getDeducedType();
3970       break;
3971     case Type::TypeOfExpr:
3972       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3973       break;
3974     case Type::Atomic:
3975       T = cast<AtomicType>(Ty)->getValueType();
3976       break;
3977     }
3978   } while (!T.isNull() && T->isVariablyModifiedType());
3979 }
3980 
3981 /// Build a sizeof or alignof expression given a type operand.
3982 ExprResult
3983 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3984                                      SourceLocation OpLoc,
3985                                      UnaryExprOrTypeTrait ExprKind,
3986                                      SourceRange R) {
3987   if (!TInfo)
3988     return ExprError();
3989 
3990   QualType T = TInfo->getType();
3991 
3992   if (!T->isDependentType() &&
3993       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3994     return ExprError();
3995 
3996   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3997     if (auto *TT = T->getAs<TypedefType>()) {
3998       for (auto I = FunctionScopes.rbegin(),
3999                 E = std::prev(FunctionScopes.rend());
4000            I != E; ++I) {
4001         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4002         if (CSI == nullptr)
4003           break;
4004         DeclContext *DC = nullptr;
4005         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4006           DC = LSI->CallOperator;
4007         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4008           DC = CRSI->TheCapturedDecl;
4009         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4010           DC = BSI->TheDecl;
4011         if (DC) {
4012           if (DC->containsDecl(TT->getDecl()))
4013             break;
4014           captureVariablyModifiedType(Context, T, CSI);
4015         }
4016       }
4017     }
4018   }
4019 
4020   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4021   return new (Context) UnaryExprOrTypeTraitExpr(
4022       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4023 }
4024 
4025 /// Build a sizeof or alignof expression given an expression
4026 /// operand.
4027 ExprResult
4028 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4029                                      UnaryExprOrTypeTrait ExprKind) {
4030   ExprResult PE = CheckPlaceholderExpr(E);
4031   if (PE.isInvalid())
4032     return ExprError();
4033 
4034   E = PE.get();
4035 
4036   // Verify that the operand is valid.
4037   bool isInvalid = false;
4038   if (E->isTypeDependent()) {
4039     // Delay type-checking for type-dependent expressions.
4040   } else if (ExprKind == UETT_AlignOf) {
4041     isInvalid = CheckAlignOfExpr(*this, E);
4042   } else if (ExprKind == UETT_VecStep) {
4043     isInvalid = CheckVecStepExpr(E);
4044   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4045       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4046       isInvalid = true;
4047   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4048     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4049     isInvalid = true;
4050   } else {
4051     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4052   }
4053 
4054   if (isInvalid)
4055     return ExprError();
4056 
4057   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4058     PE = TransformToPotentiallyEvaluated(E);
4059     if (PE.isInvalid()) return ExprError();
4060     E = PE.get();
4061   }
4062 
4063   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4064   return new (Context) UnaryExprOrTypeTraitExpr(
4065       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4066 }
4067 
4068 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4069 /// expr and the same for @c alignof and @c __alignof
4070 /// Note that the ArgRange is invalid if isType is false.
4071 ExprResult
4072 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4073                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4074                                     void *TyOrEx, SourceRange ArgRange) {
4075   // If error parsing type, ignore.
4076   if (!TyOrEx) return ExprError();
4077 
4078   if (IsType) {
4079     TypeSourceInfo *TInfo;
4080     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4081     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4082   }
4083 
4084   Expr *ArgEx = (Expr *)TyOrEx;
4085   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4086   return Result;
4087 }
4088 
4089 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4090                                      bool IsReal) {
4091   if (V.get()->isTypeDependent())
4092     return S.Context.DependentTy;
4093 
4094   // _Real and _Imag are only l-values for normal l-values.
4095   if (V.get()->getObjectKind() != OK_Ordinary) {
4096     V = S.DefaultLvalueConversion(V.get());
4097     if (V.isInvalid())
4098       return QualType();
4099   }
4100 
4101   // These operators return the element type of a complex type.
4102   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4103     return CT->getElementType();
4104 
4105   // Otherwise they pass through real integer and floating point types here.
4106   if (V.get()->getType()->isArithmeticType())
4107     return V.get()->getType();
4108 
4109   // Test for placeholders.
4110   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4111   if (PR.isInvalid()) return QualType();
4112   if (PR.get() != V.get()) {
4113     V = PR;
4114     return CheckRealImagOperand(S, V, Loc, IsReal);
4115   }
4116 
4117   // Reject anything else.
4118   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4119     << (IsReal ? "__real" : "__imag");
4120   return QualType();
4121 }
4122 
4123 
4124 
4125 ExprResult
4126 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4127                           tok::TokenKind Kind, Expr *Input) {
4128   UnaryOperatorKind Opc;
4129   switch (Kind) {
4130   default: llvm_unreachable("Unknown unary op!");
4131   case tok::plusplus:   Opc = UO_PostInc; break;
4132   case tok::minusminus: Opc = UO_PostDec; break;
4133   }
4134 
4135   // Since this might is a postfix expression, get rid of ParenListExprs.
4136   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4137   if (Result.isInvalid()) return ExprError();
4138   Input = Result.get();
4139 
4140   return BuildUnaryOp(S, OpLoc, Opc, Input);
4141 }
4142 
4143 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4144 ///
4145 /// \return true on error
4146 static bool checkArithmeticOnObjCPointer(Sema &S,
4147                                          SourceLocation opLoc,
4148                                          Expr *op) {
4149   assert(op->getType()->isObjCObjectPointerType());
4150   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4151       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4152     return false;
4153 
4154   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4155     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4156     << op->getSourceRange();
4157   return true;
4158 }
4159 
4160 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4161   auto *BaseNoParens = Base->IgnoreParens();
4162   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4163     return MSProp->getPropertyDecl()->getType()->isArrayType();
4164   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4165 }
4166 
4167 ExprResult
4168 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4169                               Expr *idx, SourceLocation rbLoc) {
4170   if (base && !base->getType().isNull() &&
4171       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4172     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4173                                     /*Length=*/nullptr, rbLoc);
4174 
4175   // Since this might be a postfix expression, get rid of ParenListExprs.
4176   if (isa<ParenListExpr>(base)) {
4177     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4178     if (result.isInvalid()) return ExprError();
4179     base = result.get();
4180   }
4181 
4182   // Handle any non-overload placeholder types in the base and index
4183   // expressions.  We can't handle overloads here because the other
4184   // operand might be an overloadable type, in which case the overload
4185   // resolution for the operator overload should get the first crack
4186   // at the overload.
4187   bool IsMSPropertySubscript = false;
4188   if (base->getType()->isNonOverloadPlaceholderType()) {
4189     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4190     if (!IsMSPropertySubscript) {
4191       ExprResult result = CheckPlaceholderExpr(base);
4192       if (result.isInvalid())
4193         return ExprError();
4194       base = result.get();
4195     }
4196   }
4197   if (idx->getType()->isNonOverloadPlaceholderType()) {
4198     ExprResult result = CheckPlaceholderExpr(idx);
4199     if (result.isInvalid()) return ExprError();
4200     idx = result.get();
4201   }
4202 
4203   // Build an unanalyzed expression if either operand is type-dependent.
4204   if (getLangOpts().CPlusPlus &&
4205       (base->isTypeDependent() || idx->isTypeDependent())) {
4206     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4207                                             VK_LValue, OK_Ordinary, rbLoc);
4208   }
4209 
4210   // MSDN, property (C++)
4211   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4212   // This attribute can also be used in the declaration of an empty array in a
4213   // class or structure definition. For example:
4214   // __declspec(property(get=GetX, put=PutX)) int x[];
4215   // The above statement indicates that x[] can be used with one or more array
4216   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4217   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4218   if (IsMSPropertySubscript) {
4219     // Build MS property subscript expression if base is MS property reference
4220     // or MS property subscript.
4221     return new (Context) MSPropertySubscriptExpr(
4222         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4223   }
4224 
4225   // Use C++ overloaded-operator rules if either operand has record
4226   // type.  The spec says to do this if either type is *overloadable*,
4227   // but enum types can't declare subscript operators or conversion
4228   // operators, so there's nothing interesting for overload resolution
4229   // to do if there aren't any record types involved.
4230   //
4231   // ObjC pointers have their own subscripting logic that is not tied
4232   // to overload resolution and so should not take this path.
4233   if (getLangOpts().CPlusPlus &&
4234       (base->getType()->isRecordType() ||
4235        (!base->getType()->isObjCObjectPointerType() &&
4236         idx->getType()->isRecordType()))) {
4237     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4238   }
4239 
4240   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4241 }
4242 
4243 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4244                                           Expr *LowerBound,
4245                                           SourceLocation ColonLoc, Expr *Length,
4246                                           SourceLocation RBLoc) {
4247   if (Base->getType()->isPlaceholderType() &&
4248       !Base->getType()->isSpecificPlaceholderType(
4249           BuiltinType::OMPArraySection)) {
4250     ExprResult Result = CheckPlaceholderExpr(Base);
4251     if (Result.isInvalid())
4252       return ExprError();
4253     Base = Result.get();
4254   }
4255   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4256     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4257     if (Result.isInvalid())
4258       return ExprError();
4259     Result = DefaultLvalueConversion(Result.get());
4260     if (Result.isInvalid())
4261       return ExprError();
4262     LowerBound = Result.get();
4263   }
4264   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4265     ExprResult Result = CheckPlaceholderExpr(Length);
4266     if (Result.isInvalid())
4267       return ExprError();
4268     Result = DefaultLvalueConversion(Result.get());
4269     if (Result.isInvalid())
4270       return ExprError();
4271     Length = Result.get();
4272   }
4273 
4274   // Build an unanalyzed expression if either operand is type-dependent.
4275   if (Base->isTypeDependent() ||
4276       (LowerBound &&
4277        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4278       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4279     return new (Context)
4280         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4281                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4282   }
4283 
4284   // Perform default conversions.
4285   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4286   QualType ResultTy;
4287   if (OriginalTy->isAnyPointerType()) {
4288     ResultTy = OriginalTy->getPointeeType();
4289   } else if (OriginalTy->isArrayType()) {
4290     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4291   } else {
4292     return ExprError(
4293         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4294         << Base->getSourceRange());
4295   }
4296   // C99 6.5.2.1p1
4297   if (LowerBound) {
4298     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4299                                                       LowerBound);
4300     if (Res.isInvalid())
4301       return ExprError(Diag(LowerBound->getExprLoc(),
4302                             diag::err_omp_typecheck_section_not_integer)
4303                        << 0 << LowerBound->getSourceRange());
4304     LowerBound = Res.get();
4305 
4306     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4307         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4308       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4309           << 0 << LowerBound->getSourceRange();
4310   }
4311   if (Length) {
4312     auto Res =
4313         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4314     if (Res.isInvalid())
4315       return ExprError(Diag(Length->getExprLoc(),
4316                             diag::err_omp_typecheck_section_not_integer)
4317                        << 1 << Length->getSourceRange());
4318     Length = Res.get();
4319 
4320     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4321         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4322       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4323           << 1 << Length->getSourceRange();
4324   }
4325 
4326   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4327   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4328   // type. Note that functions are not objects, and that (in C99 parlance)
4329   // incomplete types are not object types.
4330   if (ResultTy->isFunctionType()) {
4331     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4332         << ResultTy << Base->getSourceRange();
4333     return ExprError();
4334   }
4335 
4336   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4337                           diag::err_omp_section_incomplete_type, Base))
4338     return ExprError();
4339 
4340   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4341     llvm::APSInt LowerBoundValue;
4342     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4343       // OpenMP 4.5, [2.4 Array Sections]
4344       // The array section must be a subset of the original array.
4345       if (LowerBoundValue.isNegative()) {
4346         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4347             << LowerBound->getSourceRange();
4348         return ExprError();
4349       }
4350     }
4351   }
4352 
4353   if (Length) {
4354     llvm::APSInt LengthValue;
4355     if (Length->EvaluateAsInt(LengthValue, Context)) {
4356       // OpenMP 4.5, [2.4 Array Sections]
4357       // The length must evaluate to non-negative integers.
4358       if (LengthValue.isNegative()) {
4359         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4360             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4361             << Length->getSourceRange();
4362         return ExprError();
4363       }
4364     }
4365   } else if (ColonLoc.isValid() &&
4366              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4367                                       !OriginalTy->isVariableArrayType()))) {
4368     // OpenMP 4.5, [2.4 Array Sections]
4369     // When the size of the array dimension is not known, the length must be
4370     // specified explicitly.
4371     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4372         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4373     return ExprError();
4374   }
4375 
4376   if (!Base->getType()->isSpecificPlaceholderType(
4377           BuiltinType::OMPArraySection)) {
4378     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4379     if (Result.isInvalid())
4380       return ExprError();
4381     Base = Result.get();
4382   }
4383   return new (Context)
4384       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4385                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4386 }
4387 
4388 ExprResult
4389 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4390                                       Expr *Idx, SourceLocation RLoc) {
4391   Expr *LHSExp = Base;
4392   Expr *RHSExp = Idx;
4393 
4394   ExprValueKind VK = VK_LValue;
4395   ExprObjectKind OK = OK_Ordinary;
4396 
4397   // Per C++ core issue 1213, the result is an xvalue if either operand is
4398   // a non-lvalue array, and an lvalue otherwise.
4399   if (getLangOpts().CPlusPlus11) {
4400     for (auto *Op : {LHSExp, RHSExp}) {
4401       Op = Op->IgnoreImplicit();
4402       if (Op->getType()->isArrayType() && !Op->isLValue())
4403         VK = VK_XValue;
4404     }
4405   }
4406 
4407   // Perform default conversions.
4408   if (!LHSExp->getType()->getAs<VectorType>()) {
4409     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4410     if (Result.isInvalid())
4411       return ExprError();
4412     LHSExp = Result.get();
4413   }
4414   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4415   if (Result.isInvalid())
4416     return ExprError();
4417   RHSExp = Result.get();
4418 
4419   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4420 
4421   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4422   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4423   // in the subscript position. As a result, we need to derive the array base
4424   // and index from the expression types.
4425   Expr *BaseExpr, *IndexExpr;
4426   QualType ResultType;
4427   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4428     BaseExpr = LHSExp;
4429     IndexExpr = RHSExp;
4430     ResultType = Context.DependentTy;
4431   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4432     BaseExpr = LHSExp;
4433     IndexExpr = RHSExp;
4434     ResultType = PTy->getPointeeType();
4435   } else if (const ObjCObjectPointerType *PTy =
4436                LHSTy->getAs<ObjCObjectPointerType>()) {
4437     BaseExpr = LHSExp;
4438     IndexExpr = RHSExp;
4439 
4440     // Use custom logic if this should be the pseudo-object subscript
4441     // expression.
4442     if (!LangOpts.isSubscriptPointerArithmetic())
4443       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4444                                           nullptr);
4445 
4446     ResultType = PTy->getPointeeType();
4447   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4448      // Handle the uncommon case of "123[Ptr]".
4449     BaseExpr = RHSExp;
4450     IndexExpr = LHSExp;
4451     ResultType = PTy->getPointeeType();
4452   } else if (const ObjCObjectPointerType *PTy =
4453                RHSTy->getAs<ObjCObjectPointerType>()) {
4454      // Handle the uncommon case of "123[Ptr]".
4455     BaseExpr = RHSExp;
4456     IndexExpr = LHSExp;
4457     ResultType = PTy->getPointeeType();
4458     if (!LangOpts.isSubscriptPointerArithmetic()) {
4459       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4460         << ResultType << BaseExpr->getSourceRange();
4461       return ExprError();
4462     }
4463   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4464     BaseExpr = LHSExp;    // vectors: V[123]
4465     IndexExpr = RHSExp;
4466     // We apply C++ DR1213 to vector subscripting too.
4467     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4468       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4469       if (Materialized.isInvalid())
4470         return ExprError();
4471       LHSExp = Materialized.get();
4472     }
4473     VK = LHSExp->getValueKind();
4474     if (VK != VK_RValue)
4475       OK = OK_VectorComponent;
4476 
4477     ResultType = VTy->getElementType();
4478     QualType BaseType = BaseExpr->getType();
4479     Qualifiers BaseQuals = BaseType.getQualifiers();
4480     Qualifiers MemberQuals = ResultType.getQualifiers();
4481     Qualifiers Combined = BaseQuals + MemberQuals;
4482     if (Combined != MemberQuals)
4483       ResultType = Context.getQualifiedType(ResultType, Combined);
4484   } else if (LHSTy->isArrayType()) {
4485     // If we see an array that wasn't promoted by
4486     // DefaultFunctionArrayLvalueConversion, it must be an array that
4487     // wasn't promoted because of the C90 rule that doesn't
4488     // allow promoting non-lvalue arrays.  Warn, then
4489     // force the promotion here.
4490     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4491         LHSExp->getSourceRange();
4492     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4493                                CK_ArrayToPointerDecay).get();
4494     LHSTy = LHSExp->getType();
4495 
4496     BaseExpr = LHSExp;
4497     IndexExpr = RHSExp;
4498     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4499   } else if (RHSTy->isArrayType()) {
4500     // Same as previous, except for 123[f().a] case
4501     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4502         RHSExp->getSourceRange();
4503     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4504                                CK_ArrayToPointerDecay).get();
4505     RHSTy = RHSExp->getType();
4506 
4507     BaseExpr = RHSExp;
4508     IndexExpr = LHSExp;
4509     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4510   } else {
4511     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4512        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4513   }
4514   // C99 6.5.2.1p1
4515   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4516     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4517                      << IndexExpr->getSourceRange());
4518 
4519   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4520        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4521          && !IndexExpr->isTypeDependent())
4522     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
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 (ResultType->isFunctionType()) {
4529     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4530       << ResultType << BaseExpr->getSourceRange();
4531     return ExprError();
4532   }
4533 
4534   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4535     // GNU extension: subscripting on pointer to void
4536     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4537       << BaseExpr->getSourceRange();
4538 
4539     // C forbids expressions of unqualified void type from being l-values.
4540     // See IsCForbiddenLValueType.
4541     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4542   } else if (!ResultType->isDependentType() &&
4543       RequireCompleteType(LLoc, ResultType,
4544                           diag::err_subscript_incomplete_type, BaseExpr))
4545     return ExprError();
4546 
4547   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4548          !ResultType.isCForbiddenLValueType());
4549 
4550   return new (Context)
4551       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4552 }
4553 
4554 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4555                                   ParmVarDecl *Param) {
4556   if (Param->hasUnparsedDefaultArg()) {
4557     Diag(CallLoc,
4558          diag::err_use_of_default_argument_to_function_declared_later) <<
4559       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4560     Diag(UnparsedDefaultArgLocs[Param],
4561          diag::note_default_argument_declared_here);
4562     return true;
4563   }
4564 
4565   if (Param->hasUninstantiatedDefaultArg()) {
4566     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4567 
4568     EnterExpressionEvaluationContext EvalContext(
4569         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4570 
4571     // Instantiate the expression.
4572     //
4573     // FIXME: Pass in a correct Pattern argument, otherwise
4574     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4575     //
4576     // template<typename T>
4577     // struct A {
4578     //   static int FooImpl();
4579     //
4580     //   template<typename Tp>
4581     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4582     //   // template argument list [[T], [Tp]], should be [[Tp]].
4583     //   friend A<Tp> Foo(int a);
4584     // };
4585     //
4586     // template<typename T>
4587     // A<T> Foo(int a = A<T>::FooImpl());
4588     MultiLevelTemplateArgumentList MutiLevelArgList
4589       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4590 
4591     InstantiatingTemplate Inst(*this, CallLoc, Param,
4592                                MutiLevelArgList.getInnermost());
4593     if (Inst.isInvalid())
4594       return true;
4595     if (Inst.isAlreadyInstantiating()) {
4596       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4597       Param->setInvalidDecl();
4598       return true;
4599     }
4600 
4601     ExprResult Result;
4602     {
4603       // C++ [dcl.fct.default]p5:
4604       //   The names in the [default argument] expression are bound, and
4605       //   the semantic constraints are checked, at the point where the
4606       //   default argument expression appears.
4607       ContextRAII SavedContext(*this, FD);
4608       LocalInstantiationScope Local(*this);
4609       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4610                                 /*DirectInit*/false);
4611     }
4612     if (Result.isInvalid())
4613       return true;
4614 
4615     // Check the expression as an initializer for the parameter.
4616     InitializedEntity Entity
4617       = InitializedEntity::InitializeParameter(Context, Param);
4618     InitializationKind Kind
4619       = InitializationKind::CreateCopy(Param->getLocation(),
4620              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4621     Expr *ResultE = Result.getAs<Expr>();
4622 
4623     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4624     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4625     if (Result.isInvalid())
4626       return true;
4627 
4628     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4629                                  Param->getOuterLocStart());
4630     if (Result.isInvalid())
4631       return true;
4632 
4633     // Remember the instantiated default argument.
4634     Param->setDefaultArg(Result.getAs<Expr>());
4635     if (ASTMutationListener *L = getASTMutationListener()) {
4636       L->DefaultArgumentInstantiated(Param);
4637     }
4638   }
4639 
4640   // If the default argument expression is not set yet, we are building it now.
4641   if (!Param->hasInit()) {
4642     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4643     Param->setInvalidDecl();
4644     return true;
4645   }
4646 
4647   // If the default expression creates temporaries, we need to
4648   // push them to the current stack of expression temporaries so they'll
4649   // be properly destroyed.
4650   // FIXME: We should really be rebuilding the default argument with new
4651   // bound temporaries; see the comment in PR5810.
4652   // We don't need to do that with block decls, though, because
4653   // blocks in default argument expression can never capture anything.
4654   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4655     // Set the "needs cleanups" bit regardless of whether there are
4656     // any explicit objects.
4657     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4658 
4659     // Append all the objects to the cleanup list.  Right now, this
4660     // should always be a no-op, because blocks in default argument
4661     // expressions should never be able to capture anything.
4662     assert(!Init->getNumObjects() &&
4663            "default argument expression has capturing blocks?");
4664   }
4665 
4666   // We already type-checked the argument, so we know it works.
4667   // Just mark all of the declarations in this potentially-evaluated expression
4668   // as being "referenced".
4669   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4670                                    /*SkipLocalVariables=*/true);
4671   return false;
4672 }
4673 
4674 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4675                                         FunctionDecl *FD, ParmVarDecl *Param) {
4676   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4677     return ExprError();
4678   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4679 }
4680 
4681 Sema::VariadicCallType
4682 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4683                           Expr *Fn) {
4684   if (Proto && Proto->isVariadic()) {
4685     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4686       return VariadicConstructor;
4687     else if (Fn && Fn->getType()->isBlockPointerType())
4688       return VariadicBlock;
4689     else if (FDecl) {
4690       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4691         if (Method->isInstance())
4692           return VariadicMethod;
4693     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4694       return VariadicMethod;
4695     return VariadicFunction;
4696   }
4697   return VariadicDoesNotApply;
4698 }
4699 
4700 namespace {
4701 class FunctionCallCCC : public FunctionCallFilterCCC {
4702 public:
4703   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4704                   unsigned NumArgs, MemberExpr *ME)
4705       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4706         FunctionName(FuncName) {}
4707 
4708   bool ValidateCandidate(const TypoCorrection &candidate) override {
4709     if (!candidate.getCorrectionSpecifier() ||
4710         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4711       return false;
4712     }
4713 
4714     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4715   }
4716 
4717 private:
4718   const IdentifierInfo *const FunctionName;
4719 };
4720 }
4721 
4722 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4723                                                FunctionDecl *FDecl,
4724                                                ArrayRef<Expr *> Args) {
4725   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4726   DeclarationName FuncName = FDecl->getDeclName();
4727   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4728 
4729   if (TypoCorrection Corrected = S.CorrectTypo(
4730           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4731           S.getScopeForContext(S.CurContext), nullptr,
4732           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4733                                              Args.size(), ME),
4734           Sema::CTK_ErrorRecovery)) {
4735     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4736       if (Corrected.isOverloaded()) {
4737         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4738         OverloadCandidateSet::iterator Best;
4739         for (NamedDecl *CD : Corrected) {
4740           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4741             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4742                                    OCS);
4743         }
4744         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4745         case OR_Success:
4746           ND = Best->FoundDecl;
4747           Corrected.setCorrectionDecl(ND);
4748           break;
4749         default:
4750           break;
4751         }
4752       }
4753       ND = ND->getUnderlyingDecl();
4754       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4755         return Corrected;
4756     }
4757   }
4758   return TypoCorrection();
4759 }
4760 
4761 /// ConvertArgumentsForCall - Converts the arguments specified in
4762 /// Args/NumArgs to the parameter types of the function FDecl with
4763 /// function prototype Proto. Call is the call expression itself, and
4764 /// Fn is the function expression. For a C++ member function, this
4765 /// routine does not attempt to convert the object argument. Returns
4766 /// true if the call is ill-formed.
4767 bool
4768 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4769                               FunctionDecl *FDecl,
4770                               const FunctionProtoType *Proto,
4771                               ArrayRef<Expr *> Args,
4772                               SourceLocation RParenLoc,
4773                               bool IsExecConfig) {
4774   // Bail out early if calling a builtin with custom typechecking.
4775   if (FDecl)
4776     if (unsigned ID = FDecl->getBuiltinID())
4777       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4778         return false;
4779 
4780   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4781   // assignment, to the types of the corresponding parameter, ...
4782   unsigned NumParams = Proto->getNumParams();
4783   bool Invalid = false;
4784   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4785   unsigned FnKind = Fn->getType()->isBlockPointerType()
4786                        ? 1 /* block */
4787                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4788                                        : 0 /* function */);
4789 
4790   // If too few arguments are available (and we don't have default
4791   // arguments for the remaining parameters), don't make the call.
4792   if (Args.size() < NumParams) {
4793     if (Args.size() < MinArgs) {
4794       TypoCorrection TC;
4795       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4796         unsigned diag_id =
4797             MinArgs == NumParams && !Proto->isVariadic()
4798                 ? diag::err_typecheck_call_too_few_args_suggest
4799                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4800         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4801                                         << static_cast<unsigned>(Args.size())
4802                                         << TC.getCorrectionRange());
4803       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4804         Diag(RParenLoc,
4805              MinArgs == NumParams && !Proto->isVariadic()
4806                  ? diag::err_typecheck_call_too_few_args_one
4807                  : diag::err_typecheck_call_too_few_args_at_least_one)
4808             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4809       else
4810         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4811                             ? diag::err_typecheck_call_too_few_args
4812                             : diag::err_typecheck_call_too_few_args_at_least)
4813             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4814             << Fn->getSourceRange();
4815 
4816       // Emit the location of the prototype.
4817       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4818         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4819           << FDecl;
4820 
4821       return true;
4822     }
4823     Call->setNumArgs(Context, NumParams);
4824   }
4825 
4826   // If too many are passed and not variadic, error on the extras and drop
4827   // them.
4828   if (Args.size() > NumParams) {
4829     if (!Proto->isVariadic()) {
4830       TypoCorrection TC;
4831       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4832         unsigned diag_id =
4833             MinArgs == NumParams && !Proto->isVariadic()
4834                 ? diag::err_typecheck_call_too_many_args_suggest
4835                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4836         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4837                                         << static_cast<unsigned>(Args.size())
4838                                         << TC.getCorrectionRange());
4839       } else if (NumParams == 1 && FDecl &&
4840                  FDecl->getParamDecl(0)->getDeclName())
4841         Diag(Args[NumParams]->getLocStart(),
4842              MinArgs == NumParams
4843                  ? diag::err_typecheck_call_too_many_args_one
4844                  : diag::err_typecheck_call_too_many_args_at_most_one)
4845             << FnKind << FDecl->getParamDecl(0)
4846             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4847             << SourceRange(Args[NumParams]->getLocStart(),
4848                            Args.back()->getLocEnd());
4849       else
4850         Diag(Args[NumParams]->getLocStart(),
4851              MinArgs == NumParams
4852                  ? diag::err_typecheck_call_too_many_args
4853                  : diag::err_typecheck_call_too_many_args_at_most)
4854             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4855             << Fn->getSourceRange()
4856             << SourceRange(Args[NumParams]->getLocStart(),
4857                            Args.back()->getLocEnd());
4858 
4859       // Emit the location of the prototype.
4860       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4861         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4862           << FDecl;
4863 
4864       // This deletes the extra arguments.
4865       Call->setNumArgs(Context, NumParams);
4866       return true;
4867     }
4868   }
4869   SmallVector<Expr *, 8> AllArgs;
4870   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4871 
4872   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4873                                    Proto, 0, Args, AllArgs, CallType);
4874   if (Invalid)
4875     return true;
4876   unsigned TotalNumArgs = AllArgs.size();
4877   for (unsigned i = 0; i < TotalNumArgs; ++i)
4878     Call->setArg(i, AllArgs[i]);
4879 
4880   return false;
4881 }
4882 
4883 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4884                                   const FunctionProtoType *Proto,
4885                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4886                                   SmallVectorImpl<Expr *> &AllArgs,
4887                                   VariadicCallType CallType, bool AllowExplicit,
4888                                   bool IsListInitialization) {
4889   unsigned NumParams = Proto->getNumParams();
4890   bool Invalid = false;
4891   size_t ArgIx = 0;
4892   // Continue to check argument types (even if we have too few/many args).
4893   for (unsigned i = FirstParam; i < NumParams; i++) {
4894     QualType ProtoArgType = Proto->getParamType(i);
4895 
4896     Expr *Arg;
4897     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4898     if (ArgIx < Args.size()) {
4899       Arg = Args[ArgIx++];
4900 
4901       if (RequireCompleteType(Arg->getLocStart(),
4902                               ProtoArgType,
4903                               diag::err_call_incomplete_argument, Arg))
4904         return true;
4905 
4906       // Strip the unbridged-cast placeholder expression off, if applicable.
4907       bool CFAudited = false;
4908       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4909           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4910           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4911         Arg = stripARCUnbridgedCast(Arg);
4912       else if (getLangOpts().ObjCAutoRefCount &&
4913                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4914                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4915         CFAudited = true;
4916 
4917       if (Proto->getExtParameterInfo(i).isNoEscape())
4918         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4919           BE->getBlockDecl()->setDoesNotEscape();
4920 
4921       InitializedEntity Entity =
4922           Param ? InitializedEntity::InitializeParameter(Context, Param,
4923                                                          ProtoArgType)
4924                 : InitializedEntity::InitializeParameter(
4925                       Context, ProtoArgType, Proto->isParamConsumed(i));
4926 
4927       // Remember that parameter belongs to a CF audited API.
4928       if (CFAudited)
4929         Entity.setParameterCFAudited();
4930 
4931       ExprResult ArgE = PerformCopyInitialization(
4932           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4933       if (ArgE.isInvalid())
4934         return true;
4935 
4936       Arg = ArgE.getAs<Expr>();
4937     } else {
4938       assert(Param && "can't use default arguments without a known callee");
4939 
4940       ExprResult ArgExpr =
4941         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4942       if (ArgExpr.isInvalid())
4943         return true;
4944 
4945       Arg = ArgExpr.getAs<Expr>();
4946     }
4947 
4948     // Check for array bounds violations for each argument to the call. This
4949     // check only triggers warnings when the argument isn't a more complex Expr
4950     // with its own checking, such as a BinaryOperator.
4951     CheckArrayAccess(Arg);
4952 
4953     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4954     CheckStaticArrayArgument(CallLoc, Param, Arg);
4955 
4956     AllArgs.push_back(Arg);
4957   }
4958 
4959   // If this is a variadic call, handle args passed through "...".
4960   if (CallType != VariadicDoesNotApply) {
4961     // Assume that extern "C" functions with variadic arguments that
4962     // return __unknown_anytype aren't *really* variadic.
4963     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4964         FDecl->isExternC()) {
4965       for (Expr *A : Args.slice(ArgIx)) {
4966         QualType paramType; // ignored
4967         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4968         Invalid |= arg.isInvalid();
4969         AllArgs.push_back(arg.get());
4970       }
4971 
4972     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4973     } else {
4974       for (Expr *A : Args.slice(ArgIx)) {
4975         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4976         Invalid |= Arg.isInvalid();
4977         AllArgs.push_back(Arg.get());
4978       }
4979     }
4980 
4981     // Check for array bounds violations.
4982     for (Expr *A : Args.slice(ArgIx))
4983       CheckArrayAccess(A);
4984   }
4985   return Invalid;
4986 }
4987 
4988 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4989   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4990   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4991     TL = DTL.getOriginalLoc();
4992   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4993     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4994       << ATL.getLocalSourceRange();
4995 }
4996 
4997 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4998 /// array parameter, check that it is non-null, and that if it is formed by
4999 /// array-to-pointer decay, the underlying array is sufficiently large.
5000 ///
5001 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5002 /// array type derivation, then for each call to the function, the value of the
5003 /// corresponding actual argument shall provide access to the first element of
5004 /// an array with at least as many elements as specified by the size expression.
5005 void
5006 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5007                                ParmVarDecl *Param,
5008                                const Expr *ArgExpr) {
5009   // Static array parameters are not supported in C++.
5010   if (!Param || getLangOpts().CPlusPlus)
5011     return;
5012 
5013   QualType OrigTy = Param->getOriginalType();
5014 
5015   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5016   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5017     return;
5018 
5019   if (ArgExpr->isNullPointerConstant(Context,
5020                                      Expr::NPC_NeverValueDependent)) {
5021     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5022     DiagnoseCalleeStaticArrayParam(*this, Param);
5023     return;
5024   }
5025 
5026   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5027   if (!CAT)
5028     return;
5029 
5030   const ConstantArrayType *ArgCAT =
5031     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5032   if (!ArgCAT)
5033     return;
5034 
5035   if (ArgCAT->getSize().ult(CAT->getSize())) {
5036     Diag(CallLoc, diag::warn_static_array_too_small)
5037       << ArgExpr->getSourceRange()
5038       << (unsigned) ArgCAT->getSize().getZExtValue()
5039       << (unsigned) CAT->getSize().getZExtValue();
5040     DiagnoseCalleeStaticArrayParam(*this, Param);
5041   }
5042 }
5043 
5044 /// Given a function expression of unknown-any type, try to rebuild it
5045 /// to have a function type.
5046 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5047 
5048 /// Is the given type a placeholder that we need to lower out
5049 /// immediately during argument processing?
5050 static bool isPlaceholderToRemoveAsArg(QualType type) {
5051   // Placeholders are never sugared.
5052   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5053   if (!placeholder) return false;
5054 
5055   switch (placeholder->getKind()) {
5056   // Ignore all the non-placeholder types.
5057 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5058   case BuiltinType::Id:
5059 #include "clang/Basic/OpenCLImageTypes.def"
5060 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5061 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5062 #include "clang/AST/BuiltinTypes.def"
5063     return false;
5064 
5065   // We cannot lower out overload sets; they might validly be resolved
5066   // by the call machinery.
5067   case BuiltinType::Overload:
5068     return false;
5069 
5070   // Unbridged casts in ARC can be handled in some call positions and
5071   // should be left in place.
5072   case BuiltinType::ARCUnbridgedCast:
5073     return false;
5074 
5075   // Pseudo-objects should be converted as soon as possible.
5076   case BuiltinType::PseudoObject:
5077     return true;
5078 
5079   // The debugger mode could theoretically but currently does not try
5080   // to resolve unknown-typed arguments based on known parameter types.
5081   case BuiltinType::UnknownAny:
5082     return true;
5083 
5084   // These are always invalid as call arguments and should be reported.
5085   case BuiltinType::BoundMember:
5086   case BuiltinType::BuiltinFn:
5087   case BuiltinType::OMPArraySection:
5088     return true;
5089 
5090   }
5091   llvm_unreachable("bad builtin type kind");
5092 }
5093 
5094 /// Check an argument list for placeholders that we won't try to
5095 /// handle later.
5096 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5097   // Apply this processing to all the arguments at once instead of
5098   // dying at the first failure.
5099   bool hasInvalid = false;
5100   for (size_t i = 0, e = args.size(); i != e; i++) {
5101     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5102       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5103       if (result.isInvalid()) hasInvalid = true;
5104       else args[i] = result.get();
5105     } else if (hasInvalid) {
5106       (void)S.CorrectDelayedTyposInExpr(args[i]);
5107     }
5108   }
5109   return hasInvalid;
5110 }
5111 
5112 /// If a builtin function has a pointer argument with no explicit address
5113 /// space, then it should be able to accept a pointer to any address
5114 /// space as input.  In order to do this, we need to replace the
5115 /// standard builtin declaration with one that uses the same address space
5116 /// as the call.
5117 ///
5118 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5119 ///                  it does not contain any pointer arguments without
5120 ///                  an address space qualifer.  Otherwise the rewritten
5121 ///                  FunctionDecl is returned.
5122 /// TODO: Handle pointer return types.
5123 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5124                                                 const FunctionDecl *FDecl,
5125                                                 MultiExprArg ArgExprs) {
5126 
5127   QualType DeclType = FDecl->getType();
5128   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5129 
5130   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5131       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5132     return nullptr;
5133 
5134   bool NeedsNewDecl = false;
5135   unsigned i = 0;
5136   SmallVector<QualType, 8> OverloadParams;
5137 
5138   for (QualType ParamType : FT->param_types()) {
5139 
5140     // Convert array arguments to pointer to simplify type lookup.
5141     ExprResult ArgRes =
5142         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5143     if (ArgRes.isInvalid())
5144       return nullptr;
5145     Expr *Arg = ArgRes.get();
5146     QualType ArgType = Arg->getType();
5147     if (!ParamType->isPointerType() ||
5148         ParamType.getQualifiers().hasAddressSpace() ||
5149         !ArgType->isPointerType() ||
5150         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5151       OverloadParams.push_back(ParamType);
5152       continue;
5153     }
5154 
5155     NeedsNewDecl = true;
5156     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5157 
5158     QualType PointeeType = ParamType->getPointeeType();
5159     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5160     OverloadParams.push_back(Context.getPointerType(PointeeType));
5161   }
5162 
5163   if (!NeedsNewDecl)
5164     return nullptr;
5165 
5166   FunctionProtoType::ExtProtoInfo EPI;
5167   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5168                                                 OverloadParams, EPI);
5169   DeclContext *Parent = Context.getTranslationUnitDecl();
5170   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5171                                                     FDecl->getLocation(),
5172                                                     FDecl->getLocation(),
5173                                                     FDecl->getIdentifier(),
5174                                                     OverloadTy,
5175                                                     /*TInfo=*/nullptr,
5176                                                     SC_Extern, false,
5177                                                     /*hasPrototype=*/true);
5178   SmallVector<ParmVarDecl*, 16> Params;
5179   FT = cast<FunctionProtoType>(OverloadTy);
5180   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5181     QualType ParamType = FT->getParamType(i);
5182     ParmVarDecl *Parm =
5183         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5184                                 SourceLocation(), nullptr, ParamType,
5185                                 /*TInfo=*/nullptr, SC_None, nullptr);
5186     Parm->setScopeInfo(0, i);
5187     Params.push_back(Parm);
5188   }
5189   OverloadDecl->setParams(Params);
5190   return OverloadDecl;
5191 }
5192 
5193 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5194                                     FunctionDecl *Callee,
5195                                     MultiExprArg ArgExprs) {
5196   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5197   // similar attributes) really don't like it when functions are called with an
5198   // invalid number of args.
5199   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5200                          /*PartialOverloading=*/false) &&
5201       !Callee->isVariadic())
5202     return;
5203   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5204     return;
5205 
5206   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5207     S.Diag(Fn->getLocStart(),
5208            isa<CXXMethodDecl>(Callee)
5209                ? diag::err_ovl_no_viable_member_function_in_call
5210                : diag::err_ovl_no_viable_function_in_call)
5211         << Callee << Callee->getSourceRange();
5212     S.Diag(Callee->getLocation(),
5213            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5214         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5215     return;
5216   }
5217 }
5218 
5219 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5220     const UnresolvedMemberExpr *const UME, Sema &S) {
5221 
5222   const auto GetFunctionLevelDCIfCXXClass =
5223       [](Sema &S) -> const CXXRecordDecl * {
5224     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5225     if (!DC || !DC->getParent())
5226       return nullptr;
5227 
5228     // If the call to some member function was made from within a member
5229     // function body 'M' return return 'M's parent.
5230     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5231       return MD->getParent()->getCanonicalDecl();
5232     // else the call was made from within a default member initializer of a
5233     // class, so return the class.
5234     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5235       return RD->getCanonicalDecl();
5236     return nullptr;
5237   };
5238   // If our DeclContext is neither a member function nor a class (in the
5239   // case of a lambda in a default member initializer), we can't have an
5240   // enclosing 'this'.
5241 
5242   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5243   if (!CurParentClass)
5244     return false;
5245 
5246   // The naming class for implicit member functions call is the class in which
5247   // name lookup starts.
5248   const CXXRecordDecl *const NamingClass =
5249       UME->getNamingClass()->getCanonicalDecl();
5250   assert(NamingClass && "Must have naming class even for implicit access");
5251 
5252   // If the unresolved member functions were found in a 'naming class' that is
5253   // related (either the same or derived from) to the class that contains the
5254   // member function that itself contained the implicit member access.
5255 
5256   return CurParentClass == NamingClass ||
5257          CurParentClass->isDerivedFrom(NamingClass);
5258 }
5259 
5260 static void
5261 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5262     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5263 
5264   if (!UME)
5265     return;
5266 
5267   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5268   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5269   // already been captured, or if this is an implicit member function call (if
5270   // it isn't, an attempt to capture 'this' should already have been made).
5271   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5272       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5273     return;
5274 
5275   // Check if the naming class in which the unresolved members were found is
5276   // related (same as or is a base of) to the enclosing class.
5277 
5278   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5279     return;
5280 
5281 
5282   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5283   // If the enclosing function is not dependent, then this lambda is
5284   // capture ready, so if we can capture this, do so.
5285   if (!EnclosingFunctionCtx->isDependentContext()) {
5286     // If the current lambda and all enclosing lambdas can capture 'this' -
5287     // then go ahead and capture 'this' (since our unresolved overload set
5288     // contains at least one non-static member function).
5289     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5290       S.CheckCXXThisCapture(CallLoc);
5291   } else if (S.CurContext->isDependentContext()) {
5292     // ... since this is an implicit member reference, that might potentially
5293     // involve a 'this' capture, mark 'this' for potential capture in
5294     // enclosing lambdas.
5295     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5296       CurLSI->addPotentialThisCapture(CallLoc);
5297   }
5298 }
5299 
5300 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5301 /// This provides the location of the left/right parens and a list of comma
5302 /// locations.
5303 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5304                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5305                                Expr *ExecConfig, bool IsExecConfig) {
5306   // Since this might be a postfix expression, get rid of ParenListExprs.
5307   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5308   if (Result.isInvalid()) return ExprError();
5309   Fn = Result.get();
5310 
5311   if (checkArgsForPlaceholders(*this, ArgExprs))
5312     return ExprError();
5313 
5314   if (getLangOpts().CPlusPlus) {
5315     // If this is a pseudo-destructor expression, build the call immediately.
5316     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5317       if (!ArgExprs.empty()) {
5318         // Pseudo-destructor calls should not have any arguments.
5319         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5320             << FixItHint::CreateRemoval(
5321                    SourceRange(ArgExprs.front()->getLocStart(),
5322                                ArgExprs.back()->getLocEnd()));
5323       }
5324 
5325       return new (Context)
5326           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5327     }
5328     if (Fn->getType() == Context.PseudoObjectTy) {
5329       ExprResult result = CheckPlaceholderExpr(Fn);
5330       if (result.isInvalid()) return ExprError();
5331       Fn = result.get();
5332     }
5333 
5334     // Determine whether this is a dependent call inside a C++ template,
5335     // in which case we won't do any semantic analysis now.
5336     bool Dependent = false;
5337     if (Fn->isTypeDependent())
5338       Dependent = true;
5339     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5340       Dependent = true;
5341 
5342     if (Dependent) {
5343       if (ExecConfig) {
5344         return new (Context) CUDAKernelCallExpr(
5345             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5346             Context.DependentTy, VK_RValue, RParenLoc);
5347       } else {
5348 
5349        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5350             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5351             Fn->getLocStart());
5352 
5353         return new (Context) CallExpr(
5354             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5355       }
5356     }
5357 
5358     // Determine whether this is a call to an object (C++ [over.call.object]).
5359     if (Fn->getType()->isRecordType())
5360       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5361                                           RParenLoc);
5362 
5363     if (Fn->getType() == Context.UnknownAnyTy) {
5364       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5365       if (result.isInvalid()) return ExprError();
5366       Fn = result.get();
5367     }
5368 
5369     if (Fn->getType() == Context.BoundMemberTy) {
5370       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5371                                        RParenLoc);
5372     }
5373   }
5374 
5375   // Check for overloaded calls.  This can happen even in C due to extensions.
5376   if (Fn->getType() == Context.OverloadTy) {
5377     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5378 
5379     // We aren't supposed to apply this logic if there's an '&' involved.
5380     if (!find.HasFormOfMemberPointer) {
5381       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5382         return new (Context) CallExpr(
5383             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5384       OverloadExpr *ovl = find.Expression;
5385       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5386         return BuildOverloadedCallExpr(
5387             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5388             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5389       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5390                                        RParenLoc);
5391     }
5392   }
5393 
5394   // If we're directly calling a function, get the appropriate declaration.
5395   if (Fn->getType() == Context.UnknownAnyTy) {
5396     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5397     if (result.isInvalid()) return ExprError();
5398     Fn = result.get();
5399   }
5400 
5401   Expr *NakedFn = Fn->IgnoreParens();
5402 
5403   bool CallingNDeclIndirectly = false;
5404   NamedDecl *NDecl = nullptr;
5405   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5406     if (UnOp->getOpcode() == UO_AddrOf) {
5407       CallingNDeclIndirectly = true;
5408       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5409     }
5410   }
5411 
5412   if (isa<DeclRefExpr>(NakedFn)) {
5413     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5414 
5415     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5416     if (FDecl && FDecl->getBuiltinID()) {
5417       // Rewrite the function decl for this builtin by replacing parameters
5418       // with no explicit address space with the address space of the arguments
5419       // in ArgExprs.
5420       if ((FDecl =
5421                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5422         NDecl = FDecl;
5423         Fn = DeclRefExpr::Create(
5424             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5425             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5426       }
5427     }
5428   } else if (isa<MemberExpr>(NakedFn))
5429     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5430 
5431   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5432     if (CallingNDeclIndirectly &&
5433         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5434                                            Fn->getLocStart()))
5435       return ExprError();
5436 
5437     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5438       return ExprError();
5439 
5440     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5441   }
5442 
5443   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5444                                ExecConfig, IsExecConfig);
5445 }
5446 
5447 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5448 ///
5449 /// __builtin_astype( value, dst type )
5450 ///
5451 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5452                                  SourceLocation BuiltinLoc,
5453                                  SourceLocation RParenLoc) {
5454   ExprValueKind VK = VK_RValue;
5455   ExprObjectKind OK = OK_Ordinary;
5456   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5457   QualType SrcTy = E->getType();
5458   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5459     return ExprError(Diag(BuiltinLoc,
5460                           diag::err_invalid_astype_of_different_size)
5461                      << DstTy
5462                      << SrcTy
5463                      << E->getSourceRange());
5464   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5465 }
5466 
5467 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5468 /// provided arguments.
5469 ///
5470 /// __builtin_convertvector( value, dst type )
5471 ///
5472 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5473                                         SourceLocation BuiltinLoc,
5474                                         SourceLocation RParenLoc) {
5475   TypeSourceInfo *TInfo;
5476   GetTypeFromParser(ParsedDestTy, &TInfo);
5477   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5478 }
5479 
5480 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5481 /// i.e. an expression not of \p OverloadTy.  The expression should
5482 /// unary-convert to an expression of function-pointer or
5483 /// block-pointer type.
5484 ///
5485 /// \param NDecl the declaration being called, if available
5486 ExprResult
5487 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5488                             SourceLocation LParenLoc,
5489                             ArrayRef<Expr *> Args,
5490                             SourceLocation RParenLoc,
5491                             Expr *Config, bool IsExecConfig) {
5492   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5493   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5494 
5495   // Functions with 'interrupt' attribute cannot be called directly.
5496   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5497     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5498     return ExprError();
5499   }
5500 
5501   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5502   // so there's some risk when calling out to non-interrupt handler functions
5503   // that the callee might not preserve them. This is easy to diagnose here,
5504   // but can be very challenging to debug.
5505   if (auto *Caller = getCurFunctionDecl())
5506     if (Caller->hasAttr<ARMInterruptAttr>()) {
5507       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5508       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5509         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5510     }
5511 
5512   // Promote the function operand.
5513   // We special-case function promotion here because we only allow promoting
5514   // builtin functions to function pointers in the callee of a call.
5515   ExprResult Result;
5516   if (BuiltinID &&
5517       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5518     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5519                                CK_BuiltinFnToFnPtr).get();
5520   } else {
5521     Result = CallExprUnaryConversions(Fn);
5522   }
5523   if (Result.isInvalid())
5524     return ExprError();
5525   Fn = Result.get();
5526 
5527   // Make the call expr early, before semantic checks.  This guarantees cleanup
5528   // of arguments and function on error.
5529   CallExpr *TheCall;
5530   if (Config)
5531     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5532                                                cast<CallExpr>(Config), Args,
5533                                                Context.BoolTy, VK_RValue,
5534                                                RParenLoc);
5535   else
5536     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5537                                      VK_RValue, RParenLoc);
5538 
5539   if (!getLangOpts().CPlusPlus) {
5540     // C cannot always handle TypoExpr nodes in builtin calls and direct
5541     // function calls as their argument checking don't necessarily handle
5542     // dependent types properly, so make sure any TypoExprs have been
5543     // dealt with.
5544     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5545     if (!Result.isUsable()) return ExprError();
5546     TheCall = dyn_cast<CallExpr>(Result.get());
5547     if (!TheCall) return Result;
5548     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5549   }
5550 
5551   // Bail out early if calling a builtin with custom typechecking.
5552   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5553     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5554 
5555  retry:
5556   const FunctionType *FuncT;
5557   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5558     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5559     // have type pointer to function".
5560     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5561     if (!FuncT)
5562       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5563                          << Fn->getType() << Fn->getSourceRange());
5564   } else if (const BlockPointerType *BPT =
5565                Fn->getType()->getAs<BlockPointerType>()) {
5566     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5567   } else {
5568     // Handle calls to expressions of unknown-any type.
5569     if (Fn->getType() == Context.UnknownAnyTy) {
5570       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5571       if (rewrite.isInvalid()) return ExprError();
5572       Fn = rewrite.get();
5573       TheCall->setCallee(Fn);
5574       goto retry;
5575     }
5576 
5577     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5578       << Fn->getType() << Fn->getSourceRange());
5579   }
5580 
5581   if (getLangOpts().CUDA) {
5582     if (Config) {
5583       // CUDA: Kernel calls must be to global functions
5584       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5585         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5586             << FDecl << Fn->getSourceRange());
5587 
5588       // CUDA: Kernel function must have 'void' return type
5589       if (!FuncT->getReturnType()->isVoidType())
5590         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5591             << Fn->getType() << Fn->getSourceRange());
5592     } else {
5593       // CUDA: Calls to global functions must be configured
5594       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5595         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5596             << FDecl << Fn->getSourceRange());
5597     }
5598   }
5599 
5600   // Check for a valid return type
5601   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5602                           FDecl))
5603     return ExprError();
5604 
5605   // We know the result type of the call, set it.
5606   TheCall->setType(FuncT->getCallResultType(Context));
5607   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5608 
5609   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5610   if (Proto) {
5611     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5612                                 IsExecConfig))
5613       return ExprError();
5614   } else {
5615     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5616 
5617     if (FDecl) {
5618       // Check if we have too few/too many template arguments, based
5619       // on our knowledge of the function definition.
5620       const FunctionDecl *Def = nullptr;
5621       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5622         Proto = Def->getType()->getAs<FunctionProtoType>();
5623        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5624           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5625           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5626       }
5627 
5628       // If the function we're calling isn't a function prototype, but we have
5629       // a function prototype from a prior declaratiom, use that prototype.
5630       if (!FDecl->hasPrototype())
5631         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5632     }
5633 
5634     // Promote the arguments (C99 6.5.2.2p6).
5635     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5636       Expr *Arg = Args[i];
5637 
5638       if (Proto && i < Proto->getNumParams()) {
5639         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5640             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5641         ExprResult ArgE =
5642             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5643         if (ArgE.isInvalid())
5644           return true;
5645 
5646         Arg = ArgE.getAs<Expr>();
5647 
5648       } else {
5649         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5650 
5651         if (ArgE.isInvalid())
5652           return true;
5653 
5654         Arg = ArgE.getAs<Expr>();
5655       }
5656 
5657       if (RequireCompleteType(Arg->getLocStart(),
5658                               Arg->getType(),
5659                               diag::err_call_incomplete_argument, Arg))
5660         return ExprError();
5661 
5662       TheCall->setArg(i, Arg);
5663     }
5664   }
5665 
5666   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5667     if (!Method->isStatic())
5668       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5669         << Fn->getSourceRange());
5670 
5671   // Check for sentinels
5672   if (NDecl)
5673     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5674 
5675   // Do special checking on direct calls to functions.
5676   if (FDecl) {
5677     if (CheckFunctionCall(FDecl, TheCall, Proto))
5678       return ExprError();
5679 
5680     if (BuiltinID)
5681       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5682   } else if (NDecl) {
5683     if (CheckPointerCall(NDecl, TheCall, Proto))
5684       return ExprError();
5685   } else {
5686     if (CheckOtherCall(TheCall, Proto))
5687       return ExprError();
5688   }
5689 
5690   return MaybeBindToTemporary(TheCall);
5691 }
5692 
5693 ExprResult
5694 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5695                            SourceLocation RParenLoc, Expr *InitExpr) {
5696   assert(Ty && "ActOnCompoundLiteral(): missing type");
5697   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5698 
5699   TypeSourceInfo *TInfo;
5700   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5701   if (!TInfo)
5702     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5703 
5704   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5705 }
5706 
5707 ExprResult
5708 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5709                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5710   QualType literalType = TInfo->getType();
5711 
5712   if (literalType->isArrayType()) {
5713     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5714           diag::err_illegal_decl_array_incomplete_type,
5715           SourceRange(LParenLoc,
5716                       LiteralExpr->getSourceRange().getEnd())))
5717       return ExprError();
5718     if (literalType->isVariableArrayType())
5719       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5720         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5721   } else if (!literalType->isDependentType() &&
5722              RequireCompleteType(LParenLoc, literalType,
5723                diag::err_typecheck_decl_incomplete_type,
5724                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5725     return ExprError();
5726 
5727   InitializedEntity Entity
5728     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5729   InitializationKind Kind
5730     = InitializationKind::CreateCStyleCast(LParenLoc,
5731                                            SourceRange(LParenLoc, RParenLoc),
5732                                            /*InitList=*/true);
5733   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5734   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5735                                       &literalType);
5736   if (Result.isInvalid())
5737     return ExprError();
5738   LiteralExpr = Result.get();
5739 
5740   bool isFileScope = !CurContext->isFunctionOrMethod();
5741   if (isFileScope &&
5742       !LiteralExpr->isTypeDependent() &&
5743       !LiteralExpr->isValueDependent() &&
5744       !literalType->isDependentType()) { // 6.5.2.5p3
5745     if (CheckForConstantInitializer(LiteralExpr, literalType))
5746       return ExprError();
5747   }
5748 
5749   // In C, compound literals are l-values for some reason.
5750   // For GCC compatibility, in C++, file-scope array compound literals with
5751   // constant initializers are also l-values, and compound literals are
5752   // otherwise prvalues.
5753   //
5754   // (GCC also treats C++ list-initialized file-scope array prvalues with
5755   // constant initializers as l-values, but that's non-conforming, so we don't
5756   // follow it there.)
5757   //
5758   // FIXME: It would be better to handle the lvalue cases as materializing and
5759   // lifetime-extending a temporary object, but our materialized temporaries
5760   // representation only supports lifetime extension from a variable, not "out
5761   // of thin air".
5762   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5763   // is bound to the result of applying array-to-pointer decay to the compound
5764   // literal.
5765   // FIXME: GCC supports compound literals of reference type, which should
5766   // obviously have a value kind derived from the kind of reference involved.
5767   ExprValueKind VK =
5768       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5769           ? VK_RValue
5770           : VK_LValue;
5771 
5772   return MaybeBindToTemporary(
5773       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5774                                         VK, LiteralExpr, isFileScope));
5775 }
5776 
5777 ExprResult
5778 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5779                     SourceLocation RBraceLoc) {
5780   // Immediately handle non-overload placeholders.  Overloads can be
5781   // resolved contextually, but everything else here can't.
5782   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5783     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5784       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5785 
5786       // Ignore failures; dropping the entire initializer list because
5787       // of one failure would be terrible for indexing/etc.
5788       if (result.isInvalid()) continue;
5789 
5790       InitArgList[I] = result.get();
5791     }
5792   }
5793 
5794   // Semantic analysis for initializers is done by ActOnDeclarator() and
5795   // CheckInitializer() - it requires knowledge of the object being initialized.
5796 
5797   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5798                                                RBraceLoc);
5799   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5800   return E;
5801 }
5802 
5803 /// Do an explicit extend of the given block pointer if we're in ARC.
5804 void Sema::maybeExtendBlockObject(ExprResult &E) {
5805   assert(E.get()->getType()->isBlockPointerType());
5806   assert(E.get()->isRValue());
5807 
5808   // Only do this in an r-value context.
5809   if (!getLangOpts().ObjCAutoRefCount) return;
5810 
5811   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5812                                CK_ARCExtendBlockObject, E.get(),
5813                                /*base path*/ nullptr, VK_RValue);
5814   Cleanup.setExprNeedsCleanups(true);
5815 }
5816 
5817 /// Prepare a conversion of the given expression to an ObjC object
5818 /// pointer type.
5819 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5820   QualType type = E.get()->getType();
5821   if (type->isObjCObjectPointerType()) {
5822     return CK_BitCast;
5823   } else if (type->isBlockPointerType()) {
5824     maybeExtendBlockObject(E);
5825     return CK_BlockPointerToObjCPointerCast;
5826   } else {
5827     assert(type->isPointerType());
5828     return CK_CPointerToObjCPointerCast;
5829   }
5830 }
5831 
5832 /// Prepares for a scalar cast, performing all the necessary stages
5833 /// except the final cast and returning the kind required.
5834 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5835   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5836   // Also, callers should have filtered out the invalid cases with
5837   // pointers.  Everything else should be possible.
5838 
5839   QualType SrcTy = Src.get()->getType();
5840   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5841     return CK_NoOp;
5842 
5843   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5844   case Type::STK_MemberPointer:
5845     llvm_unreachable("member pointer type in C");
5846 
5847   case Type::STK_CPointer:
5848   case Type::STK_BlockPointer:
5849   case Type::STK_ObjCObjectPointer:
5850     switch (DestTy->getScalarTypeKind()) {
5851     case Type::STK_CPointer: {
5852       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5853       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5854       if (SrcAS != DestAS)
5855         return CK_AddressSpaceConversion;
5856       return CK_BitCast;
5857     }
5858     case Type::STK_BlockPointer:
5859       return (SrcKind == Type::STK_BlockPointer
5860                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5861     case Type::STK_ObjCObjectPointer:
5862       if (SrcKind == Type::STK_ObjCObjectPointer)
5863         return CK_BitCast;
5864       if (SrcKind == Type::STK_CPointer)
5865         return CK_CPointerToObjCPointerCast;
5866       maybeExtendBlockObject(Src);
5867       return CK_BlockPointerToObjCPointerCast;
5868     case Type::STK_Bool:
5869       return CK_PointerToBoolean;
5870     case Type::STK_Integral:
5871       return CK_PointerToIntegral;
5872     case Type::STK_Floating:
5873     case Type::STK_FloatingComplex:
5874     case Type::STK_IntegralComplex:
5875     case Type::STK_MemberPointer:
5876       llvm_unreachable("illegal cast from pointer");
5877     }
5878     llvm_unreachable("Should have returned before this");
5879 
5880   case Type::STK_Bool: // casting from bool is like casting from an integer
5881   case Type::STK_Integral:
5882     switch (DestTy->getScalarTypeKind()) {
5883     case Type::STK_CPointer:
5884     case Type::STK_ObjCObjectPointer:
5885     case Type::STK_BlockPointer:
5886       if (Src.get()->isNullPointerConstant(Context,
5887                                            Expr::NPC_ValueDependentIsNull))
5888         return CK_NullToPointer;
5889       return CK_IntegralToPointer;
5890     case Type::STK_Bool:
5891       return CK_IntegralToBoolean;
5892     case Type::STK_Integral:
5893       return CK_IntegralCast;
5894     case Type::STK_Floating:
5895       return CK_IntegralToFloating;
5896     case Type::STK_IntegralComplex:
5897       Src = ImpCastExprToType(Src.get(),
5898                       DestTy->castAs<ComplexType>()->getElementType(),
5899                       CK_IntegralCast);
5900       return CK_IntegralRealToComplex;
5901     case Type::STK_FloatingComplex:
5902       Src = ImpCastExprToType(Src.get(),
5903                       DestTy->castAs<ComplexType>()->getElementType(),
5904                       CK_IntegralToFloating);
5905       return CK_FloatingRealToComplex;
5906     case Type::STK_MemberPointer:
5907       llvm_unreachable("member pointer type in C");
5908     }
5909     llvm_unreachable("Should have returned before this");
5910 
5911   case Type::STK_Floating:
5912     switch (DestTy->getScalarTypeKind()) {
5913     case Type::STK_Floating:
5914       return CK_FloatingCast;
5915     case Type::STK_Bool:
5916       return CK_FloatingToBoolean;
5917     case Type::STK_Integral:
5918       return CK_FloatingToIntegral;
5919     case Type::STK_FloatingComplex:
5920       Src = ImpCastExprToType(Src.get(),
5921                               DestTy->castAs<ComplexType>()->getElementType(),
5922                               CK_FloatingCast);
5923       return CK_FloatingRealToComplex;
5924     case Type::STK_IntegralComplex:
5925       Src = ImpCastExprToType(Src.get(),
5926                               DestTy->castAs<ComplexType>()->getElementType(),
5927                               CK_FloatingToIntegral);
5928       return CK_IntegralRealToComplex;
5929     case Type::STK_CPointer:
5930     case Type::STK_ObjCObjectPointer:
5931     case Type::STK_BlockPointer:
5932       llvm_unreachable("valid float->pointer cast?");
5933     case Type::STK_MemberPointer:
5934       llvm_unreachable("member pointer type in C");
5935     }
5936     llvm_unreachable("Should have returned before this");
5937 
5938   case Type::STK_FloatingComplex:
5939     switch (DestTy->getScalarTypeKind()) {
5940     case Type::STK_FloatingComplex:
5941       return CK_FloatingComplexCast;
5942     case Type::STK_IntegralComplex:
5943       return CK_FloatingComplexToIntegralComplex;
5944     case Type::STK_Floating: {
5945       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5946       if (Context.hasSameType(ET, DestTy))
5947         return CK_FloatingComplexToReal;
5948       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5949       return CK_FloatingCast;
5950     }
5951     case Type::STK_Bool:
5952       return CK_FloatingComplexToBoolean;
5953     case Type::STK_Integral:
5954       Src = ImpCastExprToType(Src.get(),
5955                               SrcTy->castAs<ComplexType>()->getElementType(),
5956                               CK_FloatingComplexToReal);
5957       return CK_FloatingToIntegral;
5958     case Type::STK_CPointer:
5959     case Type::STK_ObjCObjectPointer:
5960     case Type::STK_BlockPointer:
5961       llvm_unreachable("valid complex float->pointer cast?");
5962     case Type::STK_MemberPointer:
5963       llvm_unreachable("member pointer type in C");
5964     }
5965     llvm_unreachable("Should have returned before this");
5966 
5967   case Type::STK_IntegralComplex:
5968     switch (DestTy->getScalarTypeKind()) {
5969     case Type::STK_FloatingComplex:
5970       return CK_IntegralComplexToFloatingComplex;
5971     case Type::STK_IntegralComplex:
5972       return CK_IntegralComplexCast;
5973     case Type::STK_Integral: {
5974       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5975       if (Context.hasSameType(ET, DestTy))
5976         return CK_IntegralComplexToReal;
5977       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5978       return CK_IntegralCast;
5979     }
5980     case Type::STK_Bool:
5981       return CK_IntegralComplexToBoolean;
5982     case Type::STK_Floating:
5983       Src = ImpCastExprToType(Src.get(),
5984                               SrcTy->castAs<ComplexType>()->getElementType(),
5985                               CK_IntegralComplexToReal);
5986       return CK_IntegralToFloating;
5987     case Type::STK_CPointer:
5988     case Type::STK_ObjCObjectPointer:
5989     case Type::STK_BlockPointer:
5990       llvm_unreachable("valid complex int->pointer cast?");
5991     case Type::STK_MemberPointer:
5992       llvm_unreachable("member pointer type in C");
5993     }
5994     llvm_unreachable("Should have returned before this");
5995   }
5996 
5997   llvm_unreachable("Unhandled scalar cast");
5998 }
5999 
6000 static bool breakDownVectorType(QualType type, uint64_t &len,
6001                                 QualType &eltType) {
6002   // Vectors are simple.
6003   if (const VectorType *vecType = type->getAs<VectorType>()) {
6004     len = vecType->getNumElements();
6005     eltType = vecType->getElementType();
6006     assert(eltType->isScalarType());
6007     return true;
6008   }
6009 
6010   // We allow lax conversion to and from non-vector types, but only if
6011   // they're real types (i.e. non-complex, non-pointer scalar types).
6012   if (!type->isRealType()) return false;
6013 
6014   len = 1;
6015   eltType = type;
6016   return true;
6017 }
6018 
6019 /// Are the two types lax-compatible vector types?  That is, given
6020 /// that one of them is a vector, do they have equal storage sizes,
6021 /// where the storage size is the number of elements times the element
6022 /// size?
6023 ///
6024 /// This will also return false if either of the types is neither a
6025 /// vector nor a real type.
6026 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6027   assert(destTy->isVectorType() || srcTy->isVectorType());
6028 
6029   // Disallow lax conversions between scalars and ExtVectors (these
6030   // conversions are allowed for other vector types because common headers
6031   // depend on them).  Most scalar OP ExtVector cases are handled by the
6032   // splat path anyway, which does what we want (convert, not bitcast).
6033   // What this rules out for ExtVectors is crazy things like char4*float.
6034   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6035   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6036 
6037   uint64_t srcLen, destLen;
6038   QualType srcEltTy, destEltTy;
6039   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6040   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6041 
6042   // ASTContext::getTypeSize will return the size rounded up to a
6043   // power of 2, so instead of using that, we need to use the raw
6044   // element size multiplied by the element count.
6045   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6046   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6047 
6048   return (srcLen * srcEltSize == destLen * destEltSize);
6049 }
6050 
6051 /// Is this a legal conversion between two types, one of which is
6052 /// known to be a vector type?
6053 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6054   assert(destTy->isVectorType() || srcTy->isVectorType());
6055 
6056   if (!Context.getLangOpts().LaxVectorConversions)
6057     return false;
6058   return areLaxCompatibleVectorTypes(srcTy, destTy);
6059 }
6060 
6061 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6062                            CastKind &Kind) {
6063   assert(VectorTy->isVectorType() && "Not a vector type!");
6064 
6065   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6066     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6067       return Diag(R.getBegin(),
6068                   Ty->isVectorType() ?
6069                   diag::err_invalid_conversion_between_vectors :
6070                   diag::err_invalid_conversion_between_vector_and_integer)
6071         << VectorTy << Ty << R;
6072   } else
6073     return Diag(R.getBegin(),
6074                 diag::err_invalid_conversion_between_vector_and_scalar)
6075       << VectorTy << Ty << R;
6076 
6077   Kind = CK_BitCast;
6078   return false;
6079 }
6080 
6081 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6082   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6083 
6084   if (DestElemTy == SplattedExpr->getType())
6085     return SplattedExpr;
6086 
6087   assert(DestElemTy->isFloatingType() ||
6088          DestElemTy->isIntegralOrEnumerationType());
6089 
6090   CastKind CK;
6091   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6092     // OpenCL requires that we convert `true` boolean expressions to -1, but
6093     // only when splatting vectors.
6094     if (DestElemTy->isFloatingType()) {
6095       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6096       // in two steps: boolean to signed integral, then to floating.
6097       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6098                                                  CK_BooleanToSignedIntegral);
6099       SplattedExpr = CastExprRes.get();
6100       CK = CK_IntegralToFloating;
6101     } else {
6102       CK = CK_BooleanToSignedIntegral;
6103     }
6104   } else {
6105     ExprResult CastExprRes = SplattedExpr;
6106     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6107     if (CastExprRes.isInvalid())
6108       return ExprError();
6109     SplattedExpr = CastExprRes.get();
6110   }
6111   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6112 }
6113 
6114 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6115                                     Expr *CastExpr, CastKind &Kind) {
6116   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6117 
6118   QualType SrcTy = CastExpr->getType();
6119 
6120   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6121   // an ExtVectorType.
6122   // In OpenCL, casts between vectors of different types are not allowed.
6123   // (See OpenCL 6.2).
6124   if (SrcTy->isVectorType()) {
6125     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6126         (getLangOpts().OpenCL &&
6127          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6128       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6129         << DestTy << SrcTy << R;
6130       return ExprError();
6131     }
6132     Kind = CK_BitCast;
6133     return CastExpr;
6134   }
6135 
6136   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6137   // conversion will take place first from scalar to elt type, and then
6138   // splat from elt type to vector.
6139   if (SrcTy->isPointerType())
6140     return Diag(R.getBegin(),
6141                 diag::err_invalid_conversion_between_vector_and_scalar)
6142       << DestTy << SrcTy << R;
6143 
6144   Kind = CK_VectorSplat;
6145   return prepareVectorSplat(DestTy, CastExpr);
6146 }
6147 
6148 ExprResult
6149 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6150                     Declarator &D, ParsedType &Ty,
6151                     SourceLocation RParenLoc, Expr *CastExpr) {
6152   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6153          "ActOnCastExpr(): missing type or expr");
6154 
6155   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6156   if (D.isInvalidType())
6157     return ExprError();
6158 
6159   if (getLangOpts().CPlusPlus) {
6160     // Check that there are no default arguments (C++ only).
6161     CheckExtraCXXDefaultArguments(D);
6162   } else {
6163     // Make sure any TypoExprs have been dealt with.
6164     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6165     if (!Res.isUsable())
6166       return ExprError();
6167     CastExpr = Res.get();
6168   }
6169 
6170   checkUnusedDeclAttributes(D);
6171 
6172   QualType castType = castTInfo->getType();
6173   Ty = CreateParsedType(castType, castTInfo);
6174 
6175   bool isVectorLiteral = false;
6176 
6177   // Check for an altivec or OpenCL literal,
6178   // i.e. all the elements are integer constants.
6179   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6180   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6181   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6182        && castType->isVectorType() && (PE || PLE)) {
6183     if (PLE && PLE->getNumExprs() == 0) {
6184       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6185       return ExprError();
6186     }
6187     if (PE || PLE->getNumExprs() == 1) {
6188       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6189       if (!E->getType()->isVectorType())
6190         isVectorLiteral = true;
6191     }
6192     else
6193       isVectorLiteral = true;
6194   }
6195 
6196   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6197   // then handle it as such.
6198   if (isVectorLiteral)
6199     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6200 
6201   // If the Expr being casted is a ParenListExpr, handle it specially.
6202   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6203   // sequence of BinOp comma operators.
6204   if (isa<ParenListExpr>(CastExpr)) {
6205     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6206     if (Result.isInvalid()) return ExprError();
6207     CastExpr = Result.get();
6208   }
6209 
6210   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6211       !getSourceManager().isInSystemMacro(LParenLoc))
6212     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6213 
6214   CheckTollFreeBridgeCast(castType, CastExpr);
6215 
6216   CheckObjCBridgeRelatedCast(castType, CastExpr);
6217 
6218   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6219 
6220   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6221 }
6222 
6223 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6224                                     SourceLocation RParenLoc, Expr *E,
6225                                     TypeSourceInfo *TInfo) {
6226   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6227          "Expected paren or paren list expression");
6228 
6229   Expr **exprs;
6230   unsigned numExprs;
6231   Expr *subExpr;
6232   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6233   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6234     LiteralLParenLoc = PE->getLParenLoc();
6235     LiteralRParenLoc = PE->getRParenLoc();
6236     exprs = PE->getExprs();
6237     numExprs = PE->getNumExprs();
6238   } else { // isa<ParenExpr> by assertion at function entrance
6239     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6240     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6241     subExpr = cast<ParenExpr>(E)->getSubExpr();
6242     exprs = &subExpr;
6243     numExprs = 1;
6244   }
6245 
6246   QualType Ty = TInfo->getType();
6247   assert(Ty->isVectorType() && "Expected vector type");
6248 
6249   SmallVector<Expr *, 8> initExprs;
6250   const VectorType *VTy = Ty->getAs<VectorType>();
6251   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6252 
6253   // '(...)' form of vector initialization in AltiVec: the number of
6254   // initializers must be one or must match the size of the vector.
6255   // If a single value is specified in the initializer then it will be
6256   // replicated to all the components of the vector
6257   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6258     // The number of initializers must be one or must match the size of the
6259     // vector. If a single value is specified in the initializer then it will
6260     // be replicated to all the components of the vector
6261     if (numExprs == 1) {
6262       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6263       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6264       if (Literal.isInvalid())
6265         return ExprError();
6266       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6267                                   PrepareScalarCast(Literal, ElemTy));
6268       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6269     }
6270     else if (numExprs < numElems) {
6271       Diag(E->getExprLoc(),
6272            diag::err_incorrect_number_of_vector_initializers);
6273       return ExprError();
6274     }
6275     else
6276       initExprs.append(exprs, exprs + numExprs);
6277   }
6278   else {
6279     // For OpenCL, when the number of initializers is a single value,
6280     // it will be replicated to all components of the vector.
6281     if (getLangOpts().OpenCL &&
6282         VTy->getVectorKind() == VectorType::GenericVector &&
6283         numExprs == 1) {
6284         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6285         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6286         if (Literal.isInvalid())
6287           return ExprError();
6288         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6289                                     PrepareScalarCast(Literal, ElemTy));
6290         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6291     }
6292 
6293     initExprs.append(exprs, exprs + numExprs);
6294   }
6295   // FIXME: This means that pretty-printing the final AST will produce curly
6296   // braces instead of the original commas.
6297   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6298                                                    initExprs, LiteralRParenLoc);
6299   initE->setType(Ty);
6300   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6301 }
6302 
6303 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6304 /// the ParenListExpr into a sequence of comma binary operators.
6305 ExprResult
6306 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6307   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6308   if (!E)
6309     return OrigExpr;
6310 
6311   ExprResult Result(E->getExpr(0));
6312 
6313   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6314     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6315                         E->getExpr(i));
6316 
6317   if (Result.isInvalid()) return ExprError();
6318 
6319   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6320 }
6321 
6322 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6323                                     SourceLocation R,
6324                                     MultiExprArg Val) {
6325   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6326   return expr;
6327 }
6328 
6329 /// Emit a specialized diagnostic when one expression is a null pointer
6330 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6331 /// emitted.
6332 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6333                                       SourceLocation QuestionLoc) {
6334   Expr *NullExpr = LHSExpr;
6335   Expr *NonPointerExpr = RHSExpr;
6336   Expr::NullPointerConstantKind NullKind =
6337       NullExpr->isNullPointerConstant(Context,
6338                                       Expr::NPC_ValueDependentIsNotNull);
6339 
6340   if (NullKind == Expr::NPCK_NotNull) {
6341     NullExpr = RHSExpr;
6342     NonPointerExpr = LHSExpr;
6343     NullKind =
6344         NullExpr->isNullPointerConstant(Context,
6345                                         Expr::NPC_ValueDependentIsNotNull);
6346   }
6347 
6348   if (NullKind == Expr::NPCK_NotNull)
6349     return false;
6350 
6351   if (NullKind == Expr::NPCK_ZeroExpression)
6352     return false;
6353 
6354   if (NullKind == Expr::NPCK_ZeroLiteral) {
6355     // In this case, check to make sure that we got here from a "NULL"
6356     // string in the source code.
6357     NullExpr = NullExpr->IgnoreParenImpCasts();
6358     SourceLocation loc = NullExpr->getExprLoc();
6359     if (!findMacroSpelling(loc, "NULL"))
6360       return false;
6361   }
6362 
6363   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6364   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6365       << NonPointerExpr->getType() << DiagType
6366       << NonPointerExpr->getSourceRange();
6367   return true;
6368 }
6369 
6370 /// Return false if the condition expression is valid, true otherwise.
6371 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6372   QualType CondTy = Cond->getType();
6373 
6374   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6375   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6376     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6377       << CondTy << Cond->getSourceRange();
6378     return true;
6379   }
6380 
6381   // C99 6.5.15p2
6382   if (CondTy->isScalarType()) return false;
6383 
6384   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6385     << CondTy << Cond->getSourceRange();
6386   return true;
6387 }
6388 
6389 /// Handle when one or both operands are void type.
6390 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6391                                          ExprResult &RHS) {
6392     Expr *LHSExpr = LHS.get();
6393     Expr *RHSExpr = RHS.get();
6394 
6395     if (!LHSExpr->getType()->isVoidType())
6396       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6397         << RHSExpr->getSourceRange();
6398     if (!RHSExpr->getType()->isVoidType())
6399       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6400         << LHSExpr->getSourceRange();
6401     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6402     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6403     return S.Context.VoidTy;
6404 }
6405 
6406 /// Return false if the NullExpr can be promoted to PointerTy,
6407 /// true otherwise.
6408 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6409                                         QualType PointerTy) {
6410   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6411       !NullExpr.get()->isNullPointerConstant(S.Context,
6412                                             Expr::NPC_ValueDependentIsNull))
6413     return true;
6414 
6415   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6416   return false;
6417 }
6418 
6419 /// Checks compatibility between two pointers and return the resulting
6420 /// type.
6421 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6422                                                      ExprResult &RHS,
6423                                                      SourceLocation Loc) {
6424   QualType LHSTy = LHS.get()->getType();
6425   QualType RHSTy = RHS.get()->getType();
6426 
6427   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6428     // Two identical pointers types are always compatible.
6429     return LHSTy;
6430   }
6431 
6432   QualType lhptee, rhptee;
6433 
6434   // Get the pointee types.
6435   bool IsBlockPointer = false;
6436   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6437     lhptee = LHSBTy->getPointeeType();
6438     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6439     IsBlockPointer = true;
6440   } else {
6441     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6442     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6443   }
6444 
6445   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6446   // differently qualified versions of compatible types, the result type is
6447   // a pointer to an appropriately qualified version of the composite
6448   // type.
6449 
6450   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6451   // clause doesn't make sense for our extensions. E.g. address space 2 should
6452   // be incompatible with address space 3: they may live on different devices or
6453   // anything.
6454   Qualifiers lhQual = lhptee.getQualifiers();
6455   Qualifiers rhQual = rhptee.getQualifiers();
6456 
6457   LangAS ResultAddrSpace = LangAS::Default;
6458   LangAS LAddrSpace = lhQual.getAddressSpace();
6459   LangAS RAddrSpace = rhQual.getAddressSpace();
6460   if (S.getLangOpts().OpenCL) {
6461     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6462     // spaces is disallowed.
6463     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6464       ResultAddrSpace = LAddrSpace;
6465     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6466       ResultAddrSpace = RAddrSpace;
6467     else {
6468       S.Diag(Loc,
6469              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6470           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6471           << RHS.get()->getSourceRange();
6472       return QualType();
6473     }
6474   }
6475 
6476   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6477   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6478   lhQual.removeCVRQualifiers();
6479   rhQual.removeCVRQualifiers();
6480 
6481   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6482   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6483   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6484   // qual types are compatible iff
6485   //  * corresponded types are compatible
6486   //  * CVR qualifiers are equal
6487   //  * address spaces are equal
6488   // Thus for conditional operator we merge CVR and address space unqualified
6489   // pointees and if there is a composite type we return a pointer to it with
6490   // merged qualifiers.
6491   if (S.getLangOpts().OpenCL) {
6492     LHSCastKind = LAddrSpace == ResultAddrSpace
6493                       ? CK_BitCast
6494                       : CK_AddressSpaceConversion;
6495     RHSCastKind = RAddrSpace == ResultAddrSpace
6496                       ? CK_BitCast
6497                       : CK_AddressSpaceConversion;
6498     lhQual.removeAddressSpace();
6499     rhQual.removeAddressSpace();
6500   }
6501 
6502   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6503   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6504 
6505   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6506 
6507   if (CompositeTy.isNull()) {
6508     // In this situation, we assume void* type. No especially good
6509     // reason, but this is what gcc does, and we do have to pick
6510     // to get a consistent AST.
6511     QualType incompatTy;
6512     incompatTy = S.Context.getPointerType(
6513         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6514     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6515     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6516     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6517     // for casts between types with incompatible address space qualifiers.
6518     // For the following code the compiler produces casts between global and
6519     // local address spaces of the corresponded innermost pointees:
6520     // local int *global *a;
6521     // global int *global *b;
6522     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6523     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6524         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6525         << RHS.get()->getSourceRange();
6526     return incompatTy;
6527   }
6528 
6529   // The pointer types are compatible.
6530   // In case of OpenCL ResultTy should have the address space qualifier
6531   // which is a superset of address spaces of both the 2nd and the 3rd
6532   // operands of the conditional operator.
6533   QualType ResultTy = [&, ResultAddrSpace]() {
6534     if (S.getLangOpts().OpenCL) {
6535       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6536       CompositeQuals.setAddressSpace(ResultAddrSpace);
6537       return S.Context
6538           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6539           .withCVRQualifiers(MergedCVRQual);
6540     }
6541     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6542   }();
6543   if (IsBlockPointer)
6544     ResultTy = S.Context.getBlockPointerType(ResultTy);
6545   else
6546     ResultTy = S.Context.getPointerType(ResultTy);
6547 
6548   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6549   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6550   return ResultTy;
6551 }
6552 
6553 /// Return the resulting type when the operands are both block pointers.
6554 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6555                                                           ExprResult &LHS,
6556                                                           ExprResult &RHS,
6557                                                           SourceLocation Loc) {
6558   QualType LHSTy = LHS.get()->getType();
6559   QualType RHSTy = RHS.get()->getType();
6560 
6561   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6562     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6563       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6564       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6565       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6566       return destType;
6567     }
6568     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6569       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6570       << RHS.get()->getSourceRange();
6571     return QualType();
6572   }
6573 
6574   // We have 2 block pointer types.
6575   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6576 }
6577 
6578 /// Return the resulting type when the operands are both pointers.
6579 static QualType
6580 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6581                                             ExprResult &RHS,
6582                                             SourceLocation Loc) {
6583   // get the pointer types
6584   QualType LHSTy = LHS.get()->getType();
6585   QualType RHSTy = RHS.get()->getType();
6586 
6587   // get the "pointed to" types
6588   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6589   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6590 
6591   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6592   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6593     // Figure out necessary qualifiers (C99 6.5.15p6)
6594     QualType destPointee
6595       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6596     QualType destType = S.Context.getPointerType(destPointee);
6597     // Add qualifiers if necessary.
6598     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6599     // Promote to void*.
6600     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6601     return destType;
6602   }
6603   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6604     QualType destPointee
6605       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6606     QualType destType = S.Context.getPointerType(destPointee);
6607     // Add qualifiers if necessary.
6608     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6609     // Promote to void*.
6610     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6611     return destType;
6612   }
6613 
6614   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6615 }
6616 
6617 /// Return false if the first expression is not an integer and the second
6618 /// expression is not a pointer, true otherwise.
6619 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6620                                         Expr* PointerExpr, SourceLocation Loc,
6621                                         bool IsIntFirstExpr) {
6622   if (!PointerExpr->getType()->isPointerType() ||
6623       !Int.get()->getType()->isIntegerType())
6624     return false;
6625 
6626   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6627   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6628 
6629   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6630     << Expr1->getType() << Expr2->getType()
6631     << Expr1->getSourceRange() << Expr2->getSourceRange();
6632   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6633                             CK_IntegralToPointer);
6634   return true;
6635 }
6636 
6637 /// Simple conversion between integer and floating point types.
6638 ///
6639 /// Used when handling the OpenCL conditional operator where the
6640 /// condition is a vector while the other operands are scalar.
6641 ///
6642 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6643 /// types are either integer or floating type. Between the two
6644 /// operands, the type with the higher rank is defined as the "result
6645 /// type". The other operand needs to be promoted to the same type. No
6646 /// other type promotion is allowed. We cannot use
6647 /// UsualArithmeticConversions() for this purpose, since it always
6648 /// promotes promotable types.
6649 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6650                                             ExprResult &RHS,
6651                                             SourceLocation QuestionLoc) {
6652   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6653   if (LHS.isInvalid())
6654     return QualType();
6655   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6656   if (RHS.isInvalid())
6657     return QualType();
6658 
6659   // For conversion purposes, we ignore any qualifiers.
6660   // For example, "const float" and "float" are equivalent.
6661   QualType LHSType =
6662     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6663   QualType RHSType =
6664     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6665 
6666   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6667     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6668       << LHSType << LHS.get()->getSourceRange();
6669     return QualType();
6670   }
6671 
6672   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6673     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6674       << RHSType << RHS.get()->getSourceRange();
6675     return QualType();
6676   }
6677 
6678   // If both types are identical, no conversion is needed.
6679   if (LHSType == RHSType)
6680     return LHSType;
6681 
6682   // Now handle "real" floating types (i.e. float, double, long double).
6683   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6684     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6685                                  /*IsCompAssign = */ false);
6686 
6687   // Finally, we have two differing integer types.
6688   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6689   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6690 }
6691 
6692 /// Convert scalar operands to a vector that matches the
6693 ///        condition in length.
6694 ///
6695 /// Used when handling the OpenCL conditional operator where the
6696 /// condition is a vector while the other operands are scalar.
6697 ///
6698 /// We first compute the "result type" for the scalar operands
6699 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6700 /// into a vector of that type where the length matches the condition
6701 /// vector type. s6.11.6 requires that the element types of the result
6702 /// and the condition must have the same number of bits.
6703 static QualType
6704 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6705                               QualType CondTy, SourceLocation QuestionLoc) {
6706   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6707   if (ResTy.isNull()) return QualType();
6708 
6709   const VectorType *CV = CondTy->getAs<VectorType>();
6710   assert(CV);
6711 
6712   // Determine the vector result type
6713   unsigned NumElements = CV->getNumElements();
6714   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6715 
6716   // Ensure that all types have the same number of bits
6717   if (S.Context.getTypeSize(CV->getElementType())
6718       != S.Context.getTypeSize(ResTy)) {
6719     // Since VectorTy is created internally, it does not pretty print
6720     // with an OpenCL name. Instead, we just print a description.
6721     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6722     SmallString<64> Str;
6723     llvm::raw_svector_ostream OS(Str);
6724     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6725     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6726       << CondTy << OS.str();
6727     return QualType();
6728   }
6729 
6730   // Convert operands to the vector result type
6731   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6732   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6733 
6734   return VectorTy;
6735 }
6736 
6737 /// Return false if this is a valid OpenCL condition vector
6738 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6739                                        SourceLocation QuestionLoc) {
6740   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6741   // integral type.
6742   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6743   assert(CondTy);
6744   QualType EleTy = CondTy->getElementType();
6745   if (EleTy->isIntegerType()) return false;
6746 
6747   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6748     << Cond->getType() << Cond->getSourceRange();
6749   return true;
6750 }
6751 
6752 /// Return false if the vector condition type and the vector
6753 ///        result type are compatible.
6754 ///
6755 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6756 /// number of elements, and their element types have the same number
6757 /// of bits.
6758 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6759                               SourceLocation QuestionLoc) {
6760   const VectorType *CV = CondTy->getAs<VectorType>();
6761   const VectorType *RV = VecResTy->getAs<VectorType>();
6762   assert(CV && RV);
6763 
6764   if (CV->getNumElements() != RV->getNumElements()) {
6765     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6766       << CondTy << VecResTy;
6767     return true;
6768   }
6769 
6770   QualType CVE = CV->getElementType();
6771   QualType RVE = RV->getElementType();
6772 
6773   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6774     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6775       << CondTy << VecResTy;
6776     return true;
6777   }
6778 
6779   return false;
6780 }
6781 
6782 /// Return the resulting type for the conditional operator in
6783 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6784 ///        s6.3.i) when the condition is a vector type.
6785 static QualType
6786 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6787                              ExprResult &LHS, ExprResult &RHS,
6788                              SourceLocation QuestionLoc) {
6789   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6790   if (Cond.isInvalid())
6791     return QualType();
6792   QualType CondTy = Cond.get()->getType();
6793 
6794   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6795     return QualType();
6796 
6797   // If either operand is a vector then find the vector type of the
6798   // result as specified in OpenCL v1.1 s6.3.i.
6799   if (LHS.get()->getType()->isVectorType() ||
6800       RHS.get()->getType()->isVectorType()) {
6801     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6802                                               /*isCompAssign*/false,
6803                                               /*AllowBothBool*/true,
6804                                               /*AllowBoolConversions*/false);
6805     if (VecResTy.isNull()) return QualType();
6806     // The result type must match the condition type as specified in
6807     // OpenCL v1.1 s6.11.6.
6808     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6809       return QualType();
6810     return VecResTy;
6811   }
6812 
6813   // Both operands are scalar.
6814   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6815 }
6816 
6817 /// Return true if the Expr is block type
6818 static bool checkBlockType(Sema &S, const Expr *E) {
6819   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6820     QualType Ty = CE->getCallee()->getType();
6821     if (Ty->isBlockPointerType()) {
6822       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6823       return true;
6824     }
6825   }
6826   return false;
6827 }
6828 
6829 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6830 /// In that case, LHS = cond.
6831 /// C99 6.5.15
6832 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6833                                         ExprResult &RHS, ExprValueKind &VK,
6834                                         ExprObjectKind &OK,
6835                                         SourceLocation QuestionLoc) {
6836 
6837   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6838   if (!LHSResult.isUsable()) return QualType();
6839   LHS = LHSResult;
6840 
6841   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6842   if (!RHSResult.isUsable()) return QualType();
6843   RHS = RHSResult;
6844 
6845   // C++ is sufficiently different to merit its own checker.
6846   if (getLangOpts().CPlusPlus)
6847     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6848 
6849   VK = VK_RValue;
6850   OK = OK_Ordinary;
6851 
6852   // The OpenCL operator with a vector condition is sufficiently
6853   // different to merit its own checker.
6854   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6855     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6856 
6857   // First, check the condition.
6858   Cond = UsualUnaryConversions(Cond.get());
6859   if (Cond.isInvalid())
6860     return QualType();
6861   if (checkCondition(*this, Cond.get(), QuestionLoc))
6862     return QualType();
6863 
6864   // Now check the two expressions.
6865   if (LHS.get()->getType()->isVectorType() ||
6866       RHS.get()->getType()->isVectorType())
6867     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6868                                /*AllowBothBool*/true,
6869                                /*AllowBoolConversions*/false);
6870 
6871   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6872   if (LHS.isInvalid() || RHS.isInvalid())
6873     return QualType();
6874 
6875   QualType LHSTy = LHS.get()->getType();
6876   QualType RHSTy = RHS.get()->getType();
6877 
6878   // Diagnose attempts to convert between __float128 and long double where
6879   // such conversions currently can't be handled.
6880   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6881     Diag(QuestionLoc,
6882          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6883       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6884     return QualType();
6885   }
6886 
6887   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6888   // selection operator (?:).
6889   if (getLangOpts().OpenCL &&
6890       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6891     return QualType();
6892   }
6893 
6894   // If both operands have arithmetic type, do the usual arithmetic conversions
6895   // to find a common type: C99 6.5.15p3,5.
6896   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6897     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6898     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6899 
6900     return ResTy;
6901   }
6902 
6903   // If both operands are the same structure or union type, the result is that
6904   // type.
6905   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6906     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6907       if (LHSRT->getDecl() == RHSRT->getDecl())
6908         // "If both the operands have structure or union type, the result has
6909         // that type."  This implies that CV qualifiers are dropped.
6910         return LHSTy.getUnqualifiedType();
6911     // FIXME: Type of conditional expression must be complete in C mode.
6912   }
6913 
6914   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6915   // The following || allows only one side to be void (a GCC-ism).
6916   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6917     return checkConditionalVoidType(*this, LHS, RHS);
6918   }
6919 
6920   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6921   // the type of the other operand."
6922   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6923   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6924 
6925   // All objective-c pointer type analysis is done here.
6926   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6927                                                         QuestionLoc);
6928   if (LHS.isInvalid() || RHS.isInvalid())
6929     return QualType();
6930   if (!compositeType.isNull())
6931     return compositeType;
6932 
6933 
6934   // Handle block pointer types.
6935   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6936     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6937                                                      QuestionLoc);
6938 
6939   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6940   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6941     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6942                                                        QuestionLoc);
6943 
6944   // GCC compatibility: soften pointer/integer mismatch.  Note that
6945   // null pointers have been filtered out by this point.
6946   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6947       /*isIntFirstExpr=*/true))
6948     return RHSTy;
6949   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6950       /*isIntFirstExpr=*/false))
6951     return LHSTy;
6952 
6953   // Emit a better diagnostic if one of the expressions is a null pointer
6954   // constant and the other is not a pointer type. In this case, the user most
6955   // likely forgot to take the address of the other expression.
6956   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6957     return QualType();
6958 
6959   // Otherwise, the operands are not compatible.
6960   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6961     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6962     << RHS.get()->getSourceRange();
6963   return QualType();
6964 }
6965 
6966 /// FindCompositeObjCPointerType - Helper method to find composite type of
6967 /// two objective-c pointer types of the two input expressions.
6968 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6969                                             SourceLocation QuestionLoc) {
6970   QualType LHSTy = LHS.get()->getType();
6971   QualType RHSTy = RHS.get()->getType();
6972 
6973   // Handle things like Class and struct objc_class*.  Here we case the result
6974   // to the pseudo-builtin, because that will be implicitly cast back to the
6975   // redefinition type if an attempt is made to access its fields.
6976   if (LHSTy->isObjCClassType() &&
6977       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6978     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6979     return LHSTy;
6980   }
6981   if (RHSTy->isObjCClassType() &&
6982       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6983     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6984     return RHSTy;
6985   }
6986   // And the same for struct objc_object* / id
6987   if (LHSTy->isObjCIdType() &&
6988       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6989     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6990     return LHSTy;
6991   }
6992   if (RHSTy->isObjCIdType() &&
6993       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6994     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6995     return RHSTy;
6996   }
6997   // And the same for struct objc_selector* / SEL
6998   if (Context.isObjCSelType(LHSTy) &&
6999       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7000     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7001     return LHSTy;
7002   }
7003   if (Context.isObjCSelType(RHSTy) &&
7004       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7005     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7006     return RHSTy;
7007   }
7008   // Check constraints for Objective-C object pointers types.
7009   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7010 
7011     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7012       // Two identical object pointer types are always compatible.
7013       return LHSTy;
7014     }
7015     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7016     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7017     QualType compositeType = LHSTy;
7018 
7019     // If both operands are interfaces and either operand can be
7020     // assigned to the other, use that type as the composite
7021     // type. This allows
7022     //   xxx ? (A*) a : (B*) b
7023     // where B is a subclass of A.
7024     //
7025     // Additionally, as for assignment, if either type is 'id'
7026     // allow silent coercion. Finally, if the types are
7027     // incompatible then make sure to use 'id' as the composite
7028     // type so the result is acceptable for sending messages to.
7029 
7030     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7031     // It could return the composite type.
7032     if (!(compositeType =
7033           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7034       // Nothing more to do.
7035     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7036       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7037     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7038       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7039     } else if ((LHSTy->isObjCQualifiedIdType() ||
7040                 RHSTy->isObjCQualifiedIdType()) &&
7041                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7042       // Need to handle "id<xx>" explicitly.
7043       // GCC allows qualified id and any Objective-C type to devolve to
7044       // id. Currently localizing to here until clear this should be
7045       // part of ObjCQualifiedIdTypesAreCompatible.
7046       compositeType = Context.getObjCIdType();
7047     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7048       compositeType = Context.getObjCIdType();
7049     } else {
7050       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7051       << LHSTy << RHSTy
7052       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7053       QualType incompatTy = Context.getObjCIdType();
7054       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7055       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7056       return incompatTy;
7057     }
7058     // The object pointer types are compatible.
7059     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7060     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7061     return compositeType;
7062   }
7063   // Check Objective-C object pointer types and 'void *'
7064   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7065     if (getLangOpts().ObjCAutoRefCount) {
7066       // ARC forbids the implicit conversion of object pointers to 'void *',
7067       // so these types are not compatible.
7068       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7069           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7070       LHS = RHS = true;
7071       return QualType();
7072     }
7073     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7074     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7075     QualType destPointee
7076     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7077     QualType destType = Context.getPointerType(destPointee);
7078     // Add qualifiers if necessary.
7079     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7080     // Promote to void*.
7081     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7082     return destType;
7083   }
7084   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7085     if (getLangOpts().ObjCAutoRefCount) {
7086       // ARC forbids the implicit conversion of object pointers to 'void *',
7087       // so these types are not compatible.
7088       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7089           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7090       LHS = RHS = true;
7091       return QualType();
7092     }
7093     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7094     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7095     QualType destPointee
7096     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7097     QualType destType = Context.getPointerType(destPointee);
7098     // Add qualifiers if necessary.
7099     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7100     // Promote to void*.
7101     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7102     return destType;
7103   }
7104   return QualType();
7105 }
7106 
7107 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7108 /// ParenRange in parentheses.
7109 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7110                                const PartialDiagnostic &Note,
7111                                SourceRange ParenRange) {
7112   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7113   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7114       EndLoc.isValid()) {
7115     Self.Diag(Loc, Note)
7116       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7117       << FixItHint::CreateInsertion(EndLoc, ")");
7118   } else {
7119     // We can't display the parentheses, so just show the bare note.
7120     Self.Diag(Loc, Note) << ParenRange;
7121   }
7122 }
7123 
7124 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7125   return BinaryOperator::isAdditiveOp(Opc) ||
7126          BinaryOperator::isMultiplicativeOp(Opc) ||
7127          BinaryOperator::isShiftOp(Opc);
7128 }
7129 
7130 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7131 /// expression, either using a built-in or overloaded operator,
7132 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7133 /// expression.
7134 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7135                                    Expr **RHSExprs) {
7136   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7137   E = E->IgnoreImpCasts();
7138   E = E->IgnoreConversionOperator();
7139   E = E->IgnoreImpCasts();
7140 
7141   // Built-in binary operator.
7142   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7143     if (IsArithmeticOp(OP->getOpcode())) {
7144       *Opcode = OP->getOpcode();
7145       *RHSExprs = OP->getRHS();
7146       return true;
7147     }
7148   }
7149 
7150   // Overloaded operator.
7151   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7152     if (Call->getNumArgs() != 2)
7153       return false;
7154 
7155     // Make sure this is really a binary operator that is safe to pass into
7156     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7157     OverloadedOperatorKind OO = Call->getOperator();
7158     if (OO < OO_Plus || OO > OO_Arrow ||
7159         OO == OO_PlusPlus || OO == OO_MinusMinus)
7160       return false;
7161 
7162     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7163     if (IsArithmeticOp(OpKind)) {
7164       *Opcode = OpKind;
7165       *RHSExprs = Call->getArg(1);
7166       return true;
7167     }
7168   }
7169 
7170   return false;
7171 }
7172 
7173 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7174 /// or is a logical expression such as (x==y) which has int type, but is
7175 /// commonly interpreted as boolean.
7176 static bool ExprLooksBoolean(Expr *E) {
7177   E = E->IgnoreParenImpCasts();
7178 
7179   if (E->getType()->isBooleanType())
7180     return true;
7181   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7182     return OP->isComparisonOp() || OP->isLogicalOp();
7183   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7184     return OP->getOpcode() == UO_LNot;
7185   if (E->getType()->isPointerType())
7186     return true;
7187 
7188   return false;
7189 }
7190 
7191 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7192 /// and binary operator are mixed in a way that suggests the programmer assumed
7193 /// the conditional operator has higher precedence, for example:
7194 /// "int x = a + someBinaryCondition ? 1 : 2".
7195 static void DiagnoseConditionalPrecedence(Sema &Self,
7196                                           SourceLocation OpLoc,
7197                                           Expr *Condition,
7198                                           Expr *LHSExpr,
7199                                           Expr *RHSExpr) {
7200   BinaryOperatorKind CondOpcode;
7201   Expr *CondRHS;
7202 
7203   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7204     return;
7205   if (!ExprLooksBoolean(CondRHS))
7206     return;
7207 
7208   // The condition is an arithmetic binary expression, with a right-
7209   // hand side that looks boolean, so warn.
7210 
7211   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7212       << Condition->getSourceRange()
7213       << BinaryOperator::getOpcodeStr(CondOpcode);
7214 
7215   SuggestParentheses(Self, OpLoc,
7216     Self.PDiag(diag::note_precedence_silence)
7217       << BinaryOperator::getOpcodeStr(CondOpcode),
7218     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7219 
7220   SuggestParentheses(Self, OpLoc,
7221     Self.PDiag(diag::note_precedence_conditional_first),
7222     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7223 }
7224 
7225 /// Compute the nullability of a conditional expression.
7226 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7227                                               QualType LHSTy, QualType RHSTy,
7228                                               ASTContext &Ctx) {
7229   if (!ResTy->isAnyPointerType())
7230     return ResTy;
7231 
7232   auto GetNullability = [&Ctx](QualType Ty) {
7233     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7234     if (Kind)
7235       return *Kind;
7236     return NullabilityKind::Unspecified;
7237   };
7238 
7239   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7240   NullabilityKind MergedKind;
7241 
7242   // Compute nullability of a binary conditional expression.
7243   if (IsBin) {
7244     if (LHSKind == NullabilityKind::NonNull)
7245       MergedKind = NullabilityKind::NonNull;
7246     else
7247       MergedKind = RHSKind;
7248   // Compute nullability of a normal conditional expression.
7249   } else {
7250     if (LHSKind == NullabilityKind::Nullable ||
7251         RHSKind == NullabilityKind::Nullable)
7252       MergedKind = NullabilityKind::Nullable;
7253     else if (LHSKind == NullabilityKind::NonNull)
7254       MergedKind = RHSKind;
7255     else if (RHSKind == NullabilityKind::NonNull)
7256       MergedKind = LHSKind;
7257     else
7258       MergedKind = NullabilityKind::Unspecified;
7259   }
7260 
7261   // Return if ResTy already has the correct nullability.
7262   if (GetNullability(ResTy) == MergedKind)
7263     return ResTy;
7264 
7265   // Strip all nullability from ResTy.
7266   while (ResTy->getNullability(Ctx))
7267     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7268 
7269   // Create a new AttributedType with the new nullability kind.
7270   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7271   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7272 }
7273 
7274 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7275 /// in the case of a the GNU conditional expr extension.
7276 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7277                                     SourceLocation ColonLoc,
7278                                     Expr *CondExpr, Expr *LHSExpr,
7279                                     Expr *RHSExpr) {
7280   if (!getLangOpts().CPlusPlus) {
7281     // C cannot handle TypoExpr nodes in the condition because it
7282     // doesn't handle dependent types properly, so make sure any TypoExprs have
7283     // been dealt with before checking the operands.
7284     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7285     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7286     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7287 
7288     if (!CondResult.isUsable())
7289       return ExprError();
7290 
7291     if (LHSExpr) {
7292       if (!LHSResult.isUsable())
7293         return ExprError();
7294     }
7295 
7296     if (!RHSResult.isUsable())
7297       return ExprError();
7298 
7299     CondExpr = CondResult.get();
7300     LHSExpr = LHSResult.get();
7301     RHSExpr = RHSResult.get();
7302   }
7303 
7304   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7305   // was the condition.
7306   OpaqueValueExpr *opaqueValue = nullptr;
7307   Expr *commonExpr = nullptr;
7308   if (!LHSExpr) {
7309     commonExpr = CondExpr;
7310     // Lower out placeholder types first.  This is important so that we don't
7311     // try to capture a placeholder. This happens in few cases in C++; such
7312     // as Objective-C++'s dictionary subscripting syntax.
7313     if (commonExpr->hasPlaceholderType()) {
7314       ExprResult result = CheckPlaceholderExpr(commonExpr);
7315       if (!result.isUsable()) return ExprError();
7316       commonExpr = result.get();
7317     }
7318     // We usually want to apply unary conversions *before* saving, except
7319     // in the special case of a C++ l-value conditional.
7320     if (!(getLangOpts().CPlusPlus
7321           && !commonExpr->isTypeDependent()
7322           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7323           && commonExpr->isGLValue()
7324           && commonExpr->isOrdinaryOrBitFieldObject()
7325           && RHSExpr->isOrdinaryOrBitFieldObject()
7326           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7327       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7328       if (commonRes.isInvalid())
7329         return ExprError();
7330       commonExpr = commonRes.get();
7331     }
7332 
7333     // If the common expression is a class or array prvalue, materialize it
7334     // so that we can safely refer to it multiple times.
7335     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7336                                    commonExpr->getType()->isArrayType())) {
7337       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7338       if (MatExpr.isInvalid())
7339         return ExprError();
7340       commonExpr = MatExpr.get();
7341     }
7342 
7343     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7344                                                 commonExpr->getType(),
7345                                                 commonExpr->getValueKind(),
7346                                                 commonExpr->getObjectKind(),
7347                                                 commonExpr);
7348     LHSExpr = CondExpr = opaqueValue;
7349   }
7350 
7351   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7352   ExprValueKind VK = VK_RValue;
7353   ExprObjectKind OK = OK_Ordinary;
7354   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7355   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7356                                              VK, OK, QuestionLoc);
7357   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7358       RHS.isInvalid())
7359     return ExprError();
7360 
7361   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7362                                 RHS.get());
7363 
7364   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7365 
7366   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7367                                          Context);
7368 
7369   if (!commonExpr)
7370     return new (Context)
7371         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7372                             RHS.get(), result, VK, OK);
7373 
7374   return new (Context) BinaryConditionalOperator(
7375       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7376       ColonLoc, result, VK, OK);
7377 }
7378 
7379 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7380 // being closely modeled after the C99 spec:-). The odd characteristic of this
7381 // routine is it effectively iqnores the qualifiers on the top level pointee.
7382 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7383 // FIXME: add a couple examples in this comment.
7384 static Sema::AssignConvertType
7385 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7386   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7387   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7388 
7389   // get the "pointed to" type (ignoring qualifiers at the top level)
7390   const Type *lhptee, *rhptee;
7391   Qualifiers lhq, rhq;
7392   std::tie(lhptee, lhq) =
7393       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7394   std::tie(rhptee, rhq) =
7395       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7396 
7397   Sema::AssignConvertType ConvTy = Sema::Compatible;
7398 
7399   // C99 6.5.16.1p1: This following citation is common to constraints
7400   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7401   // qualifiers of the type *pointed to* by the right;
7402 
7403   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7404   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7405       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7406     // Ignore lifetime for further calculation.
7407     lhq.removeObjCLifetime();
7408     rhq.removeObjCLifetime();
7409   }
7410 
7411   if (!lhq.compatiblyIncludes(rhq)) {
7412     // Treat address-space mismatches as fatal.  TODO: address subspaces
7413     if (!lhq.isAddressSpaceSupersetOf(rhq))
7414       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7415 
7416     // It's okay to add or remove GC or lifetime qualifiers when converting to
7417     // and from void*.
7418     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7419                         .compatiblyIncludes(
7420                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7421              && (lhptee->isVoidType() || rhptee->isVoidType()))
7422       ; // keep old
7423 
7424     // Treat lifetime mismatches as fatal.
7425     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7426       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7427 
7428     // For GCC/MS compatibility, other qualifier mismatches are treated
7429     // as still compatible in C.
7430     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7431   }
7432 
7433   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7434   // incomplete type and the other is a pointer to a qualified or unqualified
7435   // version of void...
7436   if (lhptee->isVoidType()) {
7437     if (rhptee->isIncompleteOrObjectType())
7438       return ConvTy;
7439 
7440     // As an extension, we allow cast to/from void* to function pointer.
7441     assert(rhptee->isFunctionType());
7442     return Sema::FunctionVoidPointer;
7443   }
7444 
7445   if (rhptee->isVoidType()) {
7446     if (lhptee->isIncompleteOrObjectType())
7447       return ConvTy;
7448 
7449     // As an extension, we allow cast to/from void* to function pointer.
7450     assert(lhptee->isFunctionType());
7451     return Sema::FunctionVoidPointer;
7452   }
7453 
7454   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7455   // unqualified versions of compatible types, ...
7456   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7457   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7458     // Check if the pointee types are compatible ignoring the sign.
7459     // We explicitly check for char so that we catch "char" vs
7460     // "unsigned char" on systems where "char" is unsigned.
7461     if (lhptee->isCharType())
7462       ltrans = S.Context.UnsignedCharTy;
7463     else if (lhptee->hasSignedIntegerRepresentation())
7464       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7465 
7466     if (rhptee->isCharType())
7467       rtrans = S.Context.UnsignedCharTy;
7468     else if (rhptee->hasSignedIntegerRepresentation())
7469       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7470 
7471     if (ltrans == rtrans) {
7472       // Types are compatible ignoring the sign. Qualifier incompatibility
7473       // takes priority over sign incompatibility because the sign
7474       // warning can be disabled.
7475       if (ConvTy != Sema::Compatible)
7476         return ConvTy;
7477 
7478       return Sema::IncompatiblePointerSign;
7479     }
7480 
7481     // If we are a multi-level pointer, it's possible that our issue is simply
7482     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7483     // the eventual target type is the same and the pointers have the same
7484     // level of indirection, this must be the issue.
7485     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7486       do {
7487         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7488         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7489       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7490 
7491       if (lhptee == rhptee)
7492         return Sema::IncompatibleNestedPointerQualifiers;
7493     }
7494 
7495     // General pointer incompatibility takes priority over qualifiers.
7496     return Sema::IncompatiblePointer;
7497   }
7498   if (!S.getLangOpts().CPlusPlus &&
7499       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7500     return Sema::IncompatiblePointer;
7501   return ConvTy;
7502 }
7503 
7504 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7505 /// block pointer types are compatible or whether a block and normal pointer
7506 /// are compatible. It is more restrict than comparing two function pointer
7507 // types.
7508 static Sema::AssignConvertType
7509 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7510                                     QualType RHSType) {
7511   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7512   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7513 
7514   QualType lhptee, rhptee;
7515 
7516   // get the "pointed to" type (ignoring qualifiers at the top level)
7517   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7518   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7519 
7520   // In C++, the types have to match exactly.
7521   if (S.getLangOpts().CPlusPlus)
7522     return Sema::IncompatibleBlockPointer;
7523 
7524   Sema::AssignConvertType ConvTy = Sema::Compatible;
7525 
7526   // For blocks we enforce that qualifiers are identical.
7527   Qualifiers LQuals = lhptee.getLocalQualifiers();
7528   Qualifiers RQuals = rhptee.getLocalQualifiers();
7529   if (S.getLangOpts().OpenCL) {
7530     LQuals.removeAddressSpace();
7531     RQuals.removeAddressSpace();
7532   }
7533   if (LQuals != RQuals)
7534     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7535 
7536   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7537   // assignment.
7538   // The current behavior is similar to C++ lambdas. A block might be
7539   // assigned to a variable iff its return type and parameters are compatible
7540   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7541   // an assignment. Presumably it should behave in way that a function pointer
7542   // assignment does in C, so for each parameter and return type:
7543   //  * CVR and address space of LHS should be a superset of CVR and address
7544   //  space of RHS.
7545   //  * unqualified types should be compatible.
7546   if (S.getLangOpts().OpenCL) {
7547     if (!S.Context.typesAreBlockPointerCompatible(
7548             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7549             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7550       return Sema::IncompatibleBlockPointer;
7551   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7552     return Sema::IncompatibleBlockPointer;
7553 
7554   return ConvTy;
7555 }
7556 
7557 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7558 /// for assignment compatibility.
7559 static Sema::AssignConvertType
7560 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7561                                    QualType RHSType) {
7562   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7563   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7564 
7565   if (LHSType->isObjCBuiltinType()) {
7566     // Class is not compatible with ObjC object pointers.
7567     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7568         !RHSType->isObjCQualifiedClassType())
7569       return Sema::IncompatiblePointer;
7570     return Sema::Compatible;
7571   }
7572   if (RHSType->isObjCBuiltinType()) {
7573     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7574         !LHSType->isObjCQualifiedClassType())
7575       return Sema::IncompatiblePointer;
7576     return Sema::Compatible;
7577   }
7578   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7579   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7580 
7581   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7582       // make an exception for id<P>
7583       !LHSType->isObjCQualifiedIdType())
7584     return Sema::CompatiblePointerDiscardsQualifiers;
7585 
7586   if (S.Context.typesAreCompatible(LHSType, RHSType))
7587     return Sema::Compatible;
7588   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7589     return Sema::IncompatibleObjCQualifiedId;
7590   return Sema::IncompatiblePointer;
7591 }
7592 
7593 Sema::AssignConvertType
7594 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7595                                  QualType LHSType, QualType RHSType) {
7596   // Fake up an opaque expression.  We don't actually care about what
7597   // cast operations are required, so if CheckAssignmentConstraints
7598   // adds casts to this they'll be wasted, but fortunately that doesn't
7599   // usually happen on valid code.
7600   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7601   ExprResult RHSPtr = &RHSExpr;
7602   CastKind K;
7603 
7604   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7605 }
7606 
7607 /// This helper function returns true if QT is a vector type that has element
7608 /// type ElementType.
7609 static bool isVector(QualType QT, QualType ElementType) {
7610   if (const VectorType *VT = QT->getAs<VectorType>())
7611     return VT->getElementType() == ElementType;
7612   return false;
7613 }
7614 
7615 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7616 /// has code to accommodate several GCC extensions when type checking
7617 /// pointers. Here are some objectionable examples that GCC considers warnings:
7618 ///
7619 ///  int a, *pint;
7620 ///  short *pshort;
7621 ///  struct foo *pfoo;
7622 ///
7623 ///  pint = pshort; // warning: assignment from incompatible pointer type
7624 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7625 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7626 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7627 ///
7628 /// As a result, the code for dealing with pointers is more complex than the
7629 /// C99 spec dictates.
7630 ///
7631 /// Sets 'Kind' for any result kind except Incompatible.
7632 Sema::AssignConvertType
7633 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7634                                  CastKind &Kind, bool ConvertRHS) {
7635   QualType RHSType = RHS.get()->getType();
7636   QualType OrigLHSType = LHSType;
7637 
7638   // Get canonical types.  We're not formatting these types, just comparing
7639   // them.
7640   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7641   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7642 
7643   // Common case: no conversion required.
7644   if (LHSType == RHSType) {
7645     Kind = CK_NoOp;
7646     return Compatible;
7647   }
7648 
7649   // If we have an atomic type, try a non-atomic assignment, then just add an
7650   // atomic qualification step.
7651   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7652     Sema::AssignConvertType result =
7653       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7654     if (result != Compatible)
7655       return result;
7656     if (Kind != CK_NoOp && ConvertRHS)
7657       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7658     Kind = CK_NonAtomicToAtomic;
7659     return Compatible;
7660   }
7661 
7662   // If the left-hand side is a reference type, then we are in a
7663   // (rare!) case where we've allowed the use of references in C,
7664   // e.g., as a parameter type in a built-in function. In this case,
7665   // just make sure that the type referenced is compatible with the
7666   // right-hand side type. The caller is responsible for adjusting
7667   // LHSType so that the resulting expression does not have reference
7668   // type.
7669   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7670     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7671       Kind = CK_LValueBitCast;
7672       return Compatible;
7673     }
7674     return Incompatible;
7675   }
7676 
7677   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7678   // to the same ExtVector type.
7679   if (LHSType->isExtVectorType()) {
7680     if (RHSType->isExtVectorType())
7681       return Incompatible;
7682     if (RHSType->isArithmeticType()) {
7683       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7684       if (ConvertRHS)
7685         RHS = prepareVectorSplat(LHSType, RHS.get());
7686       Kind = CK_VectorSplat;
7687       return Compatible;
7688     }
7689   }
7690 
7691   // Conversions to or from vector type.
7692   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7693     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7694       // Allow assignments of an AltiVec vector type to an equivalent GCC
7695       // vector type and vice versa
7696       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7697         Kind = CK_BitCast;
7698         return Compatible;
7699       }
7700 
7701       // If we are allowing lax vector conversions, and LHS and RHS are both
7702       // vectors, the total size only needs to be the same. This is a bitcast;
7703       // no bits are changed but the result type is different.
7704       if (isLaxVectorConversion(RHSType, LHSType)) {
7705         Kind = CK_BitCast;
7706         return IncompatibleVectors;
7707       }
7708     }
7709 
7710     // When the RHS comes from another lax conversion (e.g. binops between
7711     // scalars and vectors) the result is canonicalized as a vector. When the
7712     // LHS is also a vector, the lax is allowed by the condition above. Handle
7713     // the case where LHS is a scalar.
7714     if (LHSType->isScalarType()) {
7715       const VectorType *VecType = RHSType->getAs<VectorType>();
7716       if (VecType && VecType->getNumElements() == 1 &&
7717           isLaxVectorConversion(RHSType, LHSType)) {
7718         ExprResult *VecExpr = &RHS;
7719         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7720         Kind = CK_BitCast;
7721         return Compatible;
7722       }
7723     }
7724 
7725     return Incompatible;
7726   }
7727 
7728   // Diagnose attempts to convert between __float128 and long double where
7729   // such conversions currently can't be handled.
7730   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7731     return Incompatible;
7732 
7733   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7734   // discards the imaginary part.
7735   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7736       !LHSType->getAs<ComplexType>())
7737     return Incompatible;
7738 
7739   // Arithmetic conversions.
7740   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7741       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7742     if (ConvertRHS)
7743       Kind = PrepareScalarCast(RHS, LHSType);
7744     return Compatible;
7745   }
7746 
7747   // Conversions to normal pointers.
7748   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7749     // U* -> T*
7750     if (isa<PointerType>(RHSType)) {
7751       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7752       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7753       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7754       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7755     }
7756 
7757     // int -> T*
7758     if (RHSType->isIntegerType()) {
7759       Kind = CK_IntegralToPointer; // FIXME: null?
7760       return IntToPointer;
7761     }
7762 
7763     // C pointers are not compatible with ObjC object pointers,
7764     // with two exceptions:
7765     if (isa<ObjCObjectPointerType>(RHSType)) {
7766       //  - conversions to void*
7767       if (LHSPointer->getPointeeType()->isVoidType()) {
7768         Kind = CK_BitCast;
7769         return Compatible;
7770       }
7771 
7772       //  - conversions from 'Class' to the redefinition type
7773       if (RHSType->isObjCClassType() &&
7774           Context.hasSameType(LHSType,
7775                               Context.getObjCClassRedefinitionType())) {
7776         Kind = CK_BitCast;
7777         return Compatible;
7778       }
7779 
7780       Kind = CK_BitCast;
7781       return IncompatiblePointer;
7782     }
7783 
7784     // U^ -> void*
7785     if (RHSType->getAs<BlockPointerType>()) {
7786       if (LHSPointer->getPointeeType()->isVoidType()) {
7787         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7788         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7789                                 ->getPointeeType()
7790                                 .getAddressSpace();
7791         Kind =
7792             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7793         return Compatible;
7794       }
7795     }
7796 
7797     return Incompatible;
7798   }
7799 
7800   // Conversions to block pointers.
7801   if (isa<BlockPointerType>(LHSType)) {
7802     // U^ -> T^
7803     if (RHSType->isBlockPointerType()) {
7804       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7805                               ->getPointeeType()
7806                               .getAddressSpace();
7807       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7808                               ->getPointeeType()
7809                               .getAddressSpace();
7810       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7811       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7812     }
7813 
7814     // int or null -> T^
7815     if (RHSType->isIntegerType()) {
7816       Kind = CK_IntegralToPointer; // FIXME: null
7817       return IntToBlockPointer;
7818     }
7819 
7820     // id -> T^
7821     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7822       Kind = CK_AnyPointerToBlockPointerCast;
7823       return Compatible;
7824     }
7825 
7826     // void* -> T^
7827     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7828       if (RHSPT->getPointeeType()->isVoidType()) {
7829         Kind = CK_AnyPointerToBlockPointerCast;
7830         return Compatible;
7831       }
7832 
7833     return Incompatible;
7834   }
7835 
7836   // Conversions to Objective-C pointers.
7837   if (isa<ObjCObjectPointerType>(LHSType)) {
7838     // A* -> B*
7839     if (RHSType->isObjCObjectPointerType()) {
7840       Kind = CK_BitCast;
7841       Sema::AssignConvertType result =
7842         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7843       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7844           result == Compatible &&
7845           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7846         result = IncompatibleObjCWeakRef;
7847       return result;
7848     }
7849 
7850     // int or null -> A*
7851     if (RHSType->isIntegerType()) {
7852       Kind = CK_IntegralToPointer; // FIXME: null
7853       return IntToPointer;
7854     }
7855 
7856     // In general, C pointers are not compatible with ObjC object pointers,
7857     // with two exceptions:
7858     if (isa<PointerType>(RHSType)) {
7859       Kind = CK_CPointerToObjCPointerCast;
7860 
7861       //  - conversions from 'void*'
7862       if (RHSType->isVoidPointerType()) {
7863         return Compatible;
7864       }
7865 
7866       //  - conversions to 'Class' from its redefinition type
7867       if (LHSType->isObjCClassType() &&
7868           Context.hasSameType(RHSType,
7869                               Context.getObjCClassRedefinitionType())) {
7870         return Compatible;
7871       }
7872 
7873       return IncompatiblePointer;
7874     }
7875 
7876     // Only under strict condition T^ is compatible with an Objective-C pointer.
7877     if (RHSType->isBlockPointerType() &&
7878         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7879       if (ConvertRHS)
7880         maybeExtendBlockObject(RHS);
7881       Kind = CK_BlockPointerToObjCPointerCast;
7882       return Compatible;
7883     }
7884 
7885     return Incompatible;
7886   }
7887 
7888   // Conversions from pointers that are not covered by the above.
7889   if (isa<PointerType>(RHSType)) {
7890     // T* -> _Bool
7891     if (LHSType == Context.BoolTy) {
7892       Kind = CK_PointerToBoolean;
7893       return Compatible;
7894     }
7895 
7896     // T* -> int
7897     if (LHSType->isIntegerType()) {
7898       Kind = CK_PointerToIntegral;
7899       return PointerToInt;
7900     }
7901 
7902     return Incompatible;
7903   }
7904 
7905   // Conversions from Objective-C pointers that are not covered by the above.
7906   if (isa<ObjCObjectPointerType>(RHSType)) {
7907     // T* -> _Bool
7908     if (LHSType == Context.BoolTy) {
7909       Kind = CK_PointerToBoolean;
7910       return Compatible;
7911     }
7912 
7913     // T* -> int
7914     if (LHSType->isIntegerType()) {
7915       Kind = CK_PointerToIntegral;
7916       return PointerToInt;
7917     }
7918 
7919     return Incompatible;
7920   }
7921 
7922   // struct A -> struct B
7923   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7924     if (Context.typesAreCompatible(LHSType, RHSType)) {
7925       Kind = CK_NoOp;
7926       return Compatible;
7927     }
7928   }
7929 
7930   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7931     Kind = CK_IntToOCLSampler;
7932     return Compatible;
7933   }
7934 
7935   return Incompatible;
7936 }
7937 
7938 /// Constructs a transparent union from an expression that is
7939 /// used to initialize the transparent union.
7940 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7941                                       ExprResult &EResult, QualType UnionType,
7942                                       FieldDecl *Field) {
7943   // Build an initializer list that designates the appropriate member
7944   // of the transparent union.
7945   Expr *E = EResult.get();
7946   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7947                                                    E, SourceLocation());
7948   Initializer->setType(UnionType);
7949   Initializer->setInitializedFieldInUnion(Field);
7950 
7951   // Build a compound literal constructing a value of the transparent
7952   // union type from this initializer list.
7953   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7954   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7955                                         VK_RValue, Initializer, false);
7956 }
7957 
7958 Sema::AssignConvertType
7959 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7960                                                ExprResult &RHS) {
7961   QualType RHSType = RHS.get()->getType();
7962 
7963   // If the ArgType is a Union type, we want to handle a potential
7964   // transparent_union GCC extension.
7965   const RecordType *UT = ArgType->getAsUnionType();
7966   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7967     return Incompatible;
7968 
7969   // The field to initialize within the transparent union.
7970   RecordDecl *UD = UT->getDecl();
7971   FieldDecl *InitField = nullptr;
7972   // It's compatible if the expression matches any of the fields.
7973   for (auto *it : UD->fields()) {
7974     if (it->getType()->isPointerType()) {
7975       // If the transparent union contains a pointer type, we allow:
7976       // 1) void pointer
7977       // 2) null pointer constant
7978       if (RHSType->isPointerType())
7979         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7980           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7981           InitField = it;
7982           break;
7983         }
7984 
7985       if (RHS.get()->isNullPointerConstant(Context,
7986                                            Expr::NPC_ValueDependentIsNull)) {
7987         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7988                                 CK_NullToPointer);
7989         InitField = it;
7990         break;
7991       }
7992     }
7993 
7994     CastKind Kind;
7995     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7996           == Compatible) {
7997       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7998       InitField = it;
7999       break;
8000     }
8001   }
8002 
8003   if (!InitField)
8004     return Incompatible;
8005 
8006   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8007   return Compatible;
8008 }
8009 
8010 Sema::AssignConvertType
8011 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8012                                        bool Diagnose,
8013                                        bool DiagnoseCFAudited,
8014                                        bool ConvertRHS) {
8015   // We need to be able to tell the caller whether we diagnosed a problem, if
8016   // they ask us to issue diagnostics.
8017   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8018 
8019   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8020   // we can't avoid *all* modifications at the moment, so we need some somewhere
8021   // to put the updated value.
8022   ExprResult LocalRHS = CallerRHS;
8023   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8024 
8025   if (getLangOpts().CPlusPlus) {
8026     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8027       // C++ 5.17p3: If the left operand is not of class type, the
8028       // expression is implicitly converted (C++ 4) to the
8029       // cv-unqualified type of the left operand.
8030       QualType RHSType = RHS.get()->getType();
8031       if (Diagnose) {
8032         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8033                                         AA_Assigning);
8034       } else {
8035         ImplicitConversionSequence ICS =
8036             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8037                                   /*SuppressUserConversions=*/false,
8038                                   /*AllowExplicit=*/false,
8039                                   /*InOverloadResolution=*/false,
8040                                   /*CStyle=*/false,
8041                                   /*AllowObjCWritebackConversion=*/false);
8042         if (ICS.isFailure())
8043           return Incompatible;
8044         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8045                                         ICS, AA_Assigning);
8046       }
8047       if (RHS.isInvalid())
8048         return Incompatible;
8049       Sema::AssignConvertType result = Compatible;
8050       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8051           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8052         result = IncompatibleObjCWeakRef;
8053       return result;
8054     }
8055 
8056     // FIXME: Currently, we fall through and treat C++ classes like C
8057     // structures.
8058     // FIXME: We also fall through for atomics; not sure what should
8059     // happen there, though.
8060   } else if (RHS.get()->getType() == Context.OverloadTy) {
8061     // As a set of extensions to C, we support overloading on functions. These
8062     // functions need to be resolved here.
8063     DeclAccessPair DAP;
8064     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8065             RHS.get(), LHSType, /*Complain=*/false, DAP))
8066       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8067     else
8068       return Incompatible;
8069   }
8070 
8071   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8072   // a null pointer constant.
8073   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8074        LHSType->isBlockPointerType()) &&
8075       RHS.get()->isNullPointerConstant(Context,
8076                                        Expr::NPC_ValueDependentIsNull)) {
8077     if (Diagnose || ConvertRHS) {
8078       CastKind Kind;
8079       CXXCastPath Path;
8080       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8081                              /*IgnoreBaseAccess=*/false, Diagnose);
8082       if (ConvertRHS)
8083         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8084     }
8085     return Compatible;
8086   }
8087 
8088   // This check seems unnatural, however it is necessary to ensure the proper
8089   // conversion of functions/arrays. If the conversion were done for all
8090   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8091   // expressions that suppress this implicit conversion (&, sizeof).
8092   //
8093   // Suppress this for references: C++ 8.5.3p5.
8094   if (!LHSType->isReferenceType()) {
8095     // FIXME: We potentially allocate here even if ConvertRHS is false.
8096     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8097     if (RHS.isInvalid())
8098       return Incompatible;
8099   }
8100 
8101   Expr *PRE = RHS.get()->IgnoreParenCasts();
8102   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8103     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8104     if (PDecl && !PDecl->hasDefinition()) {
8105       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8106       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8107     }
8108   }
8109 
8110   CastKind Kind;
8111   Sema::AssignConvertType result =
8112     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8113 
8114   // C99 6.5.16.1p2: The value of the right operand is converted to the
8115   // type of the assignment expression.
8116   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8117   // so that we can use references in built-in functions even in C.
8118   // The getNonReferenceType() call makes sure that the resulting expression
8119   // does not have reference type.
8120   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8121     QualType Ty = LHSType.getNonLValueExprType(Context);
8122     Expr *E = RHS.get();
8123 
8124     // Check for various Objective-C errors. If we are not reporting
8125     // diagnostics and just checking for errors, e.g., during overload
8126     // resolution, return Incompatible to indicate the failure.
8127     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8128         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8129                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8130       if (!Diagnose)
8131         return Incompatible;
8132     }
8133     if (getLangOpts().ObjC1 &&
8134         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8135                                            E->getType(), E, Diagnose) ||
8136          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8137       if (!Diagnose)
8138         return Incompatible;
8139       // Replace the expression with a corrected version and continue so we
8140       // can find further errors.
8141       RHS = E;
8142       return Compatible;
8143     }
8144 
8145     if (ConvertRHS)
8146       RHS = ImpCastExprToType(E, Ty, Kind);
8147   }
8148   return result;
8149 }
8150 
8151 namespace {
8152 /// The original operand to an operator, prior to the application of the usual
8153 /// arithmetic conversions and converting the arguments of a builtin operator
8154 /// candidate.
8155 struct OriginalOperand {
8156   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8157     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8158       Op = MTE->GetTemporaryExpr();
8159     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8160       Op = BTE->getSubExpr();
8161     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8162       Orig = ICE->getSubExprAsWritten();
8163       Conversion = ICE->getConversionFunction();
8164     }
8165   }
8166 
8167   QualType getType() const { return Orig->getType(); }
8168 
8169   Expr *Orig;
8170   NamedDecl *Conversion;
8171 };
8172 }
8173 
8174 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8175                                ExprResult &RHS) {
8176   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8177 
8178   Diag(Loc, diag::err_typecheck_invalid_operands)
8179     << OrigLHS.getType() << OrigRHS.getType()
8180     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8181 
8182   // If a user-defined conversion was applied to either of the operands prior
8183   // to applying the built-in operator rules, tell the user about it.
8184   if (OrigLHS.Conversion) {
8185     Diag(OrigLHS.Conversion->getLocation(),
8186          diag::note_typecheck_invalid_operands_converted)
8187       << 0 << LHS.get()->getType();
8188   }
8189   if (OrigRHS.Conversion) {
8190     Diag(OrigRHS.Conversion->getLocation(),
8191          diag::note_typecheck_invalid_operands_converted)
8192       << 1 << RHS.get()->getType();
8193   }
8194 
8195   return QualType();
8196 }
8197 
8198 // Diagnose cases where a scalar was implicitly converted to a vector and
8199 // diagnose the underlying types. Otherwise, diagnose the error
8200 // as invalid vector logical operands for non-C++ cases.
8201 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8202                                             ExprResult &RHS) {
8203   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8204   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8205 
8206   bool LHSNatVec = LHSType->isVectorType();
8207   bool RHSNatVec = RHSType->isVectorType();
8208 
8209   if (!(LHSNatVec && RHSNatVec)) {
8210     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8211     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8212     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8213         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8214         << Vector->getSourceRange();
8215     return QualType();
8216   }
8217 
8218   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8219       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8220       << RHS.get()->getSourceRange();
8221 
8222   return QualType();
8223 }
8224 
8225 /// Try to convert a value of non-vector type to a vector type by converting
8226 /// the type to the element type of the vector and then performing a splat.
8227 /// If the language is OpenCL, we only use conversions that promote scalar
8228 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8229 /// for float->int.
8230 ///
8231 /// OpenCL V2.0 6.2.6.p2:
8232 /// An error shall occur if any scalar operand type has greater rank
8233 /// than the type of the vector element.
8234 ///
8235 /// \param scalar - if non-null, actually perform the conversions
8236 /// \return true if the operation fails (but without diagnosing the failure)
8237 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8238                                      QualType scalarTy,
8239                                      QualType vectorEltTy,
8240                                      QualType vectorTy,
8241                                      unsigned &DiagID) {
8242   // The conversion to apply to the scalar before splatting it,
8243   // if necessary.
8244   CastKind scalarCast = CK_NoOp;
8245 
8246   if (vectorEltTy->isIntegralType(S.Context)) {
8247     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8248         (scalarTy->isIntegerType() &&
8249          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8250       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8251       return true;
8252     }
8253     if (!scalarTy->isIntegralType(S.Context))
8254       return true;
8255     scalarCast = CK_IntegralCast;
8256   } else if (vectorEltTy->isRealFloatingType()) {
8257     if (scalarTy->isRealFloatingType()) {
8258       if (S.getLangOpts().OpenCL &&
8259           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8260         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8261         return true;
8262       }
8263       scalarCast = CK_FloatingCast;
8264     }
8265     else if (scalarTy->isIntegralType(S.Context))
8266       scalarCast = CK_IntegralToFloating;
8267     else
8268       return true;
8269   } else {
8270     return true;
8271   }
8272 
8273   // Adjust scalar if desired.
8274   if (scalar) {
8275     if (scalarCast != CK_NoOp)
8276       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8277     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8278   }
8279   return false;
8280 }
8281 
8282 /// Convert vector E to a vector with the same number of elements but different
8283 /// element type.
8284 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8285   const auto *VecTy = E->getType()->getAs<VectorType>();
8286   assert(VecTy && "Expression E must be a vector");
8287   QualType NewVecTy = S.Context.getVectorType(ElementType,
8288                                               VecTy->getNumElements(),
8289                                               VecTy->getVectorKind());
8290 
8291   // Look through the implicit cast. Return the subexpression if its type is
8292   // NewVecTy.
8293   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8294     if (ICE->getSubExpr()->getType() == NewVecTy)
8295       return ICE->getSubExpr();
8296 
8297   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8298   return S.ImpCastExprToType(E, NewVecTy, Cast);
8299 }
8300 
8301 /// Test if a (constant) integer Int can be casted to another integer type
8302 /// IntTy without losing precision.
8303 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8304                                       QualType OtherIntTy) {
8305   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8306 
8307   // Reject cases where the value of the Int is unknown as that would
8308   // possibly cause truncation, but accept cases where the scalar can be
8309   // demoted without loss of precision.
8310   llvm::APSInt Result;
8311   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8312   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8313   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8314   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8315 
8316   if (CstInt) {
8317     // If the scalar is constant and is of a higher order and has more active
8318     // bits that the vector element type, reject it.
8319     unsigned NumBits = IntSigned
8320                            ? (Result.isNegative() ? Result.getMinSignedBits()
8321                                                   : Result.getActiveBits())
8322                            : Result.getActiveBits();
8323     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8324       return true;
8325 
8326     // If the signedness of the scalar type and the vector element type
8327     // differs and the number of bits is greater than that of the vector
8328     // element reject it.
8329     return (IntSigned != OtherIntSigned &&
8330             NumBits > S.Context.getIntWidth(OtherIntTy));
8331   }
8332 
8333   // Reject cases where the value of the scalar is not constant and it's
8334   // order is greater than that of the vector element type.
8335   return (Order < 0);
8336 }
8337 
8338 /// Test if a (constant) integer Int can be casted to floating point type
8339 /// FloatTy without losing precision.
8340 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8341                                      QualType FloatTy) {
8342   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8343 
8344   // Determine if the integer constant can be expressed as a floating point
8345   // number of the appropriate type.
8346   llvm::APSInt Result;
8347   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8348   uint64_t Bits = 0;
8349   if (CstInt) {
8350     // Reject constants that would be truncated if they were converted to
8351     // the floating point type. Test by simple to/from conversion.
8352     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8353     //        could be avoided if there was a convertFromAPInt method
8354     //        which could signal back if implicit truncation occurred.
8355     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8356     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8357                            llvm::APFloat::rmTowardZero);
8358     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8359                              !IntTy->hasSignedIntegerRepresentation());
8360     bool Ignored = false;
8361     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8362                            &Ignored);
8363     if (Result != ConvertBack)
8364       return true;
8365   } else {
8366     // Reject types that cannot be fully encoded into the mantissa of
8367     // the float.
8368     Bits = S.Context.getTypeSize(IntTy);
8369     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8370         S.Context.getFloatTypeSemantics(FloatTy));
8371     if (Bits > FloatPrec)
8372       return true;
8373   }
8374 
8375   return false;
8376 }
8377 
8378 /// Attempt to convert and splat Scalar into a vector whose types matches
8379 /// Vector following GCC conversion rules. The rule is that implicit
8380 /// conversion can occur when Scalar can be casted to match Vector's element
8381 /// type without causing truncation of Scalar.
8382 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8383                                         ExprResult *Vector) {
8384   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8385   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8386   const VectorType *VT = VectorTy->getAs<VectorType>();
8387 
8388   assert(!isa<ExtVectorType>(VT) &&
8389          "ExtVectorTypes should not be handled here!");
8390 
8391   QualType VectorEltTy = VT->getElementType();
8392 
8393   // Reject cases where the vector element type or the scalar element type are
8394   // not integral or floating point types.
8395   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8396     return true;
8397 
8398   // The conversion to apply to the scalar before splatting it,
8399   // if necessary.
8400   CastKind ScalarCast = CK_NoOp;
8401 
8402   // Accept cases where the vector elements are integers and the scalar is
8403   // an integer.
8404   // FIXME: Notionally if the scalar was a floating point value with a precise
8405   //        integral representation, we could cast it to an appropriate integer
8406   //        type and then perform the rest of the checks here. GCC will perform
8407   //        this conversion in some cases as determined by the input language.
8408   //        We should accept it on a language independent basis.
8409   if (VectorEltTy->isIntegralType(S.Context) &&
8410       ScalarTy->isIntegralType(S.Context) &&
8411       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8412 
8413     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8414       return true;
8415 
8416     ScalarCast = CK_IntegralCast;
8417   } else if (VectorEltTy->isRealFloatingType()) {
8418     if (ScalarTy->isRealFloatingType()) {
8419 
8420       // Reject cases where the scalar type is not a constant and has a higher
8421       // Order than the vector element type.
8422       llvm::APFloat Result(0.0);
8423       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8424       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8425       if (!CstScalar && Order < 0)
8426         return true;
8427 
8428       // If the scalar cannot be safely casted to the vector element type,
8429       // reject it.
8430       if (CstScalar) {
8431         bool Truncated = false;
8432         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8433                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8434         if (Truncated)
8435           return true;
8436       }
8437 
8438       ScalarCast = CK_FloatingCast;
8439     } else if (ScalarTy->isIntegralType(S.Context)) {
8440       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8441         return true;
8442 
8443       ScalarCast = CK_IntegralToFloating;
8444     } else
8445       return true;
8446   }
8447 
8448   // Adjust scalar if desired.
8449   if (Scalar) {
8450     if (ScalarCast != CK_NoOp)
8451       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8452     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8453   }
8454   return false;
8455 }
8456 
8457 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8458                                    SourceLocation Loc, bool IsCompAssign,
8459                                    bool AllowBothBool,
8460                                    bool AllowBoolConversions) {
8461   if (!IsCompAssign) {
8462     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8463     if (LHS.isInvalid())
8464       return QualType();
8465   }
8466   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8467   if (RHS.isInvalid())
8468     return QualType();
8469 
8470   // For conversion purposes, we ignore any qualifiers.
8471   // For example, "const float" and "float" are equivalent.
8472   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8473   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8474 
8475   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8476   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8477   assert(LHSVecType || RHSVecType);
8478 
8479   // AltiVec-style "vector bool op vector bool" combinations are allowed
8480   // for some operators but not others.
8481   if (!AllowBothBool &&
8482       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8483       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8484     return InvalidOperands(Loc, LHS, RHS);
8485 
8486   // If the vector types are identical, return.
8487   if (Context.hasSameType(LHSType, RHSType))
8488     return LHSType;
8489 
8490   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8491   if (LHSVecType && RHSVecType &&
8492       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8493     if (isa<ExtVectorType>(LHSVecType)) {
8494       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8495       return LHSType;
8496     }
8497 
8498     if (!IsCompAssign)
8499       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8500     return RHSType;
8501   }
8502 
8503   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8504   // can be mixed, with the result being the non-bool type.  The non-bool
8505   // operand must have integer element type.
8506   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8507       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8508       (Context.getTypeSize(LHSVecType->getElementType()) ==
8509        Context.getTypeSize(RHSVecType->getElementType()))) {
8510     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8511         LHSVecType->getElementType()->isIntegerType() &&
8512         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8513       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8514       return LHSType;
8515     }
8516     if (!IsCompAssign &&
8517         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8518         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8519         RHSVecType->getElementType()->isIntegerType()) {
8520       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8521       return RHSType;
8522     }
8523   }
8524 
8525   // If there's a vector type and a scalar, try to convert the scalar to
8526   // the vector element type and splat.
8527   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8528   if (!RHSVecType) {
8529     if (isa<ExtVectorType>(LHSVecType)) {
8530       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8531                                     LHSVecType->getElementType(), LHSType,
8532                                     DiagID))
8533         return LHSType;
8534     } else {
8535       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8536         return LHSType;
8537     }
8538   }
8539   if (!LHSVecType) {
8540     if (isa<ExtVectorType>(RHSVecType)) {
8541       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8542                                     LHSType, RHSVecType->getElementType(),
8543                                     RHSType, DiagID))
8544         return RHSType;
8545     } else {
8546       if (LHS.get()->getValueKind() == VK_LValue ||
8547           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8548         return RHSType;
8549     }
8550   }
8551 
8552   // FIXME: The code below also handles conversion between vectors and
8553   // non-scalars, we should break this down into fine grained specific checks
8554   // and emit proper diagnostics.
8555   QualType VecType = LHSVecType ? LHSType : RHSType;
8556   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8557   QualType OtherType = LHSVecType ? RHSType : LHSType;
8558   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8559   if (isLaxVectorConversion(OtherType, VecType)) {
8560     // If we're allowing lax vector conversions, only the total (data) size
8561     // needs to be the same. For non compound assignment, if one of the types is
8562     // scalar, the result is always the vector type.
8563     if (!IsCompAssign) {
8564       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8565       return VecType;
8566     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8567     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8568     // type. Note that this is already done by non-compound assignments in
8569     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8570     // <1 x T> -> T. The result is also a vector type.
8571     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8572                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8573       ExprResult *RHSExpr = &RHS;
8574       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8575       return VecType;
8576     }
8577   }
8578 
8579   // Okay, the expression is invalid.
8580 
8581   // If there's a non-vector, non-real operand, diagnose that.
8582   if ((!RHSVecType && !RHSType->isRealType()) ||
8583       (!LHSVecType && !LHSType->isRealType())) {
8584     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8585       << LHSType << RHSType
8586       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8587     return QualType();
8588   }
8589 
8590   // OpenCL V1.1 6.2.6.p1:
8591   // If the operands are of more than one vector type, then an error shall
8592   // occur. Implicit conversions between vector types are not permitted, per
8593   // section 6.2.1.
8594   if (getLangOpts().OpenCL &&
8595       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8596       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8597     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8598                                                            << RHSType;
8599     return QualType();
8600   }
8601 
8602 
8603   // If there is a vector type that is not a ExtVector and a scalar, we reach
8604   // this point if scalar could not be converted to the vector's element type
8605   // without truncation.
8606   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8607       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8608     QualType Scalar = LHSVecType ? RHSType : LHSType;
8609     QualType Vector = LHSVecType ? LHSType : RHSType;
8610     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8611     Diag(Loc,
8612          diag::err_typecheck_vector_not_convertable_implict_truncation)
8613         << ScalarOrVector << Scalar << Vector;
8614 
8615     return QualType();
8616   }
8617 
8618   // Otherwise, use the generic diagnostic.
8619   Diag(Loc, DiagID)
8620     << LHSType << RHSType
8621     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8622   return QualType();
8623 }
8624 
8625 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8626 // expression.  These are mainly cases where the null pointer is used as an
8627 // integer instead of a pointer.
8628 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8629                                 SourceLocation Loc, bool IsCompare) {
8630   // The canonical way to check for a GNU null is with isNullPointerConstant,
8631   // but we use a bit of a hack here for speed; this is a relatively
8632   // hot path, and isNullPointerConstant is slow.
8633   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8634   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8635 
8636   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8637 
8638   // Avoid analyzing cases where the result will either be invalid (and
8639   // diagnosed as such) or entirely valid and not something to warn about.
8640   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8641       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8642     return;
8643 
8644   // Comparison operations would not make sense with a null pointer no matter
8645   // what the other expression is.
8646   if (!IsCompare) {
8647     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8648         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8649         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8650     return;
8651   }
8652 
8653   // The rest of the operations only make sense with a null pointer
8654   // if the other expression is a pointer.
8655   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8656       NonNullType->canDecayToPointerType())
8657     return;
8658 
8659   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8660       << LHSNull /* LHS is NULL */ << NonNullType
8661       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8662 }
8663 
8664 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8665                                                ExprResult &RHS,
8666                                                SourceLocation Loc, bool IsDiv) {
8667   // Check for division/remainder by zero.
8668   llvm::APSInt RHSValue;
8669   if (!RHS.get()->isValueDependent() &&
8670       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8671     S.DiagRuntimeBehavior(Loc, RHS.get(),
8672                           S.PDiag(diag::warn_remainder_division_by_zero)
8673                             << IsDiv << RHS.get()->getSourceRange());
8674 }
8675 
8676 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8677                                            SourceLocation Loc,
8678                                            bool IsCompAssign, bool IsDiv) {
8679   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8680 
8681   if (LHS.get()->getType()->isVectorType() ||
8682       RHS.get()->getType()->isVectorType())
8683     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8684                                /*AllowBothBool*/getLangOpts().AltiVec,
8685                                /*AllowBoolConversions*/false);
8686 
8687   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8688   if (LHS.isInvalid() || RHS.isInvalid())
8689     return QualType();
8690 
8691 
8692   if (compType.isNull() || !compType->isArithmeticType())
8693     return InvalidOperands(Loc, LHS, RHS);
8694   if (IsDiv)
8695     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8696   return compType;
8697 }
8698 
8699 QualType Sema::CheckRemainderOperands(
8700   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8701   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8702 
8703   if (LHS.get()->getType()->isVectorType() ||
8704       RHS.get()->getType()->isVectorType()) {
8705     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8706         RHS.get()->getType()->hasIntegerRepresentation())
8707       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8708                                  /*AllowBothBool*/getLangOpts().AltiVec,
8709                                  /*AllowBoolConversions*/false);
8710     return InvalidOperands(Loc, LHS, RHS);
8711   }
8712 
8713   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8714   if (LHS.isInvalid() || RHS.isInvalid())
8715     return QualType();
8716 
8717   if (compType.isNull() || !compType->isIntegerType())
8718     return InvalidOperands(Loc, LHS, RHS);
8719   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8720   return compType;
8721 }
8722 
8723 /// Diagnose invalid arithmetic on two void pointers.
8724 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8725                                                 Expr *LHSExpr, Expr *RHSExpr) {
8726   S.Diag(Loc, S.getLangOpts().CPlusPlus
8727                 ? diag::err_typecheck_pointer_arith_void_type
8728                 : diag::ext_gnu_void_ptr)
8729     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8730                             << RHSExpr->getSourceRange();
8731 }
8732 
8733 /// Diagnose invalid arithmetic on a void pointer.
8734 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8735                                             Expr *Pointer) {
8736   S.Diag(Loc, S.getLangOpts().CPlusPlus
8737                 ? diag::err_typecheck_pointer_arith_void_type
8738                 : diag::ext_gnu_void_ptr)
8739     << 0 /* one pointer */ << Pointer->getSourceRange();
8740 }
8741 
8742 /// Diagnose invalid arithmetic on a null pointer.
8743 ///
8744 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8745 /// idiom, which we recognize as a GNU extension.
8746 ///
8747 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8748                                             Expr *Pointer, bool IsGNUIdiom) {
8749   if (IsGNUIdiom)
8750     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8751       << Pointer->getSourceRange();
8752   else
8753     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8754       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8755 }
8756 
8757 /// Diagnose invalid arithmetic on two function pointers.
8758 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8759                                                     Expr *LHS, Expr *RHS) {
8760   assert(LHS->getType()->isAnyPointerType());
8761   assert(RHS->getType()->isAnyPointerType());
8762   S.Diag(Loc, S.getLangOpts().CPlusPlus
8763                 ? diag::err_typecheck_pointer_arith_function_type
8764                 : diag::ext_gnu_ptr_func_arith)
8765     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8766     // We only show the second type if it differs from the first.
8767     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8768                                                    RHS->getType())
8769     << RHS->getType()->getPointeeType()
8770     << LHS->getSourceRange() << RHS->getSourceRange();
8771 }
8772 
8773 /// Diagnose invalid arithmetic on a function pointer.
8774 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8775                                                 Expr *Pointer) {
8776   assert(Pointer->getType()->isAnyPointerType());
8777   S.Diag(Loc, S.getLangOpts().CPlusPlus
8778                 ? diag::err_typecheck_pointer_arith_function_type
8779                 : diag::ext_gnu_ptr_func_arith)
8780     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8781     << 0 /* one pointer, so only one type */
8782     << Pointer->getSourceRange();
8783 }
8784 
8785 /// Emit error if Operand is incomplete pointer type
8786 ///
8787 /// \returns True if pointer has incomplete type
8788 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8789                                                  Expr *Operand) {
8790   QualType ResType = Operand->getType();
8791   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8792     ResType = ResAtomicType->getValueType();
8793 
8794   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8795   QualType PointeeTy = ResType->getPointeeType();
8796   return S.RequireCompleteType(Loc, PointeeTy,
8797                                diag::err_typecheck_arithmetic_incomplete_type,
8798                                PointeeTy, Operand->getSourceRange());
8799 }
8800 
8801 /// Check the validity of an arithmetic pointer operand.
8802 ///
8803 /// If the operand has pointer type, this code will check for pointer types
8804 /// which are invalid in arithmetic operations. These will be diagnosed
8805 /// appropriately, including whether or not the use is supported as an
8806 /// extension.
8807 ///
8808 /// \returns True when the operand is valid to use (even if as an extension).
8809 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8810                                             Expr *Operand) {
8811   QualType ResType = Operand->getType();
8812   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8813     ResType = ResAtomicType->getValueType();
8814 
8815   if (!ResType->isAnyPointerType()) return true;
8816 
8817   QualType PointeeTy = ResType->getPointeeType();
8818   if (PointeeTy->isVoidType()) {
8819     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8820     return !S.getLangOpts().CPlusPlus;
8821   }
8822   if (PointeeTy->isFunctionType()) {
8823     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8824     return !S.getLangOpts().CPlusPlus;
8825   }
8826 
8827   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8828 
8829   return true;
8830 }
8831 
8832 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8833 /// operands.
8834 ///
8835 /// This routine will diagnose any invalid arithmetic on pointer operands much
8836 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8837 /// for emitting a single diagnostic even for operations where both LHS and RHS
8838 /// are (potentially problematic) pointers.
8839 ///
8840 /// \returns True when the operand is valid to use (even if as an extension).
8841 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8842                                                 Expr *LHSExpr, Expr *RHSExpr) {
8843   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8844   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8845   if (!isLHSPointer && !isRHSPointer) return true;
8846 
8847   QualType LHSPointeeTy, RHSPointeeTy;
8848   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8849   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8850 
8851   // if both are pointers check if operation is valid wrt address spaces
8852   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8853     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8854     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8855     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8856       S.Diag(Loc,
8857              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8858           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8859           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8860       return false;
8861     }
8862   }
8863 
8864   // Check for arithmetic on pointers to incomplete types.
8865   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8866   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8867   if (isLHSVoidPtr || isRHSVoidPtr) {
8868     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8869     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8870     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8871 
8872     return !S.getLangOpts().CPlusPlus;
8873   }
8874 
8875   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8876   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8877   if (isLHSFuncPtr || isRHSFuncPtr) {
8878     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8879     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8880                                                                 RHSExpr);
8881     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8882 
8883     return !S.getLangOpts().CPlusPlus;
8884   }
8885 
8886   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8887     return false;
8888   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8889     return false;
8890 
8891   return true;
8892 }
8893 
8894 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8895 /// literal.
8896 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8897                                   Expr *LHSExpr, Expr *RHSExpr) {
8898   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8899   Expr* IndexExpr = RHSExpr;
8900   if (!StrExpr) {
8901     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8902     IndexExpr = LHSExpr;
8903   }
8904 
8905   bool IsStringPlusInt = StrExpr &&
8906       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8907   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8908     return;
8909 
8910   llvm::APSInt index;
8911   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8912     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8913     if (index.isNonNegative() &&
8914         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8915                               index.isUnsigned()))
8916       return;
8917   }
8918 
8919   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8920   Self.Diag(OpLoc, diag::warn_string_plus_int)
8921       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8922 
8923   // Only print a fixit for "str" + int, not for int + "str".
8924   if (IndexExpr == RHSExpr) {
8925     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8926     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8927         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8928         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8929         << FixItHint::CreateInsertion(EndLoc, "]");
8930   } else
8931     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8932 }
8933 
8934 /// Emit a warning when adding a char literal to a string.
8935 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8936                                    Expr *LHSExpr, Expr *RHSExpr) {
8937   const Expr *StringRefExpr = LHSExpr;
8938   const CharacterLiteral *CharExpr =
8939       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8940 
8941   if (!CharExpr) {
8942     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8943     StringRefExpr = RHSExpr;
8944   }
8945 
8946   if (!CharExpr || !StringRefExpr)
8947     return;
8948 
8949   const QualType StringType = StringRefExpr->getType();
8950 
8951   // Return if not a PointerType.
8952   if (!StringType->isAnyPointerType())
8953     return;
8954 
8955   // Return if not a CharacterType.
8956   if (!StringType->getPointeeType()->isAnyCharacterType())
8957     return;
8958 
8959   ASTContext &Ctx = Self.getASTContext();
8960   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8961 
8962   const QualType CharType = CharExpr->getType();
8963   if (!CharType->isAnyCharacterType() &&
8964       CharType->isIntegerType() &&
8965       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8966     Self.Diag(OpLoc, diag::warn_string_plus_char)
8967         << DiagRange << Ctx.CharTy;
8968   } else {
8969     Self.Diag(OpLoc, diag::warn_string_plus_char)
8970         << DiagRange << CharExpr->getType();
8971   }
8972 
8973   // Only print a fixit for str + char, not for char + str.
8974   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8975     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8976     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8977         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8978         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8979         << FixItHint::CreateInsertion(EndLoc, "]");
8980   } else {
8981     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8982   }
8983 }
8984 
8985 /// Emit error when two pointers are incompatible.
8986 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8987                                            Expr *LHSExpr, Expr *RHSExpr) {
8988   assert(LHSExpr->getType()->isAnyPointerType());
8989   assert(RHSExpr->getType()->isAnyPointerType());
8990   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8991     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8992     << RHSExpr->getSourceRange();
8993 }
8994 
8995 // C99 6.5.6
8996 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8997                                      SourceLocation Loc, BinaryOperatorKind Opc,
8998                                      QualType* CompLHSTy) {
8999   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9000 
9001   if (LHS.get()->getType()->isVectorType() ||
9002       RHS.get()->getType()->isVectorType()) {
9003     QualType compType = CheckVectorOperands(
9004         LHS, RHS, Loc, CompLHSTy,
9005         /*AllowBothBool*/getLangOpts().AltiVec,
9006         /*AllowBoolConversions*/getLangOpts().ZVector);
9007     if (CompLHSTy) *CompLHSTy = compType;
9008     return compType;
9009   }
9010 
9011   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9012   if (LHS.isInvalid() || RHS.isInvalid())
9013     return QualType();
9014 
9015   // Diagnose "string literal" '+' int and string '+' "char literal".
9016   if (Opc == BO_Add) {
9017     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9018     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9019   }
9020 
9021   // handle the common case first (both operands are arithmetic).
9022   if (!compType.isNull() && compType->isArithmeticType()) {
9023     if (CompLHSTy) *CompLHSTy = compType;
9024     return compType;
9025   }
9026 
9027   // Type-checking.  Ultimately the pointer's going to be in PExp;
9028   // note that we bias towards the LHS being the pointer.
9029   Expr *PExp = LHS.get(), *IExp = RHS.get();
9030 
9031   bool isObjCPointer;
9032   if (PExp->getType()->isPointerType()) {
9033     isObjCPointer = false;
9034   } else if (PExp->getType()->isObjCObjectPointerType()) {
9035     isObjCPointer = true;
9036   } else {
9037     std::swap(PExp, IExp);
9038     if (PExp->getType()->isPointerType()) {
9039       isObjCPointer = false;
9040     } else if (PExp->getType()->isObjCObjectPointerType()) {
9041       isObjCPointer = true;
9042     } else {
9043       return InvalidOperands(Loc, LHS, RHS);
9044     }
9045   }
9046   assert(PExp->getType()->isAnyPointerType());
9047 
9048   if (!IExp->getType()->isIntegerType())
9049     return InvalidOperands(Loc, LHS, RHS);
9050 
9051   // Adding to a null pointer results in undefined behavior.
9052   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9053           Context, Expr::NPC_ValueDependentIsNotNull)) {
9054     // In C++ adding zero to a null pointer is defined.
9055     llvm::APSInt KnownVal;
9056     if (!getLangOpts().CPlusPlus ||
9057         (!IExp->isValueDependent() &&
9058          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9059       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9060       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9061           Context, BO_Add, PExp, IExp);
9062       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9063     }
9064   }
9065 
9066   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9067     return QualType();
9068 
9069   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9070     return QualType();
9071 
9072   // Check array bounds for pointer arithemtic
9073   CheckArrayAccess(PExp, IExp);
9074 
9075   if (CompLHSTy) {
9076     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9077     if (LHSTy.isNull()) {
9078       LHSTy = LHS.get()->getType();
9079       if (LHSTy->isPromotableIntegerType())
9080         LHSTy = Context.getPromotedIntegerType(LHSTy);
9081     }
9082     *CompLHSTy = LHSTy;
9083   }
9084 
9085   return PExp->getType();
9086 }
9087 
9088 // C99 6.5.6
9089 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9090                                         SourceLocation Loc,
9091                                         QualType* CompLHSTy) {
9092   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9093 
9094   if (LHS.get()->getType()->isVectorType() ||
9095       RHS.get()->getType()->isVectorType()) {
9096     QualType compType = CheckVectorOperands(
9097         LHS, RHS, Loc, CompLHSTy,
9098         /*AllowBothBool*/getLangOpts().AltiVec,
9099         /*AllowBoolConversions*/getLangOpts().ZVector);
9100     if (CompLHSTy) *CompLHSTy = compType;
9101     return compType;
9102   }
9103 
9104   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9105   if (LHS.isInvalid() || RHS.isInvalid())
9106     return QualType();
9107 
9108   // Enforce type constraints: C99 6.5.6p3.
9109 
9110   // Handle the common case first (both operands are arithmetic).
9111   if (!compType.isNull() && compType->isArithmeticType()) {
9112     if (CompLHSTy) *CompLHSTy = compType;
9113     return compType;
9114   }
9115 
9116   // Either ptr - int   or   ptr - ptr.
9117   if (LHS.get()->getType()->isAnyPointerType()) {
9118     QualType lpointee = LHS.get()->getType()->getPointeeType();
9119 
9120     // Diagnose bad cases where we step over interface counts.
9121     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9122         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9123       return QualType();
9124 
9125     // The result type of a pointer-int computation is the pointer type.
9126     if (RHS.get()->getType()->isIntegerType()) {
9127       // Subtracting from a null pointer should produce a warning.
9128       // The last argument to the diagnose call says this doesn't match the
9129       // GNU int-to-pointer idiom.
9130       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9131                                            Expr::NPC_ValueDependentIsNotNull)) {
9132         // In C++ adding zero to a null pointer is defined.
9133         llvm::APSInt KnownVal;
9134         if (!getLangOpts().CPlusPlus ||
9135             (!RHS.get()->isValueDependent() &&
9136              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9137           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9138         }
9139       }
9140 
9141       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9142         return QualType();
9143 
9144       // Check array bounds for pointer arithemtic
9145       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9146                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9147 
9148       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9149       return LHS.get()->getType();
9150     }
9151 
9152     // Handle pointer-pointer subtractions.
9153     if (const PointerType *RHSPTy
9154           = RHS.get()->getType()->getAs<PointerType>()) {
9155       QualType rpointee = RHSPTy->getPointeeType();
9156 
9157       if (getLangOpts().CPlusPlus) {
9158         // Pointee types must be the same: C++ [expr.add]
9159         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9160           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9161         }
9162       } else {
9163         // Pointee types must be compatible C99 6.5.6p3
9164         if (!Context.typesAreCompatible(
9165                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9166                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9167           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9168           return QualType();
9169         }
9170       }
9171 
9172       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9173                                                LHS.get(), RHS.get()))
9174         return QualType();
9175 
9176       // FIXME: Add warnings for nullptr - ptr.
9177 
9178       // The pointee type may have zero size.  As an extension, a structure or
9179       // union may have zero size or an array may have zero length.  In this
9180       // case subtraction does not make sense.
9181       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9182         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9183         if (ElementSize.isZero()) {
9184           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9185             << rpointee.getUnqualifiedType()
9186             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9187         }
9188       }
9189 
9190       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9191       return Context.getPointerDiffType();
9192     }
9193   }
9194 
9195   return InvalidOperands(Loc, LHS, RHS);
9196 }
9197 
9198 static bool isScopedEnumerationType(QualType T) {
9199   if (const EnumType *ET = T->getAs<EnumType>())
9200     return ET->getDecl()->isScoped();
9201   return false;
9202 }
9203 
9204 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9205                                    SourceLocation Loc, BinaryOperatorKind Opc,
9206                                    QualType LHSType) {
9207   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9208   // so skip remaining warnings as we don't want to modify values within Sema.
9209   if (S.getLangOpts().OpenCL)
9210     return;
9211 
9212   llvm::APSInt Right;
9213   // Check right/shifter operand
9214   if (RHS.get()->isValueDependent() ||
9215       !RHS.get()->EvaluateAsInt(Right, S.Context))
9216     return;
9217 
9218   if (Right.isNegative()) {
9219     S.DiagRuntimeBehavior(Loc, RHS.get(),
9220                           S.PDiag(diag::warn_shift_negative)
9221                             << RHS.get()->getSourceRange());
9222     return;
9223   }
9224   llvm::APInt LeftBits(Right.getBitWidth(),
9225                        S.Context.getTypeSize(LHS.get()->getType()));
9226   if (Right.uge(LeftBits)) {
9227     S.DiagRuntimeBehavior(Loc, RHS.get(),
9228                           S.PDiag(diag::warn_shift_gt_typewidth)
9229                             << RHS.get()->getSourceRange());
9230     return;
9231   }
9232   if (Opc != BO_Shl)
9233     return;
9234 
9235   // When left shifting an ICE which is signed, we can check for overflow which
9236   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9237   // integers have defined behavior modulo one more than the maximum value
9238   // representable in the result type, so never warn for those.
9239   llvm::APSInt Left;
9240   if (LHS.get()->isValueDependent() ||
9241       LHSType->hasUnsignedIntegerRepresentation() ||
9242       !LHS.get()->EvaluateAsInt(Left, S.Context))
9243     return;
9244 
9245   // If LHS does not have a signed type and non-negative value
9246   // then, the behavior is undefined. Warn about it.
9247   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9248     S.DiagRuntimeBehavior(Loc, LHS.get(),
9249                           S.PDiag(diag::warn_shift_lhs_negative)
9250                             << LHS.get()->getSourceRange());
9251     return;
9252   }
9253 
9254   llvm::APInt ResultBits =
9255       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9256   if (LeftBits.uge(ResultBits))
9257     return;
9258   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9259   Result = Result.shl(Right);
9260 
9261   // Print the bit representation of the signed integer as an unsigned
9262   // hexadecimal number.
9263   SmallString<40> HexResult;
9264   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9265 
9266   // If we are only missing a sign bit, this is less likely to result in actual
9267   // bugs -- if the result is cast back to an unsigned type, it will have the
9268   // expected value. Thus we place this behind a different warning that can be
9269   // turned off separately if needed.
9270   if (LeftBits == ResultBits - 1) {
9271     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9272         << HexResult << LHSType
9273         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9274     return;
9275   }
9276 
9277   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9278     << HexResult.str() << Result.getMinSignedBits() << LHSType
9279     << Left.getBitWidth() << LHS.get()->getSourceRange()
9280     << RHS.get()->getSourceRange();
9281 }
9282 
9283 /// Return the resulting type when a vector is shifted
9284 ///        by a scalar or vector shift amount.
9285 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9286                                  SourceLocation Loc, bool IsCompAssign) {
9287   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9288   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9289       !LHS.get()->getType()->isVectorType()) {
9290     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9291       << RHS.get()->getType() << LHS.get()->getType()
9292       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9293     return QualType();
9294   }
9295 
9296   if (!IsCompAssign) {
9297     LHS = S.UsualUnaryConversions(LHS.get());
9298     if (LHS.isInvalid()) return QualType();
9299   }
9300 
9301   RHS = S.UsualUnaryConversions(RHS.get());
9302   if (RHS.isInvalid()) return QualType();
9303 
9304   QualType LHSType = LHS.get()->getType();
9305   // Note that LHS might be a scalar because the routine calls not only in
9306   // OpenCL case.
9307   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9308   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9309 
9310   // Note that RHS might not be a vector.
9311   QualType RHSType = RHS.get()->getType();
9312   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9313   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9314 
9315   // The operands need to be integers.
9316   if (!LHSEleType->isIntegerType()) {
9317     S.Diag(Loc, diag::err_typecheck_expect_int)
9318       << LHS.get()->getType() << LHS.get()->getSourceRange();
9319     return QualType();
9320   }
9321 
9322   if (!RHSEleType->isIntegerType()) {
9323     S.Diag(Loc, diag::err_typecheck_expect_int)
9324       << RHS.get()->getType() << RHS.get()->getSourceRange();
9325     return QualType();
9326   }
9327 
9328   if (!LHSVecTy) {
9329     assert(RHSVecTy);
9330     if (IsCompAssign)
9331       return RHSType;
9332     if (LHSEleType != RHSEleType) {
9333       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9334       LHSEleType = RHSEleType;
9335     }
9336     QualType VecTy =
9337         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9338     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9339     LHSType = VecTy;
9340   } else if (RHSVecTy) {
9341     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9342     // are applied component-wise. So if RHS is a vector, then ensure
9343     // that the number of elements is the same as LHS...
9344     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9345       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9346         << LHS.get()->getType() << RHS.get()->getType()
9347         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9348       return QualType();
9349     }
9350     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9351       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9352       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9353       if (LHSBT != RHSBT &&
9354           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9355         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9356             << LHS.get()->getType() << RHS.get()->getType()
9357             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9358       }
9359     }
9360   } else {
9361     // ...else expand RHS to match the number of elements in LHS.
9362     QualType VecTy =
9363       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9364     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9365   }
9366 
9367   return LHSType;
9368 }
9369 
9370 // C99 6.5.7
9371 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9372                                   SourceLocation Loc, BinaryOperatorKind Opc,
9373                                   bool IsCompAssign) {
9374   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9375 
9376   // Vector shifts promote their scalar inputs to vector type.
9377   if (LHS.get()->getType()->isVectorType() ||
9378       RHS.get()->getType()->isVectorType()) {
9379     if (LangOpts.ZVector) {
9380       // The shift operators for the z vector extensions work basically
9381       // like general shifts, except that neither the LHS nor the RHS is
9382       // allowed to be a "vector bool".
9383       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9384         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9385           return InvalidOperands(Loc, LHS, RHS);
9386       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9387         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9388           return InvalidOperands(Loc, LHS, RHS);
9389     }
9390     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9391   }
9392 
9393   // Shifts don't perform usual arithmetic conversions, they just do integer
9394   // promotions on each operand. C99 6.5.7p3
9395 
9396   // For the LHS, do usual unary conversions, but then reset them away
9397   // if this is a compound assignment.
9398   ExprResult OldLHS = LHS;
9399   LHS = UsualUnaryConversions(LHS.get());
9400   if (LHS.isInvalid())
9401     return QualType();
9402   QualType LHSType = LHS.get()->getType();
9403   if (IsCompAssign) LHS = OldLHS;
9404 
9405   // The RHS is simpler.
9406   RHS = UsualUnaryConversions(RHS.get());
9407   if (RHS.isInvalid())
9408     return QualType();
9409   QualType RHSType = RHS.get()->getType();
9410 
9411   // C99 6.5.7p2: Each of the operands shall have integer type.
9412   if (!LHSType->hasIntegerRepresentation() ||
9413       !RHSType->hasIntegerRepresentation())
9414     return InvalidOperands(Loc, LHS, RHS);
9415 
9416   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9417   // hasIntegerRepresentation() above instead of this.
9418   if (isScopedEnumerationType(LHSType) ||
9419       isScopedEnumerationType(RHSType)) {
9420     return InvalidOperands(Loc, LHS, RHS);
9421   }
9422   // Sanity-check shift operands
9423   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9424 
9425   // "The type of the result is that of the promoted left operand."
9426   return LHSType;
9427 }
9428 
9429 /// If two different enums are compared, raise a warning.
9430 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9431                                 Expr *RHS) {
9432   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9433   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9434 
9435   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9436   if (!LHSEnumType)
9437     return;
9438   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9439   if (!RHSEnumType)
9440     return;
9441 
9442   // Ignore anonymous enums.
9443   if (!LHSEnumType->getDecl()->getIdentifier() &&
9444       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9445     return;
9446   if (!RHSEnumType->getDecl()->getIdentifier() &&
9447       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9448     return;
9449 
9450   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9451     return;
9452 
9453   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9454       << LHSStrippedType << RHSStrippedType
9455       << LHS->getSourceRange() << RHS->getSourceRange();
9456 }
9457 
9458 /// Diagnose bad pointer comparisons.
9459 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9460                                               ExprResult &LHS, ExprResult &RHS,
9461                                               bool IsError) {
9462   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9463                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9464     << LHS.get()->getType() << RHS.get()->getType()
9465     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9466 }
9467 
9468 /// Returns false if the pointers are converted to a composite type,
9469 /// true otherwise.
9470 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9471                                            ExprResult &LHS, ExprResult &RHS) {
9472   // C++ [expr.rel]p2:
9473   //   [...] Pointer conversions (4.10) and qualification
9474   //   conversions (4.4) are performed on pointer operands (or on
9475   //   a pointer operand and a null pointer constant) to bring
9476   //   them to their composite pointer type. [...]
9477   //
9478   // C++ [expr.eq]p1 uses the same notion for (in)equality
9479   // comparisons of pointers.
9480 
9481   QualType LHSType = LHS.get()->getType();
9482   QualType RHSType = RHS.get()->getType();
9483   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9484          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9485 
9486   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9487   if (T.isNull()) {
9488     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9489         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9490       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9491     else
9492       S.InvalidOperands(Loc, LHS, RHS);
9493     return true;
9494   }
9495 
9496   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9497   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9498   return false;
9499 }
9500 
9501 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9502                                                     ExprResult &LHS,
9503                                                     ExprResult &RHS,
9504                                                     bool IsError) {
9505   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9506                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9507     << LHS.get()->getType() << RHS.get()->getType()
9508     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9509 }
9510 
9511 static bool isObjCObjectLiteral(ExprResult &E) {
9512   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9513   case Stmt::ObjCArrayLiteralClass:
9514   case Stmt::ObjCDictionaryLiteralClass:
9515   case Stmt::ObjCStringLiteralClass:
9516   case Stmt::ObjCBoxedExprClass:
9517     return true;
9518   default:
9519     // Note that ObjCBoolLiteral is NOT an object literal!
9520     return false;
9521   }
9522 }
9523 
9524 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9525   const ObjCObjectPointerType *Type =
9526     LHS->getType()->getAs<ObjCObjectPointerType>();
9527 
9528   // If this is not actually an Objective-C object, bail out.
9529   if (!Type)
9530     return false;
9531 
9532   // Get the LHS object's interface type.
9533   QualType InterfaceType = Type->getPointeeType();
9534 
9535   // If the RHS isn't an Objective-C object, bail out.
9536   if (!RHS->getType()->isObjCObjectPointerType())
9537     return false;
9538 
9539   // Try to find the -isEqual: method.
9540   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9541   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9542                                                       InterfaceType,
9543                                                       /*instance=*/true);
9544   if (!Method) {
9545     if (Type->isObjCIdType()) {
9546       // For 'id', just check the global pool.
9547       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9548                                                   /*receiverId=*/true);
9549     } else {
9550       // Check protocols.
9551       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9552                                              /*instance=*/true);
9553     }
9554   }
9555 
9556   if (!Method)
9557     return false;
9558 
9559   QualType T = Method->parameters()[0]->getType();
9560   if (!T->isObjCObjectPointerType())
9561     return false;
9562 
9563   QualType R = Method->getReturnType();
9564   if (!R->isScalarType())
9565     return false;
9566 
9567   return true;
9568 }
9569 
9570 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9571   FromE = FromE->IgnoreParenImpCasts();
9572   switch (FromE->getStmtClass()) {
9573     default:
9574       break;
9575     case Stmt::ObjCStringLiteralClass:
9576       // "string literal"
9577       return LK_String;
9578     case Stmt::ObjCArrayLiteralClass:
9579       // "array literal"
9580       return LK_Array;
9581     case Stmt::ObjCDictionaryLiteralClass:
9582       // "dictionary literal"
9583       return LK_Dictionary;
9584     case Stmt::BlockExprClass:
9585       return LK_Block;
9586     case Stmt::ObjCBoxedExprClass: {
9587       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9588       switch (Inner->getStmtClass()) {
9589         case Stmt::IntegerLiteralClass:
9590         case Stmt::FloatingLiteralClass:
9591         case Stmt::CharacterLiteralClass:
9592         case Stmt::ObjCBoolLiteralExprClass:
9593         case Stmt::CXXBoolLiteralExprClass:
9594           // "numeric literal"
9595           return LK_Numeric;
9596         case Stmt::ImplicitCastExprClass: {
9597           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9598           // Boolean literals can be represented by implicit casts.
9599           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9600             return LK_Numeric;
9601           break;
9602         }
9603         default:
9604           break;
9605       }
9606       return LK_Boxed;
9607     }
9608   }
9609   return LK_None;
9610 }
9611 
9612 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9613                                           ExprResult &LHS, ExprResult &RHS,
9614                                           BinaryOperator::Opcode Opc){
9615   Expr *Literal;
9616   Expr *Other;
9617   if (isObjCObjectLiteral(LHS)) {
9618     Literal = LHS.get();
9619     Other = RHS.get();
9620   } else {
9621     Literal = RHS.get();
9622     Other = LHS.get();
9623   }
9624 
9625   // Don't warn on comparisons against nil.
9626   Other = Other->IgnoreParenCasts();
9627   if (Other->isNullPointerConstant(S.getASTContext(),
9628                                    Expr::NPC_ValueDependentIsNotNull))
9629     return;
9630 
9631   // This should be kept in sync with warn_objc_literal_comparison.
9632   // LK_String should always be after the other literals, since it has its own
9633   // warning flag.
9634   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9635   assert(LiteralKind != Sema::LK_Block);
9636   if (LiteralKind == Sema::LK_None) {
9637     llvm_unreachable("Unknown Objective-C object literal kind");
9638   }
9639 
9640   if (LiteralKind == Sema::LK_String)
9641     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9642       << Literal->getSourceRange();
9643   else
9644     S.Diag(Loc, diag::warn_objc_literal_comparison)
9645       << LiteralKind << Literal->getSourceRange();
9646 
9647   if (BinaryOperator::isEqualityOp(Opc) &&
9648       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9649     SourceLocation Start = LHS.get()->getLocStart();
9650     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9651     CharSourceRange OpRange =
9652       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9653 
9654     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9655       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9656       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9657       << FixItHint::CreateInsertion(End, "]");
9658   }
9659 }
9660 
9661 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9662 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9663                                            ExprResult &RHS, SourceLocation Loc,
9664                                            BinaryOperatorKind Opc) {
9665   // Check that left hand side is !something.
9666   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9667   if (!UO || UO->getOpcode() != UO_LNot) return;
9668 
9669   // Only check if the right hand side is non-bool arithmetic type.
9670   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9671 
9672   // Make sure that the something in !something is not bool.
9673   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9674   if (SubExpr->isKnownToHaveBooleanValue()) return;
9675 
9676   // Emit warning.
9677   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9678   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9679       << Loc << IsBitwiseOp;
9680 
9681   // First note suggest !(x < y)
9682   SourceLocation FirstOpen = SubExpr->getLocStart();
9683   SourceLocation FirstClose = RHS.get()->getLocEnd();
9684   FirstClose = S.getLocForEndOfToken(FirstClose);
9685   if (FirstClose.isInvalid())
9686     FirstOpen = SourceLocation();
9687   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9688       << IsBitwiseOp
9689       << FixItHint::CreateInsertion(FirstOpen, "(")
9690       << FixItHint::CreateInsertion(FirstClose, ")");
9691 
9692   // Second note suggests (!x) < y
9693   SourceLocation SecondOpen = LHS.get()->getLocStart();
9694   SourceLocation SecondClose = LHS.get()->getLocEnd();
9695   SecondClose = S.getLocForEndOfToken(SecondClose);
9696   if (SecondClose.isInvalid())
9697     SecondOpen = SourceLocation();
9698   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9699       << FixItHint::CreateInsertion(SecondOpen, "(")
9700       << FixItHint::CreateInsertion(SecondClose, ")");
9701 }
9702 
9703 // Get the decl for a simple expression: a reference to a variable,
9704 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9705 static ValueDecl *getCompareDecl(Expr *E) {
9706   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9707     return DR->getDecl();
9708   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9709     if (Ivar->isFreeIvar())
9710       return Ivar->getDecl();
9711   }
9712   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9713     if (Mem->isImplicitAccess())
9714       return Mem->getMemberDecl();
9715   }
9716   return nullptr;
9717 }
9718 
9719 /// Diagnose some forms of syntactically-obvious tautological comparison.
9720 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9721                                            Expr *LHS, Expr *RHS,
9722                                            BinaryOperatorKind Opc) {
9723   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9724   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9725 
9726   QualType LHSType = LHS->getType();
9727   QualType RHSType = RHS->getType();
9728   if (LHSType->hasFloatingRepresentation() ||
9729       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9730       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9731       S.inTemplateInstantiation())
9732     return;
9733 
9734   // Comparisons between two array types are ill-formed for operator<=>, so
9735   // we shouldn't emit any additional warnings about it.
9736   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9737     return;
9738 
9739   // For non-floating point types, check for self-comparisons of the form
9740   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9741   // often indicate logic errors in the program.
9742   //
9743   // NOTE: Don't warn about comparison expressions resulting from macro
9744   // expansion. Also don't warn about comparisons which are only self
9745   // comparisons within a template instantiation. The warnings should catch
9746   // obvious cases in the definition of the template anyways. The idea is to
9747   // warn when the typed comparison operator will always evaluate to the same
9748   // result.
9749   ValueDecl *DL = getCompareDecl(LHSStripped);
9750   ValueDecl *DR = getCompareDecl(RHSStripped);
9751   if (DL && DR && declaresSameEntity(DL, DR)) {
9752     StringRef Result;
9753     switch (Opc) {
9754     case BO_EQ: case BO_LE: case BO_GE:
9755       Result = "true";
9756       break;
9757     case BO_NE: case BO_LT: case BO_GT:
9758       Result = "false";
9759       break;
9760     case BO_Cmp:
9761       Result = "'std::strong_ordering::equal'";
9762       break;
9763     default:
9764       break;
9765     }
9766     S.DiagRuntimeBehavior(Loc, nullptr,
9767                           S.PDiag(diag::warn_comparison_always)
9768                               << 0 /*self-comparison*/ << !Result.empty()
9769                               << Result);
9770   } else if (DL && DR &&
9771              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9772              !DL->isWeak() && !DR->isWeak()) {
9773     // What is it always going to evaluate to?
9774     StringRef Result;
9775     switch(Opc) {
9776     case BO_EQ: // e.g. array1 == array2
9777       Result = "false";
9778       break;
9779     case BO_NE: // e.g. array1 != array2
9780       Result = "true";
9781       break;
9782     default: // e.g. array1 <= array2
9783       // The best we can say is 'a constant'
9784       break;
9785     }
9786     S.DiagRuntimeBehavior(Loc, nullptr,
9787                           S.PDiag(diag::warn_comparison_always)
9788                               << 1 /*array comparison*/
9789                               << !Result.empty() << Result);
9790   }
9791 
9792   if (isa<CastExpr>(LHSStripped))
9793     LHSStripped = LHSStripped->IgnoreParenCasts();
9794   if (isa<CastExpr>(RHSStripped))
9795     RHSStripped = RHSStripped->IgnoreParenCasts();
9796 
9797   // Warn about comparisons against a string constant (unless the other
9798   // operand is null); the user probably wants strcmp.
9799   Expr *LiteralString = nullptr;
9800   Expr *LiteralStringStripped = nullptr;
9801   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9802       !RHSStripped->isNullPointerConstant(S.Context,
9803                                           Expr::NPC_ValueDependentIsNull)) {
9804     LiteralString = LHS;
9805     LiteralStringStripped = LHSStripped;
9806   } else if ((isa<StringLiteral>(RHSStripped) ||
9807               isa<ObjCEncodeExpr>(RHSStripped)) &&
9808              !LHSStripped->isNullPointerConstant(S.Context,
9809                                           Expr::NPC_ValueDependentIsNull)) {
9810     LiteralString = RHS;
9811     LiteralStringStripped = RHSStripped;
9812   }
9813 
9814   if (LiteralString) {
9815     S.DiagRuntimeBehavior(Loc, nullptr,
9816                           S.PDiag(diag::warn_stringcompare)
9817                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9818                               << LiteralString->getSourceRange());
9819   }
9820 }
9821 
9822 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9823   switch (CK) {
9824   default: {
9825 #ifndef NDEBUG
9826     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9827                  << "\n";
9828 #endif
9829     llvm_unreachable("unhandled cast kind");
9830   }
9831   case CK_UserDefinedConversion:
9832     return ICK_Identity;
9833   case CK_LValueToRValue:
9834     return ICK_Lvalue_To_Rvalue;
9835   case CK_ArrayToPointerDecay:
9836     return ICK_Array_To_Pointer;
9837   case CK_FunctionToPointerDecay:
9838     return ICK_Function_To_Pointer;
9839   case CK_IntegralCast:
9840     return ICK_Integral_Conversion;
9841   case CK_FloatingCast:
9842     return ICK_Floating_Conversion;
9843   case CK_IntegralToFloating:
9844   case CK_FloatingToIntegral:
9845     return ICK_Floating_Integral;
9846   case CK_IntegralComplexCast:
9847   case CK_FloatingComplexCast:
9848   case CK_FloatingComplexToIntegralComplex:
9849   case CK_IntegralComplexToFloatingComplex:
9850     return ICK_Complex_Conversion;
9851   case CK_FloatingComplexToReal:
9852   case CK_FloatingRealToComplex:
9853   case CK_IntegralComplexToReal:
9854   case CK_IntegralRealToComplex:
9855     return ICK_Complex_Real;
9856   }
9857 }
9858 
9859 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9860                                              QualType FromType,
9861                                              SourceLocation Loc) {
9862   // Check for a narrowing implicit conversion.
9863   StandardConversionSequence SCS;
9864   SCS.setAsIdentityConversion();
9865   SCS.setToType(0, FromType);
9866   SCS.setToType(1, ToType);
9867   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9868     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9869 
9870   APValue PreNarrowingValue;
9871   QualType PreNarrowingType;
9872   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9873                                PreNarrowingType,
9874                                /*IgnoreFloatToIntegralConversion*/ true)) {
9875   case NK_Dependent_Narrowing:
9876     // Implicit conversion to a narrower type, but the expression is
9877     // value-dependent so we can't tell whether it's actually narrowing.
9878   case NK_Not_Narrowing:
9879     return false;
9880 
9881   case NK_Constant_Narrowing:
9882     // Implicit conversion to a narrower type, and the value is not a constant
9883     // expression.
9884     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9885         << /*Constant*/ 1
9886         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9887     return true;
9888 
9889   case NK_Variable_Narrowing:
9890     // Implicit conversion to a narrower type, and the value is not a constant
9891     // expression.
9892   case NK_Type_Narrowing:
9893     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9894         << /*Constant*/ 0 << FromType << ToType;
9895     // TODO: It's not a constant expression, but what if the user intended it
9896     // to be? Can we produce notes to help them figure out why it isn't?
9897     return true;
9898   }
9899   llvm_unreachable("unhandled case in switch");
9900 }
9901 
9902 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
9903                                                          ExprResult &LHS,
9904                                                          ExprResult &RHS,
9905                                                          SourceLocation Loc) {
9906   using CCT = ComparisonCategoryType;
9907 
9908   QualType LHSType = LHS.get()->getType();
9909   QualType RHSType = RHS.get()->getType();
9910   // Dig out the original argument type and expression before implicit casts
9911   // were applied. These are the types/expressions we need to check the
9912   // [expr.spaceship] requirements against.
9913   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9914   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9915   QualType LHSStrippedType = LHSStripped.get()->getType();
9916   QualType RHSStrippedType = RHSStripped.get()->getType();
9917 
9918   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9919   // other is not, the program is ill-formed.
9920   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9921     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9922     return QualType();
9923   }
9924 
9925   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9926                     RHSStrippedType->isEnumeralType();
9927   if (NumEnumArgs == 1) {
9928     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9929     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9930     if (OtherTy->hasFloatingRepresentation()) {
9931       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9932       return QualType();
9933     }
9934   }
9935   if (NumEnumArgs == 2) {
9936     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9937     // type E, the operator yields the result of converting the operands
9938     // to the underlying type of E and applying <=> to the converted operands.
9939     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
9940       S.InvalidOperands(Loc, LHS, RHS);
9941       return QualType();
9942     }
9943     QualType IntType =
9944         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
9945     assert(IntType->isArithmeticType());
9946 
9947     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
9948     // promote the boolean type, and all other promotable integer types, to
9949     // avoid this.
9950     if (IntType->isPromotableIntegerType())
9951       IntType = S.Context.getPromotedIntegerType(IntType);
9952 
9953     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
9954     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
9955     LHSType = RHSType = IntType;
9956   }
9957 
9958   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
9959   // usual arithmetic conversions are applied to the operands.
9960   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9961   if (LHS.isInvalid() || RHS.isInvalid())
9962     return QualType();
9963   if (Type.isNull())
9964     return S.InvalidOperands(Loc, LHS, RHS);
9965   assert(Type->isArithmeticType() || Type->isEnumeralType());
9966 
9967   bool HasNarrowing = checkThreeWayNarrowingConversion(
9968       S, Type, LHS.get(), LHSType, LHS.get()->getLocStart());
9969   HasNarrowing |= checkThreeWayNarrowingConversion(
9970       S, Type, RHS.get(), RHSType, RHS.get()->getLocStart());
9971   if (HasNarrowing)
9972     return QualType();
9973 
9974   assert(!Type.isNull() && "composite type for <=> has not been set");
9975 
9976   auto TypeKind = [&]() {
9977     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
9978       if (CT->getElementType()->hasFloatingRepresentation())
9979         return CCT::WeakEquality;
9980       return CCT::StrongEquality;
9981     }
9982     if (Type->isIntegralOrEnumerationType())
9983       return CCT::StrongOrdering;
9984     if (Type->hasFloatingRepresentation())
9985       return CCT::PartialOrdering;
9986     llvm_unreachable("other types are unimplemented");
9987   }();
9988 
9989   return S.CheckComparisonCategoryType(TypeKind, Loc);
9990 }
9991 
9992 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9993                                                  ExprResult &RHS,
9994                                                  SourceLocation Loc,
9995                                                  BinaryOperatorKind Opc) {
9996   if (Opc == BO_Cmp)
9997     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
9998 
9999   // C99 6.5.8p3 / C99 6.5.9p4
10000   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10001   if (LHS.isInvalid() || RHS.isInvalid())
10002     return QualType();
10003   if (Type.isNull())
10004     return S.InvalidOperands(Loc, LHS, RHS);
10005   assert(Type->isArithmeticType() || Type->isEnumeralType());
10006 
10007   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10008 
10009   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10010     return S.InvalidOperands(Loc, LHS, RHS);
10011 
10012   // Check for comparisons of floating point operands using != and ==.
10013   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10014     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10015 
10016   // The result of comparisons is 'bool' in C++, 'int' in C.
10017   return S.Context.getLogicalOperationType();
10018 }
10019 
10020 // C99 6.5.8, C++ [expr.rel]
10021 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10022                                     SourceLocation Loc,
10023                                     BinaryOperatorKind Opc) {
10024   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10025   bool IsThreeWay = Opc == BO_Cmp;
10026   auto IsAnyPointerType = [](ExprResult E) {
10027     QualType Ty = E.get()->getType();
10028     return Ty->isPointerType() || Ty->isMemberPointerType();
10029   };
10030 
10031   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10032   // type, array-to-pointer, ..., conversions are performed on both operands to
10033   // bring them to their composite type.
10034   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10035   // any type-related checks.
10036   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10037     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10038     if (LHS.isInvalid())
10039       return QualType();
10040     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10041     if (RHS.isInvalid())
10042       return QualType();
10043   } else {
10044     LHS = DefaultLvalueConversion(LHS.get());
10045     if (LHS.isInvalid())
10046       return QualType();
10047     RHS = DefaultLvalueConversion(RHS.get());
10048     if (RHS.isInvalid())
10049       return QualType();
10050   }
10051 
10052   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10053 
10054   // Handle vector comparisons separately.
10055   if (LHS.get()->getType()->isVectorType() ||
10056       RHS.get()->getType()->isVectorType())
10057     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10058 
10059   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10060   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10061 
10062   QualType LHSType = LHS.get()->getType();
10063   QualType RHSType = RHS.get()->getType();
10064   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10065       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10066     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10067 
10068   const Expr::NullPointerConstantKind LHSNullKind =
10069       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10070   const Expr::NullPointerConstantKind RHSNullKind =
10071       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10072   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10073   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10074 
10075   auto computeResultTy = [&]() {
10076     if (Opc != BO_Cmp)
10077       return Context.getLogicalOperationType();
10078     assert(getLangOpts().CPlusPlus);
10079     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10080 
10081     QualType CompositeTy = LHS.get()->getType();
10082     assert(!CompositeTy->isReferenceType());
10083 
10084     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10085       return CheckComparisonCategoryType(Kind, Loc);
10086     };
10087 
10088     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10089     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10090     // result is of type std::strong_equality
10091     if (CompositeTy->isFunctionPointerType() ||
10092         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10093       // FIXME: consider making the function pointer case produce
10094       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10095       // and direction polls
10096       return buildResultTy(ComparisonCategoryType::StrongEquality);
10097 
10098     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10099     // pointer type, p <=> q is of type std::strong_ordering.
10100     if (CompositeTy->isPointerType()) {
10101       // P0946R0: Comparisons between a null pointer constant and an object
10102       // pointer result in std::strong_equality
10103       if (LHSIsNull != RHSIsNull)
10104         return buildResultTy(ComparisonCategoryType::StrongEquality);
10105       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10106     }
10107     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10108     // TODO: Extend support for operator<=> to ObjC types.
10109     return InvalidOperands(Loc, LHS, RHS);
10110   };
10111 
10112 
10113   if (!IsRelational && LHSIsNull != RHSIsNull) {
10114     bool IsEquality = Opc == BO_EQ;
10115     if (RHSIsNull)
10116       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10117                                    RHS.get()->getSourceRange());
10118     else
10119       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10120                                    LHS.get()->getSourceRange());
10121   }
10122 
10123   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10124       (RHSType->isIntegerType() && !RHSIsNull)) {
10125     // Skip normal pointer conversion checks in this case; we have better
10126     // diagnostics for this below.
10127   } else if (getLangOpts().CPlusPlus) {
10128     // Equality comparison of a function pointer to a void pointer is invalid,
10129     // but we allow it as an extension.
10130     // FIXME: If we really want to allow this, should it be part of composite
10131     // pointer type computation so it works in conditionals too?
10132     if (!IsRelational &&
10133         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10134          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10135       // This is a gcc extension compatibility comparison.
10136       // In a SFINAE context, we treat this as a hard error to maintain
10137       // conformance with the C++ standard.
10138       diagnoseFunctionPointerToVoidComparison(
10139           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10140 
10141       if (isSFINAEContext())
10142         return QualType();
10143 
10144       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10145       return computeResultTy();
10146     }
10147 
10148     // C++ [expr.eq]p2:
10149     //   If at least one operand is a pointer [...] bring them to their
10150     //   composite pointer type.
10151     // C++ [expr.spaceship]p6
10152     //  If at least one of the operands is of pointer type, [...] bring them
10153     //  to their composite pointer type.
10154     // C++ [expr.rel]p2:
10155     //   If both operands are pointers, [...] bring them to their composite
10156     //   pointer type.
10157     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10158             (IsRelational ? 2 : 1) &&
10159         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10160                                          RHSType->isObjCObjectPointerType()))) {
10161       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10162         return QualType();
10163       return computeResultTy();
10164     }
10165   } else if (LHSType->isPointerType() &&
10166              RHSType->isPointerType()) { // C99 6.5.8p2
10167     // All of the following pointer-related warnings are GCC extensions, except
10168     // when handling null pointer constants.
10169     QualType LCanPointeeTy =
10170       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10171     QualType RCanPointeeTy =
10172       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10173 
10174     // C99 6.5.9p2 and C99 6.5.8p2
10175     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10176                                    RCanPointeeTy.getUnqualifiedType())) {
10177       // Valid unless a relational comparison of function pointers
10178       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10179         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10180           << LHSType << RHSType << LHS.get()->getSourceRange()
10181           << RHS.get()->getSourceRange();
10182       }
10183     } else if (!IsRelational &&
10184                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10185       // Valid unless comparison between non-null pointer and function pointer
10186       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10187           && !LHSIsNull && !RHSIsNull)
10188         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10189                                                 /*isError*/false);
10190     } else {
10191       // Invalid
10192       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10193     }
10194     if (LCanPointeeTy != RCanPointeeTy) {
10195       // Treat NULL constant as a special case in OpenCL.
10196       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10197         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10198         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10199           Diag(Loc,
10200                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10201               << LHSType << RHSType << 0 /* comparison */
10202               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10203         }
10204       }
10205       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10206       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10207       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10208                                                : CK_BitCast;
10209       if (LHSIsNull && !RHSIsNull)
10210         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10211       else
10212         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10213     }
10214     return computeResultTy();
10215   }
10216 
10217   if (getLangOpts().CPlusPlus) {
10218     // C++ [expr.eq]p4:
10219     //   Two operands of type std::nullptr_t or one operand of type
10220     //   std::nullptr_t and the other a null pointer constant compare equal.
10221     if (!IsRelational && LHSIsNull && RHSIsNull) {
10222       if (LHSType->isNullPtrType()) {
10223         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10224         return computeResultTy();
10225       }
10226       if (RHSType->isNullPtrType()) {
10227         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10228         return computeResultTy();
10229       }
10230     }
10231 
10232     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10233     // These aren't covered by the composite pointer type rules.
10234     if (!IsRelational && RHSType->isNullPtrType() &&
10235         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10236       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10237       return computeResultTy();
10238     }
10239     if (!IsRelational && LHSType->isNullPtrType() &&
10240         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10241       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10242       return computeResultTy();
10243     }
10244 
10245     if (IsRelational &&
10246         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10247          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10248       // HACK: Relational comparison of nullptr_t against a pointer type is
10249       // invalid per DR583, but we allow it within std::less<> and friends,
10250       // since otherwise common uses of it break.
10251       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10252       // friends to have std::nullptr_t overload candidates.
10253       DeclContext *DC = CurContext;
10254       if (isa<FunctionDecl>(DC))
10255         DC = DC->getParent();
10256       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10257         if (CTSD->isInStdNamespace() &&
10258             llvm::StringSwitch<bool>(CTSD->getName())
10259                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10260                 .Default(false)) {
10261           if (RHSType->isNullPtrType())
10262             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10263           else
10264             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10265           return computeResultTy();
10266         }
10267       }
10268     }
10269 
10270     // C++ [expr.eq]p2:
10271     //   If at least one operand is a pointer to member, [...] bring them to
10272     //   their composite pointer type.
10273     if (!IsRelational &&
10274         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10275       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10276         return QualType();
10277       else
10278         return computeResultTy();
10279     }
10280   }
10281 
10282   // Handle block pointer types.
10283   if (!IsRelational && LHSType->isBlockPointerType() &&
10284       RHSType->isBlockPointerType()) {
10285     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10286     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10287 
10288     if (!LHSIsNull && !RHSIsNull &&
10289         !Context.typesAreCompatible(lpointee, rpointee)) {
10290       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10291         << LHSType << RHSType << LHS.get()->getSourceRange()
10292         << RHS.get()->getSourceRange();
10293     }
10294     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10295     return computeResultTy();
10296   }
10297 
10298   // Allow block pointers to be compared with null pointer constants.
10299   if (!IsRelational
10300       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10301           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10302     if (!LHSIsNull && !RHSIsNull) {
10303       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10304              ->getPointeeType()->isVoidType())
10305             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10306                 ->getPointeeType()->isVoidType())))
10307         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10308           << LHSType << RHSType << LHS.get()->getSourceRange()
10309           << RHS.get()->getSourceRange();
10310     }
10311     if (LHSIsNull && !RHSIsNull)
10312       LHS = ImpCastExprToType(LHS.get(), RHSType,
10313                               RHSType->isPointerType() ? CK_BitCast
10314                                 : CK_AnyPointerToBlockPointerCast);
10315     else
10316       RHS = ImpCastExprToType(RHS.get(), LHSType,
10317                               LHSType->isPointerType() ? CK_BitCast
10318                                 : CK_AnyPointerToBlockPointerCast);
10319     return computeResultTy();
10320   }
10321 
10322   if (LHSType->isObjCObjectPointerType() ||
10323       RHSType->isObjCObjectPointerType()) {
10324     const PointerType *LPT = LHSType->getAs<PointerType>();
10325     const PointerType *RPT = RHSType->getAs<PointerType>();
10326     if (LPT || RPT) {
10327       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10328       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10329 
10330       if (!LPtrToVoid && !RPtrToVoid &&
10331           !Context.typesAreCompatible(LHSType, RHSType)) {
10332         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10333                                           /*isError*/false);
10334       }
10335       if (LHSIsNull && !RHSIsNull) {
10336         Expr *E = LHS.get();
10337         if (getLangOpts().ObjCAutoRefCount)
10338           CheckObjCConversion(SourceRange(), RHSType, E,
10339                               CCK_ImplicitConversion);
10340         LHS = ImpCastExprToType(E, RHSType,
10341                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10342       }
10343       else {
10344         Expr *E = RHS.get();
10345         if (getLangOpts().ObjCAutoRefCount)
10346           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10347                               /*Diagnose=*/true,
10348                               /*DiagnoseCFAudited=*/false, Opc);
10349         RHS = ImpCastExprToType(E, LHSType,
10350                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10351       }
10352       return computeResultTy();
10353     }
10354     if (LHSType->isObjCObjectPointerType() &&
10355         RHSType->isObjCObjectPointerType()) {
10356       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10357         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10358                                           /*isError*/false);
10359       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10360         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10361 
10362       if (LHSIsNull && !RHSIsNull)
10363         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10364       else
10365         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10366       return computeResultTy();
10367     }
10368 
10369     if (!IsRelational && LHSType->isBlockPointerType() &&
10370         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10371       LHS = ImpCastExprToType(LHS.get(), RHSType,
10372                               CK_BlockPointerToObjCPointerCast);
10373       return computeResultTy();
10374     } else if (!IsRelational &&
10375                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10376                RHSType->isBlockPointerType()) {
10377       RHS = ImpCastExprToType(RHS.get(), LHSType,
10378                               CK_BlockPointerToObjCPointerCast);
10379       return computeResultTy();
10380     }
10381   }
10382   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10383       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10384     unsigned DiagID = 0;
10385     bool isError = false;
10386     if (LangOpts.DebuggerSupport) {
10387       // Under a debugger, allow the comparison of pointers to integers,
10388       // since users tend to want to compare addresses.
10389     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10390                (RHSIsNull && RHSType->isIntegerType())) {
10391       if (IsRelational) {
10392         isError = getLangOpts().CPlusPlus;
10393         DiagID =
10394           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10395                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10396       }
10397     } else if (getLangOpts().CPlusPlus) {
10398       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10399       isError = true;
10400     } else if (IsRelational)
10401       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10402     else
10403       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10404 
10405     if (DiagID) {
10406       Diag(Loc, DiagID)
10407         << LHSType << RHSType << LHS.get()->getSourceRange()
10408         << RHS.get()->getSourceRange();
10409       if (isError)
10410         return QualType();
10411     }
10412 
10413     if (LHSType->isIntegerType())
10414       LHS = ImpCastExprToType(LHS.get(), RHSType,
10415                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10416     else
10417       RHS = ImpCastExprToType(RHS.get(), LHSType,
10418                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10419     return computeResultTy();
10420   }
10421 
10422   // Handle block pointers.
10423   if (!IsRelational && RHSIsNull
10424       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10425     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10426     return computeResultTy();
10427   }
10428   if (!IsRelational && LHSIsNull
10429       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10430     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10431     return computeResultTy();
10432   }
10433 
10434   if (getLangOpts().OpenCLVersion >= 200) {
10435     if (LHSIsNull && RHSType->isQueueT()) {
10436       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10437       return computeResultTy();
10438     }
10439 
10440     if (LHSType->isQueueT() && RHSIsNull) {
10441       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10442       return computeResultTy();
10443     }
10444   }
10445 
10446   return InvalidOperands(Loc, LHS, RHS);
10447 }
10448 
10449 // Return a signed ext_vector_type that is of identical size and number of
10450 // elements. For floating point vectors, return an integer type of identical
10451 // size and number of elements. In the non ext_vector_type case, search from
10452 // the largest type to the smallest type to avoid cases where long long == long,
10453 // where long gets picked over long long.
10454 QualType Sema::GetSignedVectorType(QualType V) {
10455   const VectorType *VTy = V->getAs<VectorType>();
10456   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10457 
10458   if (isa<ExtVectorType>(VTy)) {
10459     if (TypeSize == Context.getTypeSize(Context.CharTy))
10460       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10461     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10462       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10463     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10464       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10465     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10466       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10467     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10468            "Unhandled vector element size in vector compare");
10469     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10470   }
10471 
10472   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10473     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10474                                  VectorType::GenericVector);
10475   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10476     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10477                                  VectorType::GenericVector);
10478   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10479     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10480                                  VectorType::GenericVector);
10481   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10482     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10483                                  VectorType::GenericVector);
10484   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10485          "Unhandled vector element size in vector compare");
10486   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10487                                VectorType::GenericVector);
10488 }
10489 
10490 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10491 /// operates on extended vector types.  Instead of producing an IntTy result,
10492 /// like a scalar comparison, a vector comparison produces a vector of integer
10493 /// types.
10494 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10495                                           SourceLocation Loc,
10496                                           BinaryOperatorKind Opc) {
10497   // Check to make sure we're operating on vectors of the same type and width,
10498   // Allowing one side to be a scalar of element type.
10499   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10500                               /*AllowBothBool*/true,
10501                               /*AllowBoolConversions*/getLangOpts().ZVector);
10502   if (vType.isNull())
10503     return vType;
10504 
10505   QualType LHSType = LHS.get()->getType();
10506 
10507   // If AltiVec, the comparison results in a numeric type, i.e.
10508   // bool for C++, int for C
10509   if (getLangOpts().AltiVec &&
10510       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10511     return Context.getLogicalOperationType();
10512 
10513   // For non-floating point types, check for self-comparisons of the form
10514   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10515   // often indicate logic errors in the program.
10516   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10517 
10518   // Check for comparisons of floating point operands using != and ==.
10519   if (BinaryOperator::isEqualityOp(Opc) &&
10520       LHSType->hasFloatingRepresentation()) {
10521     assert(RHS.get()->getType()->hasFloatingRepresentation());
10522     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10523   }
10524 
10525   // Return a signed type for the vector.
10526   return GetSignedVectorType(vType);
10527 }
10528 
10529 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10530                                           SourceLocation Loc) {
10531   // Ensure that either both operands are of the same vector type, or
10532   // one operand is of a vector type and the other is of its element type.
10533   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10534                                        /*AllowBothBool*/true,
10535                                        /*AllowBoolConversions*/false);
10536   if (vType.isNull())
10537     return InvalidOperands(Loc, LHS, RHS);
10538   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10539       vType->hasFloatingRepresentation())
10540     return InvalidOperands(Loc, LHS, RHS);
10541   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10542   //        usage of the logical operators && and || with vectors in C. This
10543   //        check could be notionally dropped.
10544   if (!getLangOpts().CPlusPlus &&
10545       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10546     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10547 
10548   return GetSignedVectorType(LHS.get()->getType());
10549 }
10550 
10551 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10552                                            SourceLocation Loc,
10553                                            BinaryOperatorKind Opc) {
10554   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10555 
10556   bool IsCompAssign =
10557       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10558 
10559   if (LHS.get()->getType()->isVectorType() ||
10560       RHS.get()->getType()->isVectorType()) {
10561     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10562         RHS.get()->getType()->hasIntegerRepresentation())
10563       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10564                         /*AllowBothBool*/true,
10565                         /*AllowBoolConversions*/getLangOpts().ZVector);
10566     return InvalidOperands(Loc, LHS, RHS);
10567   }
10568 
10569   if (Opc == BO_And)
10570     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10571 
10572   ExprResult LHSResult = LHS, RHSResult = RHS;
10573   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10574                                                  IsCompAssign);
10575   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10576     return QualType();
10577   LHS = LHSResult.get();
10578   RHS = RHSResult.get();
10579 
10580   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10581     return compType;
10582   return InvalidOperands(Loc, LHS, RHS);
10583 }
10584 
10585 // C99 6.5.[13,14]
10586 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10587                                            SourceLocation Loc,
10588                                            BinaryOperatorKind Opc) {
10589   // Check vector operands differently.
10590   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10591     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10592 
10593   // Diagnose cases where the user write a logical and/or but probably meant a
10594   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10595   // is a constant.
10596   if (LHS.get()->getType()->isIntegerType() &&
10597       !LHS.get()->getType()->isBooleanType() &&
10598       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10599       // Don't warn in macros or template instantiations.
10600       !Loc.isMacroID() && !inTemplateInstantiation()) {
10601     // If the RHS can be constant folded, and if it constant folds to something
10602     // that isn't 0 or 1 (which indicate a potential logical operation that
10603     // happened to fold to true/false) then warn.
10604     // Parens on the RHS are ignored.
10605     llvm::APSInt Result;
10606     if (RHS.get()->EvaluateAsInt(Result, Context))
10607       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10608            !RHS.get()->getExprLoc().isMacroID()) ||
10609           (Result != 0 && Result != 1)) {
10610         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10611           << RHS.get()->getSourceRange()
10612           << (Opc == BO_LAnd ? "&&" : "||");
10613         // Suggest replacing the logical operator with the bitwise version
10614         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10615             << (Opc == BO_LAnd ? "&" : "|")
10616             << FixItHint::CreateReplacement(SourceRange(
10617                                                  Loc, getLocForEndOfToken(Loc)),
10618                                             Opc == BO_LAnd ? "&" : "|");
10619         if (Opc == BO_LAnd)
10620           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10621           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10622               << FixItHint::CreateRemoval(
10623                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10624                               RHS.get()->getLocEnd()));
10625       }
10626   }
10627 
10628   if (!Context.getLangOpts().CPlusPlus) {
10629     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10630     // not operate on the built-in scalar and vector float types.
10631     if (Context.getLangOpts().OpenCL &&
10632         Context.getLangOpts().OpenCLVersion < 120) {
10633       if (LHS.get()->getType()->isFloatingType() ||
10634           RHS.get()->getType()->isFloatingType())
10635         return InvalidOperands(Loc, LHS, RHS);
10636     }
10637 
10638     LHS = UsualUnaryConversions(LHS.get());
10639     if (LHS.isInvalid())
10640       return QualType();
10641 
10642     RHS = UsualUnaryConversions(RHS.get());
10643     if (RHS.isInvalid())
10644       return QualType();
10645 
10646     if (!LHS.get()->getType()->isScalarType() ||
10647         !RHS.get()->getType()->isScalarType())
10648       return InvalidOperands(Loc, LHS, RHS);
10649 
10650     return Context.IntTy;
10651   }
10652 
10653   // The following is safe because we only use this method for
10654   // non-overloadable operands.
10655 
10656   // C++ [expr.log.and]p1
10657   // C++ [expr.log.or]p1
10658   // The operands are both contextually converted to type bool.
10659   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10660   if (LHSRes.isInvalid())
10661     return InvalidOperands(Loc, LHS, RHS);
10662   LHS = LHSRes;
10663 
10664   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10665   if (RHSRes.isInvalid())
10666     return InvalidOperands(Loc, LHS, RHS);
10667   RHS = RHSRes;
10668 
10669   // C++ [expr.log.and]p2
10670   // C++ [expr.log.or]p2
10671   // The result is a bool.
10672   return Context.BoolTy;
10673 }
10674 
10675 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10676   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10677   if (!ME) return false;
10678   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10679   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10680       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10681   if (!Base) return false;
10682   return Base->getMethodDecl() != nullptr;
10683 }
10684 
10685 /// Is the given expression (which must be 'const') a reference to a
10686 /// variable which was originally non-const, but which has become
10687 /// 'const' due to being captured within a block?
10688 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10689 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10690   assert(E->isLValue() && E->getType().isConstQualified());
10691   E = E->IgnoreParens();
10692 
10693   // Must be a reference to a declaration from an enclosing scope.
10694   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10695   if (!DRE) return NCCK_None;
10696   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10697 
10698   // The declaration must be a variable which is not declared 'const'.
10699   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10700   if (!var) return NCCK_None;
10701   if (var->getType().isConstQualified()) return NCCK_None;
10702   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10703 
10704   // Decide whether the first capture was for a block or a lambda.
10705   DeclContext *DC = S.CurContext, *Prev = nullptr;
10706   // Decide whether the first capture was for a block or a lambda.
10707   while (DC) {
10708     // For init-capture, it is possible that the variable belongs to the
10709     // template pattern of the current context.
10710     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10711       if (var->isInitCapture() &&
10712           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10713         break;
10714     if (DC == var->getDeclContext())
10715       break;
10716     Prev = DC;
10717     DC = DC->getParent();
10718   }
10719   // Unless we have an init-capture, we've gone one step too far.
10720   if (!var->isInitCapture())
10721     DC = Prev;
10722   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10723 }
10724 
10725 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10726   Ty = Ty.getNonReferenceType();
10727   if (IsDereference && Ty->isPointerType())
10728     Ty = Ty->getPointeeType();
10729   return !Ty.isConstQualified();
10730 }
10731 
10732 // Update err_typecheck_assign_const and note_typecheck_assign_const
10733 // when this enum is changed.
10734 enum {
10735   ConstFunction,
10736   ConstVariable,
10737   ConstMember,
10738   ConstMethod,
10739   NestedConstMember,
10740   ConstUnknown,  // Keep as last element
10741 };
10742 
10743 /// Emit the "read-only variable not assignable" error and print notes to give
10744 /// more information about why the variable is not assignable, such as pointing
10745 /// to the declaration of a const variable, showing that a method is const, or
10746 /// that the function is returning a const reference.
10747 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10748                                     SourceLocation Loc) {
10749   SourceRange ExprRange = E->getSourceRange();
10750 
10751   // Only emit one error on the first const found.  All other consts will emit
10752   // a note to the error.
10753   bool DiagnosticEmitted = false;
10754 
10755   // Track if the current expression is the result of a dereference, and if the
10756   // next checked expression is the result of a dereference.
10757   bool IsDereference = false;
10758   bool NextIsDereference = false;
10759 
10760   // Loop to process MemberExpr chains.
10761   while (true) {
10762     IsDereference = NextIsDereference;
10763 
10764     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10765     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10766       NextIsDereference = ME->isArrow();
10767       const ValueDecl *VD = ME->getMemberDecl();
10768       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10769         // Mutable fields can be modified even if the class is const.
10770         if (Field->isMutable()) {
10771           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10772           break;
10773         }
10774 
10775         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10776           if (!DiagnosticEmitted) {
10777             S.Diag(Loc, diag::err_typecheck_assign_const)
10778                 << ExprRange << ConstMember << false /*static*/ << Field
10779                 << Field->getType();
10780             DiagnosticEmitted = true;
10781           }
10782           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10783               << ConstMember << false /*static*/ << Field << Field->getType()
10784               << Field->getSourceRange();
10785         }
10786         E = ME->getBase();
10787         continue;
10788       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10789         if (VDecl->getType().isConstQualified()) {
10790           if (!DiagnosticEmitted) {
10791             S.Diag(Loc, diag::err_typecheck_assign_const)
10792                 << ExprRange << ConstMember << true /*static*/ << VDecl
10793                 << VDecl->getType();
10794             DiagnosticEmitted = true;
10795           }
10796           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10797               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10798               << VDecl->getSourceRange();
10799         }
10800         // Static fields do not inherit constness from parents.
10801         break;
10802       }
10803       break; // End MemberExpr
10804     } else if (const ArraySubscriptExpr *ASE =
10805                    dyn_cast<ArraySubscriptExpr>(E)) {
10806       E = ASE->getBase()->IgnoreParenImpCasts();
10807       continue;
10808     } else if (const ExtVectorElementExpr *EVE =
10809                    dyn_cast<ExtVectorElementExpr>(E)) {
10810       E = EVE->getBase()->IgnoreParenImpCasts();
10811       continue;
10812     }
10813     break;
10814   }
10815 
10816   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10817     // Function calls
10818     const FunctionDecl *FD = CE->getDirectCallee();
10819     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10820       if (!DiagnosticEmitted) {
10821         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10822                                                       << ConstFunction << FD;
10823         DiagnosticEmitted = true;
10824       }
10825       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10826              diag::note_typecheck_assign_const)
10827           << ConstFunction << FD << FD->getReturnType()
10828           << FD->getReturnTypeSourceRange();
10829     }
10830   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10831     // Point to variable declaration.
10832     if (const ValueDecl *VD = DRE->getDecl()) {
10833       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10834         if (!DiagnosticEmitted) {
10835           S.Diag(Loc, diag::err_typecheck_assign_const)
10836               << ExprRange << ConstVariable << VD << VD->getType();
10837           DiagnosticEmitted = true;
10838         }
10839         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10840             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10841       }
10842     }
10843   } else if (isa<CXXThisExpr>(E)) {
10844     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10845       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10846         if (MD->isConst()) {
10847           if (!DiagnosticEmitted) {
10848             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10849                                                           << ConstMethod << MD;
10850             DiagnosticEmitted = true;
10851           }
10852           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10853               << ConstMethod << MD << MD->getSourceRange();
10854         }
10855       }
10856     }
10857   }
10858 
10859   if (DiagnosticEmitted)
10860     return;
10861 
10862   // Can't determine a more specific message, so display the generic error.
10863   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10864 }
10865 
10866 enum OriginalExprKind {
10867   OEK_Variable,
10868   OEK_Member,
10869   OEK_LValue
10870 };
10871 
10872 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10873                                          const RecordType *Ty,
10874                                          SourceLocation Loc, SourceRange Range,
10875                                          OriginalExprKind OEK,
10876                                          bool &DiagnosticEmitted,
10877                                          bool IsNested = false) {
10878   // We walk the record hierarchy breadth-first to ensure that we print
10879   // diagnostics in field nesting order.
10880   // First, check every field for constness.
10881   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10882     if (Field->getType().isConstQualified()) {
10883       if (!DiagnosticEmitted) {
10884         S.Diag(Loc, diag::err_typecheck_assign_const)
10885             << Range << NestedConstMember << OEK << VD
10886             << IsNested << Field;
10887         DiagnosticEmitted = true;
10888       }
10889       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10890           << NestedConstMember << IsNested << Field
10891           << Field->getType() << Field->getSourceRange();
10892     }
10893   }
10894   // Then, recurse.
10895   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10896     QualType FTy = Field->getType();
10897     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10898       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10899                                    OEK, DiagnosticEmitted, true);
10900   }
10901 }
10902 
10903 /// Emit an error for the case where a record we are trying to assign to has a
10904 /// const-qualified field somewhere in its hierarchy.
10905 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10906                                          SourceLocation Loc) {
10907   QualType Ty = E->getType();
10908   assert(Ty->isRecordType() && "lvalue was not record?");
10909   SourceRange Range = E->getSourceRange();
10910   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10911   bool DiagEmitted = false;
10912 
10913   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10914     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10915             Range, OEK_Member, DiagEmitted);
10916   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10917     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10918             Range, OEK_Variable, DiagEmitted);
10919   else
10920     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10921             Range, OEK_LValue, DiagEmitted);
10922   if (!DiagEmitted)
10923     DiagnoseConstAssignment(S, E, Loc);
10924 }
10925 
10926 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10927 /// emit an error and return true.  If so, return false.
10928 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10929   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10930 
10931   S.CheckShadowingDeclModification(E, Loc);
10932 
10933   SourceLocation OrigLoc = Loc;
10934   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10935                                                               &Loc);
10936   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10937     IsLV = Expr::MLV_InvalidMessageExpression;
10938   if (IsLV == Expr::MLV_Valid)
10939     return false;
10940 
10941   unsigned DiagID = 0;
10942   bool NeedType = false;
10943   switch (IsLV) { // C99 6.5.16p2
10944   case Expr::MLV_ConstQualified:
10945     // Use a specialized diagnostic when we're assigning to an object
10946     // from an enclosing function or block.
10947     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10948       if (NCCK == NCCK_Block)
10949         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10950       else
10951         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10952       break;
10953     }
10954 
10955     // In ARC, use some specialized diagnostics for occasions where we
10956     // infer 'const'.  These are always pseudo-strong variables.
10957     if (S.getLangOpts().ObjCAutoRefCount) {
10958       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10959       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10960         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10961 
10962         // Use the normal diagnostic if it's pseudo-__strong but the
10963         // user actually wrote 'const'.
10964         if (var->isARCPseudoStrong() &&
10965             (!var->getTypeSourceInfo() ||
10966              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10967           // There are two pseudo-strong cases:
10968           //  - self
10969           ObjCMethodDecl *method = S.getCurMethodDecl();
10970           if (method && var == method->getSelfDecl())
10971             DiagID = method->isClassMethod()
10972               ? diag::err_typecheck_arc_assign_self_class_method
10973               : diag::err_typecheck_arc_assign_self;
10974 
10975           //  - fast enumeration variables
10976           else
10977             DiagID = diag::err_typecheck_arr_assign_enumeration;
10978 
10979           SourceRange Assign;
10980           if (Loc != OrigLoc)
10981             Assign = SourceRange(OrigLoc, OrigLoc);
10982           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10983           // We need to preserve the AST regardless, so migration tool
10984           // can do its job.
10985           return false;
10986         }
10987       }
10988     }
10989 
10990     // If none of the special cases above are triggered, then this is a
10991     // simple const assignment.
10992     if (DiagID == 0) {
10993       DiagnoseConstAssignment(S, E, Loc);
10994       return true;
10995     }
10996 
10997     break;
10998   case Expr::MLV_ConstAddrSpace:
10999     DiagnoseConstAssignment(S, E, Loc);
11000     return true;
11001   case Expr::MLV_ConstQualifiedField:
11002     DiagnoseRecursiveConstFields(S, E, Loc);
11003     return true;
11004   case Expr::MLV_ArrayType:
11005   case Expr::MLV_ArrayTemporary:
11006     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11007     NeedType = true;
11008     break;
11009   case Expr::MLV_NotObjectType:
11010     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11011     NeedType = true;
11012     break;
11013   case Expr::MLV_LValueCast:
11014     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11015     break;
11016   case Expr::MLV_Valid:
11017     llvm_unreachable("did not take early return for MLV_Valid");
11018   case Expr::MLV_InvalidExpression:
11019   case Expr::MLV_MemberFunction:
11020   case Expr::MLV_ClassTemporary:
11021     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11022     break;
11023   case Expr::MLV_IncompleteType:
11024   case Expr::MLV_IncompleteVoidType:
11025     return S.RequireCompleteType(Loc, E->getType(),
11026              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11027   case Expr::MLV_DuplicateVectorComponents:
11028     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11029     break;
11030   case Expr::MLV_NoSetterProperty:
11031     llvm_unreachable("readonly properties should be processed differently");
11032   case Expr::MLV_InvalidMessageExpression:
11033     DiagID = diag::err_readonly_message_assignment;
11034     break;
11035   case Expr::MLV_SubObjCPropertySetting:
11036     DiagID = diag::err_no_subobject_property_setting;
11037     break;
11038   }
11039 
11040   SourceRange Assign;
11041   if (Loc != OrigLoc)
11042     Assign = SourceRange(OrigLoc, OrigLoc);
11043   if (NeedType)
11044     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11045   else
11046     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11047   return true;
11048 }
11049 
11050 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11051                                          SourceLocation Loc,
11052                                          Sema &Sema) {
11053   if (Sema.inTemplateInstantiation())
11054     return;
11055   if (Sema.isUnevaluatedContext())
11056     return;
11057   if (Loc.isInvalid() || Loc.isMacroID())
11058     return;
11059   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11060     return;
11061 
11062   // C / C++ fields
11063   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11064   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11065   if (ML && MR) {
11066     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11067       return;
11068     const ValueDecl *LHSDecl =
11069         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11070     const ValueDecl *RHSDecl =
11071         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11072     if (LHSDecl != RHSDecl)
11073       return;
11074     if (LHSDecl->getType().isVolatileQualified())
11075       return;
11076     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11077       if (RefTy->getPointeeType().isVolatileQualified())
11078         return;
11079 
11080     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11081   }
11082 
11083   // Objective-C instance variables
11084   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11085   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11086   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11087     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11088     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11089     if (RL && RR && RL->getDecl() == RR->getDecl())
11090       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11091   }
11092 }
11093 
11094 // C99 6.5.16.1
11095 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11096                                        SourceLocation Loc,
11097                                        QualType CompoundType) {
11098   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11099 
11100   // Verify that LHS is a modifiable lvalue, and emit error if not.
11101   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11102     return QualType();
11103 
11104   QualType LHSType = LHSExpr->getType();
11105   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11106                                              CompoundType;
11107   // OpenCL v1.2 s6.1.1.1 p2:
11108   // The half data type can only be used to declare a pointer to a buffer that
11109   // contains half values
11110   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11111     LHSType->isHalfType()) {
11112     Diag(Loc, diag::err_opencl_half_load_store) << 1
11113         << LHSType.getUnqualifiedType();
11114     return QualType();
11115   }
11116 
11117   AssignConvertType ConvTy;
11118   if (CompoundType.isNull()) {
11119     Expr *RHSCheck = RHS.get();
11120 
11121     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11122 
11123     QualType LHSTy(LHSType);
11124     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11125     if (RHS.isInvalid())
11126       return QualType();
11127     // Special case of NSObject attributes on c-style pointer types.
11128     if (ConvTy == IncompatiblePointer &&
11129         ((Context.isObjCNSObjectType(LHSType) &&
11130           RHSType->isObjCObjectPointerType()) ||
11131          (Context.isObjCNSObjectType(RHSType) &&
11132           LHSType->isObjCObjectPointerType())))
11133       ConvTy = Compatible;
11134 
11135     if (ConvTy == Compatible &&
11136         LHSType->isObjCObjectType())
11137         Diag(Loc, diag::err_objc_object_assignment)
11138           << LHSType;
11139 
11140     // If the RHS is a unary plus or minus, check to see if they = and + are
11141     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11142     // instead of "x += 4".
11143     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11144       RHSCheck = ICE->getSubExpr();
11145     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11146       if ((UO->getOpcode() == UO_Plus ||
11147            UO->getOpcode() == UO_Minus) &&
11148           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11149           // Only if the two operators are exactly adjacent.
11150           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11151           // And there is a space or other character before the subexpr of the
11152           // unary +/-.  We don't want to warn on "x=-1".
11153           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
11154           UO->getSubExpr()->getLocStart().isFileID()) {
11155         Diag(Loc, diag::warn_not_compound_assign)
11156           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11157           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11158       }
11159     }
11160 
11161     if (ConvTy == Compatible) {
11162       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11163         // Warn about retain cycles where a block captures the LHS, but
11164         // not if the LHS is a simple variable into which the block is
11165         // being stored...unless that variable can be captured by reference!
11166         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11167         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11168         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11169           checkRetainCycles(LHSExpr, RHS.get());
11170       }
11171 
11172       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11173           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11174         // It is safe to assign a weak reference into a strong variable.
11175         // Although this code can still have problems:
11176         //   id x = self.weakProp;
11177         //   id y = self.weakProp;
11178         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11179         // paths through the function. This should be revisited if
11180         // -Wrepeated-use-of-weak is made flow-sensitive.
11181         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11182         // variable, which will be valid for the current autorelease scope.
11183         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11184                              RHS.get()->getLocStart()))
11185           getCurFunction()->markSafeWeakUse(RHS.get());
11186 
11187       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11188         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11189       }
11190     }
11191   } else {
11192     // Compound assignment "x += y"
11193     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11194   }
11195 
11196   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11197                                RHS.get(), AA_Assigning))
11198     return QualType();
11199 
11200   CheckForNullPointerDereference(*this, LHSExpr);
11201 
11202   // C99 6.5.16p3: The type of an assignment expression is the type of the
11203   // left operand unless the left operand has qualified type, in which case
11204   // it is the unqualified version of the type of the left operand.
11205   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11206   // is converted to the type of the assignment expression (above).
11207   // C++ 5.17p1: the type of the assignment expression is that of its left
11208   // operand.
11209   return (getLangOpts().CPlusPlus
11210           ? LHSType : LHSType.getUnqualifiedType());
11211 }
11212 
11213 // Only ignore explicit casts to void.
11214 static bool IgnoreCommaOperand(const Expr *E) {
11215   E = E->IgnoreParens();
11216 
11217   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11218     if (CE->getCastKind() == CK_ToVoid) {
11219       return true;
11220     }
11221   }
11222 
11223   return false;
11224 }
11225 
11226 // Look for instances where it is likely the comma operator is confused with
11227 // another operator.  There is a whitelist of acceptable expressions for the
11228 // left hand side of the comma operator, otherwise emit a warning.
11229 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11230   // No warnings in macros
11231   if (Loc.isMacroID())
11232     return;
11233 
11234   // Don't warn in template instantiations.
11235   if (inTemplateInstantiation())
11236     return;
11237 
11238   // Scope isn't fine-grained enough to whitelist the specific cases, so
11239   // instead, skip more than needed, then call back into here with the
11240   // CommaVisitor in SemaStmt.cpp.
11241   // The whitelisted locations are the initialization and increment portions
11242   // of a for loop.  The additional checks are on the condition of
11243   // if statements, do/while loops, and for loops.
11244   const unsigned ForIncrementFlags =
11245       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
11246   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11247   const unsigned ScopeFlags = getCurScope()->getFlags();
11248   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11249       (ScopeFlags & ForInitFlags) == ForInitFlags)
11250     return;
11251 
11252   // If there are multiple comma operators used together, get the RHS of the
11253   // of the comma operator as the LHS.
11254   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11255     if (BO->getOpcode() != BO_Comma)
11256       break;
11257     LHS = BO->getRHS();
11258   }
11259 
11260   // Only allow some expressions on LHS to not warn.
11261   if (IgnoreCommaOperand(LHS))
11262     return;
11263 
11264   Diag(Loc, diag::warn_comma_operator);
11265   Diag(LHS->getLocStart(), diag::note_cast_to_void)
11266       << LHS->getSourceRange()
11267       << FixItHint::CreateInsertion(LHS->getLocStart(),
11268                                     LangOpts.CPlusPlus ? "static_cast<void>("
11269                                                        : "(void)(")
11270       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
11271                                     ")");
11272 }
11273 
11274 // C99 6.5.17
11275 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11276                                    SourceLocation Loc) {
11277   LHS = S.CheckPlaceholderExpr(LHS.get());
11278   RHS = S.CheckPlaceholderExpr(RHS.get());
11279   if (LHS.isInvalid() || RHS.isInvalid())
11280     return QualType();
11281 
11282   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11283   // operands, but not unary promotions.
11284   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11285 
11286   // So we treat the LHS as a ignored value, and in C++ we allow the
11287   // containing site to determine what should be done with the RHS.
11288   LHS = S.IgnoredValueConversions(LHS.get());
11289   if (LHS.isInvalid())
11290     return QualType();
11291 
11292   S.DiagnoseUnusedExprResult(LHS.get());
11293 
11294   if (!S.getLangOpts().CPlusPlus) {
11295     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11296     if (RHS.isInvalid())
11297       return QualType();
11298     if (!RHS.get()->getType()->isVoidType())
11299       S.RequireCompleteType(Loc, RHS.get()->getType(),
11300                             diag::err_incomplete_type);
11301   }
11302 
11303   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11304     S.DiagnoseCommaOperator(LHS.get(), Loc);
11305 
11306   return RHS.get()->getType();
11307 }
11308 
11309 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11310 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11311 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11312                                                ExprValueKind &VK,
11313                                                ExprObjectKind &OK,
11314                                                SourceLocation OpLoc,
11315                                                bool IsInc, bool IsPrefix) {
11316   if (Op->isTypeDependent())
11317     return S.Context.DependentTy;
11318 
11319   QualType ResType = Op->getType();
11320   // Atomic types can be used for increment / decrement where the non-atomic
11321   // versions can, so ignore the _Atomic() specifier for the purpose of
11322   // checking.
11323   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11324     ResType = ResAtomicType->getValueType();
11325 
11326   assert(!ResType.isNull() && "no type for increment/decrement expression");
11327 
11328   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11329     // Decrement of bool is not allowed.
11330     if (!IsInc) {
11331       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11332       return QualType();
11333     }
11334     // Increment of bool sets it to true, but is deprecated.
11335     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11336                                               : diag::warn_increment_bool)
11337       << Op->getSourceRange();
11338   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11339     // Error on enum increments and decrements in C++ mode
11340     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11341     return QualType();
11342   } else if (ResType->isRealType()) {
11343     // OK!
11344   } else if (ResType->isPointerType()) {
11345     // C99 6.5.2.4p2, 6.5.6p2
11346     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11347       return QualType();
11348   } else if (ResType->isObjCObjectPointerType()) {
11349     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11350     // Otherwise, we just need a complete type.
11351     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11352         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11353       return QualType();
11354   } else if (ResType->isAnyComplexType()) {
11355     // C99 does not support ++/-- on complex types, we allow as an extension.
11356     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11357       << ResType << Op->getSourceRange();
11358   } else if (ResType->isPlaceholderType()) {
11359     ExprResult PR = S.CheckPlaceholderExpr(Op);
11360     if (PR.isInvalid()) return QualType();
11361     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11362                                           IsInc, IsPrefix);
11363   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11364     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11365   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11366              (ResType->getAs<VectorType>()->getVectorKind() !=
11367               VectorType::AltiVecBool)) {
11368     // The z vector extensions allow ++ and -- for non-bool vectors.
11369   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11370             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11371     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11372   } else {
11373     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11374       << ResType << int(IsInc) << Op->getSourceRange();
11375     return QualType();
11376   }
11377   // At this point, we know we have a real, complex or pointer type.
11378   // Now make sure the operand is a modifiable lvalue.
11379   if (CheckForModifiableLvalue(Op, OpLoc, S))
11380     return QualType();
11381   // In C++, a prefix increment is the same type as the operand. Otherwise
11382   // (in C or with postfix), the increment is the unqualified type of the
11383   // operand.
11384   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11385     VK = VK_LValue;
11386     OK = Op->getObjectKind();
11387     return ResType;
11388   } else {
11389     VK = VK_RValue;
11390     return ResType.getUnqualifiedType();
11391   }
11392 }
11393 
11394 
11395 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11396 /// This routine allows us to typecheck complex/recursive expressions
11397 /// where the declaration is needed for type checking. We only need to
11398 /// handle cases when the expression references a function designator
11399 /// or is an lvalue. Here are some examples:
11400 ///  - &(x) => x
11401 ///  - &*****f => f for f a function designator.
11402 ///  - &s.xx => s
11403 ///  - &s.zz[1].yy -> s, if zz is an array
11404 ///  - *(x + 1) -> x, if x is an array
11405 ///  - &"123"[2] -> 0
11406 ///  - & __real__ x -> x
11407 static ValueDecl *getPrimaryDecl(Expr *E) {
11408   switch (E->getStmtClass()) {
11409   case Stmt::DeclRefExprClass:
11410     return cast<DeclRefExpr>(E)->getDecl();
11411   case Stmt::MemberExprClass:
11412     // If this is an arrow operator, the address is an offset from
11413     // the base's value, so the object the base refers to is
11414     // irrelevant.
11415     if (cast<MemberExpr>(E)->isArrow())
11416       return nullptr;
11417     // Otherwise, the expression refers to a part of the base
11418     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11419   case Stmt::ArraySubscriptExprClass: {
11420     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11421     // promotion of register arrays earlier.
11422     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11423     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11424       if (ICE->getSubExpr()->getType()->isArrayType())
11425         return getPrimaryDecl(ICE->getSubExpr());
11426     }
11427     return nullptr;
11428   }
11429   case Stmt::UnaryOperatorClass: {
11430     UnaryOperator *UO = cast<UnaryOperator>(E);
11431 
11432     switch(UO->getOpcode()) {
11433     case UO_Real:
11434     case UO_Imag:
11435     case UO_Extension:
11436       return getPrimaryDecl(UO->getSubExpr());
11437     default:
11438       return nullptr;
11439     }
11440   }
11441   case Stmt::ParenExprClass:
11442     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11443   case Stmt::ImplicitCastExprClass:
11444     // If the result of an implicit cast is an l-value, we care about
11445     // the sub-expression; otherwise, the result here doesn't matter.
11446     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11447   default:
11448     return nullptr;
11449   }
11450 }
11451 
11452 namespace {
11453   enum {
11454     AO_Bit_Field = 0,
11455     AO_Vector_Element = 1,
11456     AO_Property_Expansion = 2,
11457     AO_Register_Variable = 3,
11458     AO_No_Error = 4
11459   };
11460 }
11461 /// Diagnose invalid operand for address of operations.
11462 ///
11463 /// \param Type The type of operand which cannot have its address taken.
11464 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11465                                          Expr *E, unsigned Type) {
11466   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11467 }
11468 
11469 /// CheckAddressOfOperand - The operand of & must be either a function
11470 /// designator or an lvalue designating an object. If it is an lvalue, the
11471 /// object cannot be declared with storage class register or be a bit field.
11472 /// Note: The usual conversions are *not* applied to the operand of the &
11473 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11474 /// In C++, the operand might be an overloaded function name, in which case
11475 /// we allow the '&' but retain the overloaded-function type.
11476 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11477   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11478     if (PTy->getKind() == BuiltinType::Overload) {
11479       Expr *E = OrigOp.get()->IgnoreParens();
11480       if (!isa<OverloadExpr>(E)) {
11481         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11482         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11483           << OrigOp.get()->getSourceRange();
11484         return QualType();
11485       }
11486 
11487       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11488       if (isa<UnresolvedMemberExpr>(Ovl))
11489         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11490           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11491             << OrigOp.get()->getSourceRange();
11492           return QualType();
11493         }
11494 
11495       return Context.OverloadTy;
11496     }
11497 
11498     if (PTy->getKind() == BuiltinType::UnknownAny)
11499       return Context.UnknownAnyTy;
11500 
11501     if (PTy->getKind() == BuiltinType::BoundMember) {
11502       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11503         << OrigOp.get()->getSourceRange();
11504       return QualType();
11505     }
11506 
11507     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11508     if (OrigOp.isInvalid()) return QualType();
11509   }
11510 
11511   if (OrigOp.get()->isTypeDependent())
11512     return Context.DependentTy;
11513 
11514   assert(!OrigOp.get()->getType()->isPlaceholderType());
11515 
11516   // Make sure to ignore parentheses in subsequent checks
11517   Expr *op = OrigOp.get()->IgnoreParens();
11518 
11519   // In OpenCL captures for blocks called as lambda functions
11520   // are located in the private address space. Blocks used in
11521   // enqueue_kernel can be located in a different address space
11522   // depending on a vendor implementation. Thus preventing
11523   // taking an address of the capture to avoid invalid AS casts.
11524   if (LangOpts.OpenCL) {
11525     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11526     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11527       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11528       return QualType();
11529     }
11530   }
11531 
11532   if (getLangOpts().C99) {
11533     // Implement C99-only parts of addressof rules.
11534     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11535       if (uOp->getOpcode() == UO_Deref)
11536         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11537         // (assuming the deref expression is valid).
11538         return uOp->getSubExpr()->getType();
11539     }
11540     // Technically, there should be a check for array subscript
11541     // expressions here, but the result of one is always an lvalue anyway.
11542   }
11543   ValueDecl *dcl = getPrimaryDecl(op);
11544 
11545   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11546     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11547                                            op->getLocStart()))
11548       return QualType();
11549 
11550   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11551   unsigned AddressOfError = AO_No_Error;
11552 
11553   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11554     bool sfinae = (bool)isSFINAEContext();
11555     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11556                                   : diag::ext_typecheck_addrof_temporary)
11557       << op->getType() << op->getSourceRange();
11558     if (sfinae)
11559       return QualType();
11560     // Materialize the temporary as an lvalue so that we can take its address.
11561     OrigOp = op =
11562         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11563   } else if (isa<ObjCSelectorExpr>(op)) {
11564     return Context.getPointerType(op->getType());
11565   } else if (lval == Expr::LV_MemberFunction) {
11566     // If it's an instance method, make a member pointer.
11567     // The expression must have exactly the form &A::foo.
11568 
11569     // If the underlying expression isn't a decl ref, give up.
11570     if (!isa<DeclRefExpr>(op)) {
11571       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11572         << OrigOp.get()->getSourceRange();
11573       return QualType();
11574     }
11575     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11576     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11577 
11578     // The id-expression was parenthesized.
11579     if (OrigOp.get() != DRE) {
11580       Diag(OpLoc, diag::err_parens_pointer_member_function)
11581         << OrigOp.get()->getSourceRange();
11582 
11583     // The method was named without a qualifier.
11584     } else if (!DRE->getQualifier()) {
11585       if (MD->getParent()->getName().empty())
11586         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11587           << op->getSourceRange();
11588       else {
11589         SmallString<32> Str;
11590         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11591         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11592           << op->getSourceRange()
11593           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11594       }
11595     }
11596 
11597     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11598     if (isa<CXXDestructorDecl>(MD))
11599       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11600 
11601     QualType MPTy = Context.getMemberPointerType(
11602         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11603     // Under the MS ABI, lock down the inheritance model now.
11604     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11605       (void)isCompleteType(OpLoc, MPTy);
11606     return MPTy;
11607   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11608     // C99 6.5.3.2p1
11609     // The operand must be either an l-value or a function designator
11610     if (!op->getType()->isFunctionType()) {
11611       // Use a special diagnostic for loads from property references.
11612       if (isa<PseudoObjectExpr>(op)) {
11613         AddressOfError = AO_Property_Expansion;
11614       } else {
11615         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11616           << op->getType() << op->getSourceRange();
11617         return QualType();
11618       }
11619     }
11620   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11621     // The operand cannot be a bit-field
11622     AddressOfError = AO_Bit_Field;
11623   } else if (op->getObjectKind() == OK_VectorComponent) {
11624     // The operand cannot be an element of a vector
11625     AddressOfError = AO_Vector_Element;
11626   } else if (dcl) { // C99 6.5.3.2p1
11627     // We have an lvalue with a decl. Make sure the decl is not declared
11628     // with the register storage-class specifier.
11629     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11630       // in C++ it is not error to take address of a register
11631       // variable (c++03 7.1.1P3)
11632       if (vd->getStorageClass() == SC_Register &&
11633           !getLangOpts().CPlusPlus) {
11634         AddressOfError = AO_Register_Variable;
11635       }
11636     } else if (isa<MSPropertyDecl>(dcl)) {
11637       AddressOfError = AO_Property_Expansion;
11638     } else if (isa<FunctionTemplateDecl>(dcl)) {
11639       return Context.OverloadTy;
11640     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11641       // Okay: we can take the address of a field.
11642       // Could be a pointer to member, though, if there is an explicit
11643       // scope qualifier for the class.
11644       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11645         DeclContext *Ctx = dcl->getDeclContext();
11646         if (Ctx && Ctx->isRecord()) {
11647           if (dcl->getType()->isReferenceType()) {
11648             Diag(OpLoc,
11649                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11650               << dcl->getDeclName() << dcl->getType();
11651             return QualType();
11652           }
11653 
11654           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11655             Ctx = Ctx->getParent();
11656 
11657           QualType MPTy = Context.getMemberPointerType(
11658               op->getType(),
11659               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11660           // Under the MS ABI, lock down the inheritance model now.
11661           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11662             (void)isCompleteType(OpLoc, MPTy);
11663           return MPTy;
11664         }
11665       }
11666     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11667                !isa<BindingDecl>(dcl))
11668       llvm_unreachable("Unknown/unexpected decl type");
11669   }
11670 
11671   if (AddressOfError != AO_No_Error) {
11672     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11673     return QualType();
11674   }
11675 
11676   if (lval == Expr::LV_IncompleteVoidType) {
11677     // Taking the address of a void variable is technically illegal, but we
11678     // allow it in cases which are otherwise valid.
11679     // Example: "extern void x; void* y = &x;".
11680     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11681   }
11682 
11683   // If the operand has type "type", the result has type "pointer to type".
11684   if (op->getType()->isObjCObjectType())
11685     return Context.getObjCObjectPointerType(op->getType());
11686 
11687   CheckAddressOfPackedMember(op);
11688 
11689   return Context.getPointerType(op->getType());
11690 }
11691 
11692 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11693   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11694   if (!DRE)
11695     return;
11696   const Decl *D = DRE->getDecl();
11697   if (!D)
11698     return;
11699   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11700   if (!Param)
11701     return;
11702   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11703     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11704       return;
11705   if (FunctionScopeInfo *FD = S.getCurFunction())
11706     if (!FD->ModifiedNonNullParams.count(Param))
11707       FD->ModifiedNonNullParams.insert(Param);
11708 }
11709 
11710 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11711 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11712                                         SourceLocation OpLoc) {
11713   if (Op->isTypeDependent())
11714     return S.Context.DependentTy;
11715 
11716   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11717   if (ConvResult.isInvalid())
11718     return QualType();
11719   Op = ConvResult.get();
11720   QualType OpTy = Op->getType();
11721   QualType Result;
11722 
11723   if (isa<CXXReinterpretCastExpr>(Op)) {
11724     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11725     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11726                                      Op->getSourceRange());
11727   }
11728 
11729   if (const PointerType *PT = OpTy->getAs<PointerType>())
11730   {
11731     Result = PT->getPointeeType();
11732   }
11733   else if (const ObjCObjectPointerType *OPT =
11734              OpTy->getAs<ObjCObjectPointerType>())
11735     Result = OPT->getPointeeType();
11736   else {
11737     ExprResult PR = S.CheckPlaceholderExpr(Op);
11738     if (PR.isInvalid()) return QualType();
11739     if (PR.get() != Op)
11740       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11741   }
11742 
11743   if (Result.isNull()) {
11744     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11745       << OpTy << Op->getSourceRange();
11746     return QualType();
11747   }
11748 
11749   // Note that per both C89 and C99, indirection is always legal, even if Result
11750   // is an incomplete type or void.  It would be possible to warn about
11751   // dereferencing a void pointer, but it's completely well-defined, and such a
11752   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11753   // for pointers to 'void' but is fine for any other pointer type:
11754   //
11755   // C++ [expr.unary.op]p1:
11756   //   [...] the expression to which [the unary * operator] is applied shall
11757   //   be a pointer to an object type, or a pointer to a function type
11758   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11759     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11760       << OpTy << Op->getSourceRange();
11761 
11762   // Dereferences are usually l-values...
11763   VK = VK_LValue;
11764 
11765   // ...except that certain expressions are never l-values in C.
11766   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11767     VK = VK_RValue;
11768 
11769   return Result;
11770 }
11771 
11772 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11773   BinaryOperatorKind Opc;
11774   switch (Kind) {
11775   default: llvm_unreachable("Unknown binop!");
11776   case tok::periodstar:           Opc = BO_PtrMemD; break;
11777   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11778   case tok::star:                 Opc = BO_Mul; break;
11779   case tok::slash:                Opc = BO_Div; break;
11780   case tok::percent:              Opc = BO_Rem; break;
11781   case tok::plus:                 Opc = BO_Add; break;
11782   case tok::minus:                Opc = BO_Sub; break;
11783   case tok::lessless:             Opc = BO_Shl; break;
11784   case tok::greatergreater:       Opc = BO_Shr; break;
11785   case tok::lessequal:            Opc = BO_LE; break;
11786   case tok::less:                 Opc = BO_LT; break;
11787   case tok::greaterequal:         Opc = BO_GE; break;
11788   case tok::greater:              Opc = BO_GT; break;
11789   case tok::exclaimequal:         Opc = BO_NE; break;
11790   case tok::equalequal:           Opc = BO_EQ; break;
11791   case tok::spaceship:            Opc = BO_Cmp; break;
11792   case tok::amp:                  Opc = BO_And; break;
11793   case tok::caret:                Opc = BO_Xor; break;
11794   case tok::pipe:                 Opc = BO_Or; break;
11795   case tok::ampamp:               Opc = BO_LAnd; break;
11796   case tok::pipepipe:             Opc = BO_LOr; break;
11797   case tok::equal:                Opc = BO_Assign; break;
11798   case tok::starequal:            Opc = BO_MulAssign; break;
11799   case tok::slashequal:           Opc = BO_DivAssign; break;
11800   case tok::percentequal:         Opc = BO_RemAssign; break;
11801   case tok::plusequal:            Opc = BO_AddAssign; break;
11802   case tok::minusequal:           Opc = BO_SubAssign; break;
11803   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11804   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11805   case tok::ampequal:             Opc = BO_AndAssign; break;
11806   case tok::caretequal:           Opc = BO_XorAssign; break;
11807   case tok::pipeequal:            Opc = BO_OrAssign; break;
11808   case tok::comma:                Opc = BO_Comma; break;
11809   }
11810   return Opc;
11811 }
11812 
11813 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11814   tok::TokenKind Kind) {
11815   UnaryOperatorKind Opc;
11816   switch (Kind) {
11817   default: llvm_unreachable("Unknown unary op!");
11818   case tok::plusplus:     Opc = UO_PreInc; break;
11819   case tok::minusminus:   Opc = UO_PreDec; break;
11820   case tok::amp:          Opc = UO_AddrOf; break;
11821   case tok::star:         Opc = UO_Deref; break;
11822   case tok::plus:         Opc = UO_Plus; break;
11823   case tok::minus:        Opc = UO_Minus; break;
11824   case tok::tilde:        Opc = UO_Not; break;
11825   case tok::exclaim:      Opc = UO_LNot; break;
11826   case tok::kw___real:    Opc = UO_Real; break;
11827   case tok::kw___imag:    Opc = UO_Imag; break;
11828   case tok::kw___extension__: Opc = UO_Extension; break;
11829   }
11830   return Opc;
11831 }
11832 
11833 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11834 /// This warning suppressed in the event of macro expansions.
11835 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11836                                    SourceLocation OpLoc, bool IsBuiltin) {
11837   if (S.inTemplateInstantiation())
11838     return;
11839   if (S.isUnevaluatedContext())
11840     return;
11841   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11842     return;
11843   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11844   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11845   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11846   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11847   if (!LHSDeclRef || !RHSDeclRef ||
11848       LHSDeclRef->getLocation().isMacroID() ||
11849       RHSDeclRef->getLocation().isMacroID())
11850     return;
11851   const ValueDecl *LHSDecl =
11852     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11853   const ValueDecl *RHSDecl =
11854     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11855   if (LHSDecl != RHSDecl)
11856     return;
11857   if (LHSDecl->getType().isVolatileQualified())
11858     return;
11859   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11860     if (RefTy->getPointeeType().isVolatileQualified())
11861       return;
11862 
11863   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11864                           : diag::warn_self_assignment_overloaded)
11865       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11866       << RHSExpr->getSourceRange();
11867 }
11868 
11869 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11870 /// is usually indicative of introspection within the Objective-C pointer.
11871 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11872                                           SourceLocation OpLoc) {
11873   if (!S.getLangOpts().ObjC1)
11874     return;
11875 
11876   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11877   const Expr *LHS = L.get();
11878   const Expr *RHS = R.get();
11879 
11880   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11881     ObjCPointerExpr = LHS;
11882     OtherExpr = RHS;
11883   }
11884   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11885     ObjCPointerExpr = RHS;
11886     OtherExpr = LHS;
11887   }
11888 
11889   // This warning is deliberately made very specific to reduce false
11890   // positives with logic that uses '&' for hashing.  This logic mainly
11891   // looks for code trying to introspect into tagged pointers, which
11892   // code should generally never do.
11893   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11894     unsigned Diag = diag::warn_objc_pointer_masking;
11895     // Determine if we are introspecting the result of performSelectorXXX.
11896     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11897     // Special case messages to -performSelector and friends, which
11898     // can return non-pointer values boxed in a pointer value.
11899     // Some clients may wish to silence warnings in this subcase.
11900     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11901       Selector S = ME->getSelector();
11902       StringRef SelArg0 = S.getNameForSlot(0);
11903       if (SelArg0.startswith("performSelector"))
11904         Diag = diag::warn_objc_pointer_masking_performSelector;
11905     }
11906 
11907     S.Diag(OpLoc, Diag)
11908       << ObjCPointerExpr->getSourceRange();
11909   }
11910 }
11911 
11912 static NamedDecl *getDeclFromExpr(Expr *E) {
11913   if (!E)
11914     return nullptr;
11915   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11916     return DRE->getDecl();
11917   if (auto *ME = dyn_cast<MemberExpr>(E))
11918     return ME->getMemberDecl();
11919   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11920     return IRE->getDecl();
11921   return nullptr;
11922 }
11923 
11924 // This helper function promotes a binary operator's operands (which are of a
11925 // half vector type) to a vector of floats and then truncates the result to
11926 // a vector of either half or short.
11927 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11928                                       BinaryOperatorKind Opc, QualType ResultTy,
11929                                       ExprValueKind VK, ExprObjectKind OK,
11930                                       bool IsCompAssign, SourceLocation OpLoc,
11931                                       FPOptions FPFeatures) {
11932   auto &Context = S.getASTContext();
11933   assert((isVector(ResultTy, Context.HalfTy) ||
11934           isVector(ResultTy, Context.ShortTy)) &&
11935          "Result must be a vector of half or short");
11936   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11937          isVector(RHS.get()->getType(), Context.HalfTy) &&
11938          "both operands expected to be a half vector");
11939 
11940   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11941   QualType BinOpResTy = RHS.get()->getType();
11942 
11943   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11944   // change BinOpResTy to a vector of ints.
11945   if (isVector(ResultTy, Context.ShortTy))
11946     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11947 
11948   if (IsCompAssign)
11949     return new (Context) CompoundAssignOperator(
11950         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11951         OpLoc, FPFeatures);
11952 
11953   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11954   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11955                                           VK, OK, OpLoc, FPFeatures);
11956   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11957 }
11958 
11959 static std::pair<ExprResult, ExprResult>
11960 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11961                            Expr *RHSExpr) {
11962   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11963   if (!S.getLangOpts().CPlusPlus) {
11964     // C cannot handle TypoExpr nodes on either side of a binop because it
11965     // doesn't handle dependent types properly, so make sure any TypoExprs have
11966     // been dealt with before checking the operands.
11967     LHS = S.CorrectDelayedTyposInExpr(LHS);
11968     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11969       if (Opc != BO_Assign)
11970         return ExprResult(E);
11971       // Avoid correcting the RHS to the same Expr as the LHS.
11972       Decl *D = getDeclFromExpr(E);
11973       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11974     });
11975   }
11976   return std::make_pair(LHS, RHS);
11977 }
11978 
11979 /// Returns true if conversion between vectors of halfs and vectors of floats
11980 /// is needed.
11981 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11982                                      QualType SrcType) {
11983   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11984          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11985          isVector(SrcType, Ctx.HalfTy);
11986 }
11987 
11988 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11989 /// operator @p Opc at location @c TokLoc. This routine only supports
11990 /// built-in operations; ActOnBinOp handles overloaded operators.
11991 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11992                                     BinaryOperatorKind Opc,
11993                                     Expr *LHSExpr, Expr *RHSExpr) {
11994   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11995     // The syntax only allows initializer lists on the RHS of assignment,
11996     // so we don't need to worry about accepting invalid code for
11997     // non-assignment operators.
11998     // C++11 5.17p9:
11999     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12000     //   of x = {} is x = T().
12001     InitializationKind Kind = InitializationKind::CreateDirectList(
12002         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
12003     InitializedEntity Entity =
12004         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12005     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12006     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12007     if (Init.isInvalid())
12008       return Init;
12009     RHSExpr = Init.get();
12010   }
12011 
12012   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12013   QualType ResultTy;     // Result type of the binary operator.
12014   // The following two variables are used for compound assignment operators
12015   QualType CompLHSTy;    // Type of LHS after promotions for computation
12016   QualType CompResultTy; // Type of computation result
12017   ExprValueKind VK = VK_RValue;
12018   ExprObjectKind OK = OK_Ordinary;
12019   bool ConvertHalfVec = false;
12020 
12021   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12022   if (!LHS.isUsable() || !RHS.isUsable())
12023     return ExprError();
12024 
12025   if (getLangOpts().OpenCL) {
12026     QualType LHSTy = LHSExpr->getType();
12027     QualType RHSTy = RHSExpr->getType();
12028     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12029     // the ATOMIC_VAR_INIT macro.
12030     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12031       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
12032       if (BO_Assign == Opc)
12033         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12034       else
12035         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12036       return ExprError();
12037     }
12038 
12039     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12040     // only with a builtin functions and therefore should be disallowed here.
12041     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12042         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12043         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12044         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12045       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12046       return ExprError();
12047     }
12048   }
12049 
12050   switch (Opc) {
12051   case BO_Assign:
12052     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12053     if (getLangOpts().CPlusPlus &&
12054         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12055       VK = LHS.get()->getValueKind();
12056       OK = LHS.get()->getObjectKind();
12057     }
12058     if (!ResultTy.isNull()) {
12059       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12060       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12061     }
12062     RecordModifiableNonNullParam(*this, LHS.get());
12063     break;
12064   case BO_PtrMemD:
12065   case BO_PtrMemI:
12066     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12067                                             Opc == BO_PtrMemI);
12068     break;
12069   case BO_Mul:
12070   case BO_Div:
12071     ConvertHalfVec = true;
12072     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12073                                            Opc == BO_Div);
12074     break;
12075   case BO_Rem:
12076     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12077     break;
12078   case BO_Add:
12079     ConvertHalfVec = true;
12080     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12081     break;
12082   case BO_Sub:
12083     ConvertHalfVec = true;
12084     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12085     break;
12086   case BO_Shl:
12087   case BO_Shr:
12088     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12089     break;
12090   case BO_LE:
12091   case BO_LT:
12092   case BO_GE:
12093   case BO_GT:
12094     ConvertHalfVec = true;
12095     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12096     break;
12097   case BO_EQ:
12098   case BO_NE:
12099     ConvertHalfVec = true;
12100     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12101     break;
12102   case BO_Cmp:
12103     ConvertHalfVec = true;
12104     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12105     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12106     break;
12107   case BO_And:
12108     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12109     LLVM_FALLTHROUGH;
12110   case BO_Xor:
12111   case BO_Or:
12112     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12113     break;
12114   case BO_LAnd:
12115   case BO_LOr:
12116     ConvertHalfVec = true;
12117     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12118     break;
12119   case BO_MulAssign:
12120   case BO_DivAssign:
12121     ConvertHalfVec = true;
12122     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12123                                                Opc == BO_DivAssign);
12124     CompLHSTy = CompResultTy;
12125     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12126       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12127     break;
12128   case BO_RemAssign:
12129     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12130     CompLHSTy = CompResultTy;
12131     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12132       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12133     break;
12134   case BO_AddAssign:
12135     ConvertHalfVec = true;
12136     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12137     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12138       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12139     break;
12140   case BO_SubAssign:
12141     ConvertHalfVec = true;
12142     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12143     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12144       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12145     break;
12146   case BO_ShlAssign:
12147   case BO_ShrAssign:
12148     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12149     CompLHSTy = CompResultTy;
12150     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12151       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12152     break;
12153   case BO_AndAssign:
12154   case BO_OrAssign: // fallthrough
12155     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12156     LLVM_FALLTHROUGH;
12157   case BO_XorAssign:
12158     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12159     CompLHSTy = CompResultTy;
12160     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12161       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12162     break;
12163   case BO_Comma:
12164     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12165     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12166       VK = RHS.get()->getValueKind();
12167       OK = RHS.get()->getObjectKind();
12168     }
12169     break;
12170   }
12171   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12172     return ExprError();
12173 
12174   // Some of the binary operations require promoting operands of half vector to
12175   // float vectors and truncating the result back to half vector. For now, we do
12176   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12177   // arm64).
12178   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12179          isVector(LHS.get()->getType(), Context.HalfTy) &&
12180          "both sides are half vectors or neither sides are");
12181   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12182                                             LHS.get()->getType());
12183 
12184   // Check for array bounds violations for both sides of the BinaryOperator
12185   CheckArrayAccess(LHS.get());
12186   CheckArrayAccess(RHS.get());
12187 
12188   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12189     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12190                                                  &Context.Idents.get("object_setClass"),
12191                                                  SourceLocation(), LookupOrdinaryName);
12192     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12193       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
12194       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
12195       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
12196       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
12197       FixItHint::CreateInsertion(RHSLocEnd, ")");
12198     }
12199     else
12200       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12201   }
12202   else if (const ObjCIvarRefExpr *OIRE =
12203            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12204     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12205 
12206   // Opc is not a compound assignment if CompResultTy is null.
12207   if (CompResultTy.isNull()) {
12208     if (ConvertHalfVec)
12209       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12210                                  OpLoc, FPFeatures);
12211     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12212                                         OK, OpLoc, FPFeatures);
12213   }
12214 
12215   // Handle compound assignments.
12216   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12217       OK_ObjCProperty) {
12218     VK = VK_LValue;
12219     OK = LHS.get()->getObjectKind();
12220   }
12221 
12222   if (ConvertHalfVec)
12223     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12224                                OpLoc, FPFeatures);
12225 
12226   return new (Context) CompoundAssignOperator(
12227       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12228       OpLoc, FPFeatures);
12229 }
12230 
12231 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12232 /// operators are mixed in a way that suggests that the programmer forgot that
12233 /// comparison operators have higher precedence. The most typical example of
12234 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12235 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12236                                       SourceLocation OpLoc, Expr *LHSExpr,
12237                                       Expr *RHSExpr) {
12238   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12239   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12240 
12241   // Check that one of the sides is a comparison operator and the other isn't.
12242   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12243   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12244   if (isLeftComp == isRightComp)
12245     return;
12246 
12247   // Bitwise operations are sometimes used as eager logical ops.
12248   // Don't diagnose this.
12249   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12250   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12251   if (isLeftBitwise || isRightBitwise)
12252     return;
12253 
12254   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
12255                                                    OpLoc)
12256                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
12257   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12258   SourceRange ParensRange = isLeftComp ?
12259       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
12260     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
12261 
12262   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12263     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12264   SuggestParentheses(Self, OpLoc,
12265     Self.PDiag(diag::note_precedence_silence) << OpStr,
12266     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12267   SuggestParentheses(Self, OpLoc,
12268     Self.PDiag(diag::note_precedence_bitwise_first)
12269       << BinaryOperator::getOpcodeStr(Opc),
12270     ParensRange);
12271 }
12272 
12273 /// It accepts a '&&' expr that is inside a '||' one.
12274 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12275 /// in parentheses.
12276 static void
12277 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12278                                        BinaryOperator *Bop) {
12279   assert(Bop->getOpcode() == BO_LAnd);
12280   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12281       << Bop->getSourceRange() << OpLoc;
12282   SuggestParentheses(Self, Bop->getOperatorLoc(),
12283     Self.PDiag(diag::note_precedence_silence)
12284       << Bop->getOpcodeStr(),
12285     Bop->getSourceRange());
12286 }
12287 
12288 /// Returns true if the given expression can be evaluated as a constant
12289 /// 'true'.
12290 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12291   bool Res;
12292   return !E->isValueDependent() &&
12293          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12294 }
12295 
12296 /// Returns true if the given expression can be evaluated as a constant
12297 /// 'false'.
12298 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12299   bool Res;
12300   return !E->isValueDependent() &&
12301          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12302 }
12303 
12304 /// Look for '&&' in the left hand of a '||' expr.
12305 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12306                                              Expr *LHSExpr, Expr *RHSExpr) {
12307   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12308     if (Bop->getOpcode() == BO_LAnd) {
12309       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12310       if (EvaluatesAsFalse(S, RHSExpr))
12311         return;
12312       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12313       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12314         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12315     } else if (Bop->getOpcode() == BO_LOr) {
12316       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12317         // If it's "a || b && 1 || c" we didn't warn earlier for
12318         // "a || b && 1", but warn now.
12319         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12320           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12321       }
12322     }
12323   }
12324 }
12325 
12326 /// Look for '&&' in the right hand of a '||' expr.
12327 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12328                                              Expr *LHSExpr, Expr *RHSExpr) {
12329   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12330     if (Bop->getOpcode() == BO_LAnd) {
12331       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12332       if (EvaluatesAsFalse(S, LHSExpr))
12333         return;
12334       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12335       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12336         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12337     }
12338   }
12339 }
12340 
12341 /// Look for bitwise op in the left or right hand of a bitwise op with
12342 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12343 /// the '&' expression in parentheses.
12344 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12345                                          SourceLocation OpLoc, Expr *SubExpr) {
12346   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12347     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12348       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12349         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12350         << Bop->getSourceRange() << OpLoc;
12351       SuggestParentheses(S, Bop->getOperatorLoc(),
12352         S.PDiag(diag::note_precedence_silence)
12353           << Bop->getOpcodeStr(),
12354         Bop->getSourceRange());
12355     }
12356   }
12357 }
12358 
12359 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12360                                     Expr *SubExpr, StringRef Shift) {
12361   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12362     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12363       StringRef Op = Bop->getOpcodeStr();
12364       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12365           << Bop->getSourceRange() << OpLoc << Shift << Op;
12366       SuggestParentheses(S, Bop->getOperatorLoc(),
12367           S.PDiag(diag::note_precedence_silence) << Op,
12368           Bop->getSourceRange());
12369     }
12370   }
12371 }
12372 
12373 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12374                                  Expr *LHSExpr, Expr *RHSExpr) {
12375   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12376   if (!OCE)
12377     return;
12378 
12379   FunctionDecl *FD = OCE->getDirectCallee();
12380   if (!FD || !FD->isOverloadedOperator())
12381     return;
12382 
12383   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12384   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12385     return;
12386 
12387   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12388       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12389       << (Kind == OO_LessLess);
12390   SuggestParentheses(S, OCE->getOperatorLoc(),
12391                      S.PDiag(diag::note_precedence_silence)
12392                          << (Kind == OO_LessLess ? "<<" : ">>"),
12393                      OCE->getSourceRange());
12394   SuggestParentheses(S, OpLoc,
12395                      S.PDiag(diag::note_evaluate_comparison_first),
12396                      SourceRange(OCE->getArg(1)->getLocStart(),
12397                                  RHSExpr->getLocEnd()));
12398 }
12399 
12400 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12401 /// precedence.
12402 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12403                                     SourceLocation OpLoc, Expr *LHSExpr,
12404                                     Expr *RHSExpr){
12405   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12406   if (BinaryOperator::isBitwiseOp(Opc))
12407     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12408 
12409   // Diagnose "arg1 & arg2 | arg3"
12410   if ((Opc == BO_Or || Opc == BO_Xor) &&
12411       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12412     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12413     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12414   }
12415 
12416   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12417   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12418   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12419     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12420     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12421   }
12422 
12423   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12424       || Opc == BO_Shr) {
12425     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12426     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12427     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12428   }
12429 
12430   // Warn on overloaded shift operators and comparisons, such as:
12431   // cout << 5 == 4;
12432   if (BinaryOperator::isComparisonOp(Opc))
12433     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12434 }
12435 
12436 // Binary Operators.  'Tok' is the token for the operator.
12437 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12438                             tok::TokenKind Kind,
12439                             Expr *LHSExpr, Expr *RHSExpr) {
12440   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12441   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12442   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12443 
12444   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12445   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12446 
12447   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12448 }
12449 
12450 /// Build an overloaded binary operator expression in the given scope.
12451 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12452                                        BinaryOperatorKind Opc,
12453                                        Expr *LHS, Expr *RHS) {
12454   switch (Opc) {
12455   case BO_Assign:
12456   case BO_DivAssign:
12457   case BO_RemAssign:
12458   case BO_SubAssign:
12459   case BO_AndAssign:
12460   case BO_OrAssign:
12461   case BO_XorAssign:
12462     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12463     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12464     break;
12465   default:
12466     break;
12467   }
12468 
12469   // Find all of the overloaded operators visible from this
12470   // point. We perform both an operator-name lookup from the local
12471   // scope and an argument-dependent lookup based on the types of
12472   // the arguments.
12473   UnresolvedSet<16> Functions;
12474   OverloadedOperatorKind OverOp
12475     = BinaryOperator::getOverloadedOperator(Opc);
12476   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12477     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12478                                    RHS->getType(), Functions);
12479 
12480   // Build the (potentially-overloaded, potentially-dependent)
12481   // binary operation.
12482   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12483 }
12484 
12485 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12486                             BinaryOperatorKind Opc,
12487                             Expr *LHSExpr, Expr *RHSExpr) {
12488   ExprResult LHS, RHS;
12489   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12490   if (!LHS.isUsable() || !RHS.isUsable())
12491     return ExprError();
12492   LHSExpr = LHS.get();
12493   RHSExpr = RHS.get();
12494 
12495   // We want to end up calling one of checkPseudoObjectAssignment
12496   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12497   // both expressions are overloadable or either is type-dependent),
12498   // or CreateBuiltinBinOp (in any other case).  We also want to get
12499   // any placeholder types out of the way.
12500 
12501   // Handle pseudo-objects in the LHS.
12502   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12503     // Assignments with a pseudo-object l-value need special analysis.
12504     if (pty->getKind() == BuiltinType::PseudoObject &&
12505         BinaryOperator::isAssignmentOp(Opc))
12506       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12507 
12508     // Don't resolve overloads if the other type is overloadable.
12509     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12510       // We can't actually test that if we still have a placeholder,
12511       // though.  Fortunately, none of the exceptions we see in that
12512       // code below are valid when the LHS is an overload set.  Note
12513       // that an overload set can be dependently-typed, but it never
12514       // instantiates to having an overloadable type.
12515       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12516       if (resolvedRHS.isInvalid()) return ExprError();
12517       RHSExpr = resolvedRHS.get();
12518 
12519       if (RHSExpr->isTypeDependent() ||
12520           RHSExpr->getType()->isOverloadableType())
12521         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12522     }
12523 
12524     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12525     // template, diagnose the missing 'template' keyword instead of diagnosing
12526     // an invalid use of a bound member function.
12527     //
12528     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12529     // to C++1z [over.over]/1.4, but we already checked for that case above.
12530     if (Opc == BO_LT && inTemplateInstantiation() &&
12531         (pty->getKind() == BuiltinType::BoundMember ||
12532          pty->getKind() == BuiltinType::Overload)) {
12533       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12534       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12535           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12536             return isa<FunctionTemplateDecl>(ND);
12537           })) {
12538         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12539                                 : OE->getNameLoc(),
12540              diag::err_template_kw_missing)
12541           << OE->getName().getAsString() << "";
12542         return ExprError();
12543       }
12544     }
12545 
12546     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12547     if (LHS.isInvalid()) return ExprError();
12548     LHSExpr = LHS.get();
12549   }
12550 
12551   // Handle pseudo-objects in the RHS.
12552   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12553     // An overload in the RHS can potentially be resolved by the type
12554     // being assigned to.
12555     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12556       if (getLangOpts().CPlusPlus &&
12557           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12558            LHSExpr->getType()->isOverloadableType()))
12559         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12560 
12561       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12562     }
12563 
12564     // Don't resolve overloads if the other type is overloadable.
12565     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12566         LHSExpr->getType()->isOverloadableType())
12567       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12568 
12569     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12570     if (!resolvedRHS.isUsable()) return ExprError();
12571     RHSExpr = resolvedRHS.get();
12572   }
12573 
12574   if (getLangOpts().CPlusPlus) {
12575     // If either expression is type-dependent, always build an
12576     // overloaded op.
12577     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12578       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12579 
12580     // Otherwise, build an overloaded op if either expression has an
12581     // overloadable type.
12582     if (LHSExpr->getType()->isOverloadableType() ||
12583         RHSExpr->getType()->isOverloadableType())
12584       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12585   }
12586 
12587   // Build a built-in binary operation.
12588   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12589 }
12590 
12591 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12592   if (T.isNull() || T->isDependentType())
12593     return false;
12594 
12595   if (!T->isPromotableIntegerType())
12596     return true;
12597 
12598   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12599 }
12600 
12601 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12602                                       UnaryOperatorKind Opc,
12603                                       Expr *InputExpr) {
12604   ExprResult Input = InputExpr;
12605   ExprValueKind VK = VK_RValue;
12606   ExprObjectKind OK = OK_Ordinary;
12607   QualType resultType;
12608   bool CanOverflow = false;
12609 
12610   bool ConvertHalfVec = false;
12611   if (getLangOpts().OpenCL) {
12612     QualType Ty = InputExpr->getType();
12613     // The only legal unary operation for atomics is '&'.
12614     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12615     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12616     // only with a builtin functions and therefore should be disallowed here.
12617         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12618         || Ty->isBlockPointerType())) {
12619       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12620                        << InputExpr->getType()
12621                        << Input.get()->getSourceRange());
12622     }
12623   }
12624   switch (Opc) {
12625   case UO_PreInc:
12626   case UO_PreDec:
12627   case UO_PostInc:
12628   case UO_PostDec:
12629     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12630                                                 OpLoc,
12631                                                 Opc == UO_PreInc ||
12632                                                 Opc == UO_PostInc,
12633                                                 Opc == UO_PreInc ||
12634                                                 Opc == UO_PreDec);
12635     CanOverflow = isOverflowingIntegerType(Context, resultType);
12636     break;
12637   case UO_AddrOf:
12638     resultType = CheckAddressOfOperand(Input, OpLoc);
12639     RecordModifiableNonNullParam(*this, InputExpr);
12640     break;
12641   case UO_Deref: {
12642     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12643     if (Input.isInvalid()) return ExprError();
12644     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12645     break;
12646   }
12647   case UO_Plus:
12648   case UO_Minus:
12649     CanOverflow = Opc == UO_Minus &&
12650                   isOverflowingIntegerType(Context, Input.get()->getType());
12651     Input = UsualUnaryConversions(Input.get());
12652     if (Input.isInvalid()) return ExprError();
12653     // Unary plus and minus require promoting an operand of half vector to a
12654     // float vector and truncating the result back to a half vector. For now, we
12655     // do this only when HalfArgsAndReturns is set (that is, when the target is
12656     // arm or arm64).
12657     ConvertHalfVec =
12658         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12659 
12660     // If the operand is a half vector, promote it to a float vector.
12661     if (ConvertHalfVec)
12662       Input = convertVector(Input.get(), Context.FloatTy, *this);
12663     resultType = Input.get()->getType();
12664     if (resultType->isDependentType())
12665       break;
12666     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12667       break;
12668     else if (resultType->isVectorType() &&
12669              // The z vector extensions don't allow + or - with bool vectors.
12670              (!Context.getLangOpts().ZVector ||
12671               resultType->getAs<VectorType>()->getVectorKind() !=
12672               VectorType::AltiVecBool))
12673       break;
12674     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12675              Opc == UO_Plus &&
12676              resultType->isPointerType())
12677       break;
12678 
12679     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12680       << resultType << Input.get()->getSourceRange());
12681 
12682   case UO_Not: // bitwise complement
12683     Input = UsualUnaryConversions(Input.get());
12684     if (Input.isInvalid())
12685       return ExprError();
12686     resultType = Input.get()->getType();
12687 
12688     if (resultType->isDependentType())
12689       break;
12690     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12691     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12692       // C99 does not support '~' for complex conjugation.
12693       Diag(OpLoc, diag::ext_integer_complement_complex)
12694           << resultType << Input.get()->getSourceRange();
12695     else if (resultType->hasIntegerRepresentation())
12696       break;
12697     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12698       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12699       // on vector float types.
12700       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12701       if (!T->isIntegerType())
12702         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12703                           << resultType << Input.get()->getSourceRange());
12704     } else {
12705       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12706                        << resultType << Input.get()->getSourceRange());
12707     }
12708     break;
12709 
12710   case UO_LNot: // logical negation
12711     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12712     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12713     if (Input.isInvalid()) return ExprError();
12714     resultType = Input.get()->getType();
12715 
12716     // Though we still have to promote half FP to float...
12717     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12718       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12719       resultType = Context.FloatTy;
12720     }
12721 
12722     if (resultType->isDependentType())
12723       break;
12724     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12725       // C99 6.5.3.3p1: ok, fallthrough;
12726       if (Context.getLangOpts().CPlusPlus) {
12727         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12728         // operand contextually converted to bool.
12729         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12730                                   ScalarTypeToBooleanCastKind(resultType));
12731       } else if (Context.getLangOpts().OpenCL &&
12732                  Context.getLangOpts().OpenCLVersion < 120) {
12733         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12734         // operate on scalar float types.
12735         if (!resultType->isIntegerType() && !resultType->isPointerType())
12736           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12737                            << resultType << Input.get()->getSourceRange());
12738       }
12739     } else if (resultType->isExtVectorType()) {
12740       if (Context.getLangOpts().OpenCL &&
12741           Context.getLangOpts().OpenCLVersion < 120) {
12742         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12743         // operate on vector float types.
12744         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12745         if (!T->isIntegerType())
12746           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12747                            << resultType << Input.get()->getSourceRange());
12748       }
12749       // Vector logical not returns the signed variant of the operand type.
12750       resultType = GetSignedVectorType(resultType);
12751       break;
12752     } else {
12753       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12754       //        type in C++. We should allow that here too.
12755       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12756         << resultType << Input.get()->getSourceRange());
12757     }
12758 
12759     // LNot always has type int. C99 6.5.3.3p5.
12760     // In C++, it's bool. C++ 5.3.1p8
12761     resultType = Context.getLogicalOperationType();
12762     break;
12763   case UO_Real:
12764   case UO_Imag:
12765     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12766     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12767     // complex l-values to ordinary l-values and all other values to r-values.
12768     if (Input.isInvalid()) return ExprError();
12769     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12770       if (Input.get()->getValueKind() != VK_RValue &&
12771           Input.get()->getObjectKind() == OK_Ordinary)
12772         VK = Input.get()->getValueKind();
12773     } else if (!getLangOpts().CPlusPlus) {
12774       // In C, a volatile scalar is read by __imag. In C++, it is not.
12775       Input = DefaultLvalueConversion(Input.get());
12776     }
12777     break;
12778   case UO_Extension:
12779     resultType = Input.get()->getType();
12780     VK = Input.get()->getValueKind();
12781     OK = Input.get()->getObjectKind();
12782     break;
12783   case UO_Coawait:
12784     // It's unnecessary to represent the pass-through operator co_await in the
12785     // AST; just return the input expression instead.
12786     assert(!Input.get()->getType()->isDependentType() &&
12787                    "the co_await expression must be non-dependant before "
12788                    "building operator co_await");
12789     return Input;
12790   }
12791   if (resultType.isNull() || Input.isInvalid())
12792     return ExprError();
12793 
12794   // Check for array bounds violations in the operand of the UnaryOperator,
12795   // except for the '*' and '&' operators that have to be handled specially
12796   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12797   // that are explicitly defined as valid by the standard).
12798   if (Opc != UO_AddrOf && Opc != UO_Deref)
12799     CheckArrayAccess(Input.get());
12800 
12801   auto *UO = new (Context)
12802       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12803   // Convert the result back to a half vector.
12804   if (ConvertHalfVec)
12805     return convertVector(UO, Context.HalfTy, *this);
12806   return UO;
12807 }
12808 
12809 /// Determine whether the given expression is a qualified member
12810 /// access expression, of a form that could be turned into a pointer to member
12811 /// with the address-of operator.
12812 bool Sema::isQualifiedMemberAccess(Expr *E) {
12813   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12814     if (!DRE->getQualifier())
12815       return false;
12816 
12817     ValueDecl *VD = DRE->getDecl();
12818     if (!VD->isCXXClassMember())
12819       return false;
12820 
12821     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12822       return true;
12823     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12824       return Method->isInstance();
12825 
12826     return false;
12827   }
12828 
12829   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12830     if (!ULE->getQualifier())
12831       return false;
12832 
12833     for (NamedDecl *D : ULE->decls()) {
12834       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12835         if (Method->isInstance())
12836           return true;
12837       } else {
12838         // Overload set does not contain methods.
12839         break;
12840       }
12841     }
12842 
12843     return false;
12844   }
12845 
12846   return false;
12847 }
12848 
12849 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12850                               UnaryOperatorKind Opc, Expr *Input) {
12851   // First things first: handle placeholders so that the
12852   // overloaded-operator check considers the right type.
12853   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12854     // Increment and decrement of pseudo-object references.
12855     if (pty->getKind() == BuiltinType::PseudoObject &&
12856         UnaryOperator::isIncrementDecrementOp(Opc))
12857       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12858 
12859     // extension is always a builtin operator.
12860     if (Opc == UO_Extension)
12861       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12862 
12863     // & gets special logic for several kinds of placeholder.
12864     // The builtin code knows what to do.
12865     if (Opc == UO_AddrOf &&
12866         (pty->getKind() == BuiltinType::Overload ||
12867          pty->getKind() == BuiltinType::UnknownAny ||
12868          pty->getKind() == BuiltinType::BoundMember))
12869       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12870 
12871     // Anything else needs to be handled now.
12872     ExprResult Result = CheckPlaceholderExpr(Input);
12873     if (Result.isInvalid()) return ExprError();
12874     Input = Result.get();
12875   }
12876 
12877   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12878       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12879       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12880     // Find all of the overloaded operators visible from this
12881     // point. We perform both an operator-name lookup from the local
12882     // scope and an argument-dependent lookup based on the types of
12883     // the arguments.
12884     UnresolvedSet<16> Functions;
12885     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12886     if (S && OverOp != OO_None)
12887       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12888                                    Functions);
12889 
12890     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12891   }
12892 
12893   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12894 }
12895 
12896 // Unary Operators.  'Tok' is the token for the operator.
12897 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12898                               tok::TokenKind Op, Expr *Input) {
12899   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12900 }
12901 
12902 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12903 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12904                                 LabelDecl *TheDecl) {
12905   TheDecl->markUsed(Context);
12906   // Create the AST node.  The address of a label always has type 'void*'.
12907   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12908                                      Context.getPointerType(Context.VoidTy));
12909 }
12910 
12911 /// Given the last statement in a statement-expression, check whether
12912 /// the result is a producing expression (like a call to an
12913 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12914 /// release out of the full-expression.  Otherwise, return null.
12915 /// Cannot fail.
12916 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12917   // Should always be wrapped with one of these.
12918   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12919   if (!cleanups) return nullptr;
12920 
12921   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12922   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12923     return nullptr;
12924 
12925   // Splice out the cast.  This shouldn't modify any interesting
12926   // features of the statement.
12927   Expr *producer = cast->getSubExpr();
12928   assert(producer->getType() == cast->getType());
12929   assert(producer->getValueKind() == cast->getValueKind());
12930   cleanups->setSubExpr(producer);
12931   return cleanups;
12932 }
12933 
12934 void Sema::ActOnStartStmtExpr() {
12935   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12936 }
12937 
12938 void Sema::ActOnStmtExprError() {
12939   // Note that function is also called by TreeTransform when leaving a
12940   // StmtExpr scope without rebuilding anything.
12941 
12942   DiscardCleanupsInEvaluationContext();
12943   PopExpressionEvaluationContext();
12944 }
12945 
12946 ExprResult
12947 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12948                     SourceLocation RPLoc) { // "({..})"
12949   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12950   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12951 
12952   if (hasAnyUnrecoverableErrorsInThisFunction())
12953     DiscardCleanupsInEvaluationContext();
12954   assert(!Cleanup.exprNeedsCleanups() &&
12955          "cleanups within StmtExpr not correctly bound!");
12956   PopExpressionEvaluationContext();
12957 
12958   // FIXME: there are a variety of strange constraints to enforce here, for
12959   // example, it is not possible to goto into a stmt expression apparently.
12960   // More semantic analysis is needed.
12961 
12962   // If there are sub-stmts in the compound stmt, take the type of the last one
12963   // as the type of the stmtexpr.
12964   QualType Ty = Context.VoidTy;
12965   bool StmtExprMayBindToTemp = false;
12966   if (!Compound->body_empty()) {
12967     Stmt *LastStmt = Compound->body_back();
12968     LabelStmt *LastLabelStmt = nullptr;
12969     // If LastStmt is a label, skip down through into the body.
12970     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12971       LastLabelStmt = Label;
12972       LastStmt = Label->getSubStmt();
12973     }
12974 
12975     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12976       // Do function/array conversion on the last expression, but not
12977       // lvalue-to-rvalue.  However, initialize an unqualified type.
12978       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12979       if (LastExpr.isInvalid())
12980         return ExprError();
12981       Ty = LastExpr.get()->getType().getUnqualifiedType();
12982 
12983       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12984         // In ARC, if the final expression ends in a consume, splice
12985         // the consume out and bind it later.  In the alternate case
12986         // (when dealing with a retainable type), the result
12987         // initialization will create a produce.  In both cases the
12988         // result will be +1, and we'll need to balance that out with
12989         // a bind.
12990         if (Expr *rebuiltLastStmt
12991               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12992           LastExpr = rebuiltLastStmt;
12993         } else {
12994           LastExpr = PerformCopyInitialization(
12995               InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
12996               SourceLocation(), LastExpr);
12997         }
12998 
12999         if (LastExpr.isInvalid())
13000           return ExprError();
13001         if (LastExpr.get() != nullptr) {
13002           if (!LastLabelStmt)
13003             Compound->setLastStmt(LastExpr.get());
13004           else
13005             LastLabelStmt->setSubStmt(LastExpr.get());
13006           StmtExprMayBindToTemp = true;
13007         }
13008       }
13009     }
13010   }
13011 
13012   // FIXME: Check that expression type is complete/non-abstract; statement
13013   // expressions are not lvalues.
13014   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13015   if (StmtExprMayBindToTemp)
13016     return MaybeBindToTemporary(ResStmtExpr);
13017   return ResStmtExpr;
13018 }
13019 
13020 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13021                                       TypeSourceInfo *TInfo,
13022                                       ArrayRef<OffsetOfComponent> Components,
13023                                       SourceLocation RParenLoc) {
13024   QualType ArgTy = TInfo->getType();
13025   bool Dependent = ArgTy->isDependentType();
13026   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13027 
13028   // We must have at least one component that refers to the type, and the first
13029   // one is known to be a field designator.  Verify that the ArgTy represents
13030   // a struct/union/class.
13031   if (!Dependent && !ArgTy->isRecordType())
13032     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13033                        << ArgTy << TypeRange);
13034 
13035   // Type must be complete per C99 7.17p3 because a declaring a variable
13036   // with an incomplete type would be ill-formed.
13037   if (!Dependent
13038       && RequireCompleteType(BuiltinLoc, ArgTy,
13039                              diag::err_offsetof_incomplete_type, TypeRange))
13040     return ExprError();
13041 
13042   bool DidWarnAboutNonPOD = false;
13043   QualType CurrentType = ArgTy;
13044   SmallVector<OffsetOfNode, 4> Comps;
13045   SmallVector<Expr*, 4> Exprs;
13046   for (const OffsetOfComponent &OC : Components) {
13047     if (OC.isBrackets) {
13048       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13049       if (!CurrentType->isDependentType()) {
13050         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13051         if(!AT)
13052           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13053                            << CurrentType);
13054         CurrentType = AT->getElementType();
13055       } else
13056         CurrentType = Context.DependentTy;
13057 
13058       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13059       if (IdxRval.isInvalid())
13060         return ExprError();
13061       Expr *Idx = IdxRval.get();
13062 
13063       // The expression must be an integral expression.
13064       // FIXME: An integral constant expression?
13065       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13066           !Idx->getType()->isIntegerType())
13067         return ExprError(Diag(Idx->getLocStart(),
13068                               diag::err_typecheck_subscript_not_integer)
13069                          << Idx->getSourceRange());
13070 
13071       // Record this array index.
13072       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13073       Exprs.push_back(Idx);
13074       continue;
13075     }
13076 
13077     // Offset of a field.
13078     if (CurrentType->isDependentType()) {
13079       // We have the offset of a field, but we can't look into the dependent
13080       // type. Just record the identifier of the field.
13081       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13082       CurrentType = Context.DependentTy;
13083       continue;
13084     }
13085 
13086     // We need to have a complete type to look into.
13087     if (RequireCompleteType(OC.LocStart, CurrentType,
13088                             diag::err_offsetof_incomplete_type))
13089       return ExprError();
13090 
13091     // Look for the designated field.
13092     const RecordType *RC = CurrentType->getAs<RecordType>();
13093     if (!RC)
13094       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13095                        << CurrentType);
13096     RecordDecl *RD = RC->getDecl();
13097 
13098     // C++ [lib.support.types]p5:
13099     //   The macro offsetof accepts a restricted set of type arguments in this
13100     //   International Standard. type shall be a POD structure or a POD union
13101     //   (clause 9).
13102     // C++11 [support.types]p4:
13103     //   If type is not a standard-layout class (Clause 9), the results are
13104     //   undefined.
13105     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13106       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13107       unsigned DiagID =
13108         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13109                             : diag::ext_offsetof_non_pod_type;
13110 
13111       if (!IsSafe && !DidWarnAboutNonPOD &&
13112           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13113                               PDiag(DiagID)
13114                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13115                               << CurrentType))
13116         DidWarnAboutNonPOD = true;
13117     }
13118 
13119     // Look for the field.
13120     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13121     LookupQualifiedName(R, RD);
13122     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13123     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13124     if (!MemberDecl) {
13125       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13126         MemberDecl = IndirectMemberDecl->getAnonField();
13127     }
13128 
13129     if (!MemberDecl)
13130       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13131                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13132                                                               OC.LocEnd));
13133 
13134     // C99 7.17p3:
13135     //   (If the specified member is a bit-field, the behavior is undefined.)
13136     //
13137     // We diagnose this as an error.
13138     if (MemberDecl->isBitField()) {
13139       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13140         << MemberDecl->getDeclName()
13141         << SourceRange(BuiltinLoc, RParenLoc);
13142       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13143       return ExprError();
13144     }
13145 
13146     RecordDecl *Parent = MemberDecl->getParent();
13147     if (IndirectMemberDecl)
13148       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13149 
13150     // If the member was found in a base class, introduce OffsetOfNodes for
13151     // the base class indirections.
13152     CXXBasePaths Paths;
13153     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13154                       Paths)) {
13155       if (Paths.getDetectedVirtual()) {
13156         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13157           << MemberDecl->getDeclName()
13158           << SourceRange(BuiltinLoc, RParenLoc);
13159         return ExprError();
13160       }
13161 
13162       CXXBasePath &Path = Paths.front();
13163       for (const CXXBasePathElement &B : Path)
13164         Comps.push_back(OffsetOfNode(B.Base));
13165     }
13166 
13167     if (IndirectMemberDecl) {
13168       for (auto *FI : IndirectMemberDecl->chain()) {
13169         assert(isa<FieldDecl>(FI));
13170         Comps.push_back(OffsetOfNode(OC.LocStart,
13171                                      cast<FieldDecl>(FI), OC.LocEnd));
13172       }
13173     } else
13174       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13175 
13176     CurrentType = MemberDecl->getType().getNonReferenceType();
13177   }
13178 
13179   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13180                               Comps, Exprs, RParenLoc);
13181 }
13182 
13183 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13184                                       SourceLocation BuiltinLoc,
13185                                       SourceLocation TypeLoc,
13186                                       ParsedType ParsedArgTy,
13187                                       ArrayRef<OffsetOfComponent> Components,
13188                                       SourceLocation RParenLoc) {
13189 
13190   TypeSourceInfo *ArgTInfo;
13191   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13192   if (ArgTy.isNull())
13193     return ExprError();
13194 
13195   if (!ArgTInfo)
13196     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13197 
13198   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13199 }
13200 
13201 
13202 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13203                                  Expr *CondExpr,
13204                                  Expr *LHSExpr, Expr *RHSExpr,
13205                                  SourceLocation RPLoc) {
13206   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13207 
13208   ExprValueKind VK = VK_RValue;
13209   ExprObjectKind OK = OK_Ordinary;
13210   QualType resType;
13211   bool ValueDependent = false;
13212   bool CondIsTrue = false;
13213   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13214     resType = Context.DependentTy;
13215     ValueDependent = true;
13216   } else {
13217     // The conditional expression is required to be a constant expression.
13218     llvm::APSInt condEval(32);
13219     ExprResult CondICE
13220       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13221           diag::err_typecheck_choose_expr_requires_constant, false);
13222     if (CondICE.isInvalid())
13223       return ExprError();
13224     CondExpr = CondICE.get();
13225     CondIsTrue = condEval.getZExtValue();
13226 
13227     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13228     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13229 
13230     resType = ActiveExpr->getType();
13231     ValueDependent = ActiveExpr->isValueDependent();
13232     VK = ActiveExpr->getValueKind();
13233     OK = ActiveExpr->getObjectKind();
13234   }
13235 
13236   return new (Context)
13237       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13238                  CondIsTrue, resType->isDependentType(), ValueDependent);
13239 }
13240 
13241 //===----------------------------------------------------------------------===//
13242 // Clang Extensions.
13243 //===----------------------------------------------------------------------===//
13244 
13245 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13246 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13247   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13248 
13249   if (LangOpts.CPlusPlus) {
13250     Decl *ManglingContextDecl;
13251     if (MangleNumberingContext *MCtx =
13252             getCurrentMangleNumberContext(Block->getDeclContext(),
13253                                           ManglingContextDecl)) {
13254       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13255       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13256     }
13257   }
13258 
13259   PushBlockScope(CurScope, Block);
13260   CurContext->addDecl(Block);
13261   if (CurScope)
13262     PushDeclContext(CurScope, Block);
13263   else
13264     CurContext = Block;
13265 
13266   getCurBlock()->HasImplicitReturnType = true;
13267 
13268   // Enter a new evaluation context to insulate the block from any
13269   // cleanups from the enclosing full-expression.
13270   PushExpressionEvaluationContext(
13271       ExpressionEvaluationContext::PotentiallyEvaluated);
13272 }
13273 
13274 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13275                                Scope *CurScope) {
13276   assert(ParamInfo.getIdentifier() == nullptr &&
13277          "block-id should have no identifier!");
13278   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13279   BlockScopeInfo *CurBlock = getCurBlock();
13280 
13281   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13282   QualType T = Sig->getType();
13283 
13284   // FIXME: We should allow unexpanded parameter packs here, but that would,
13285   // in turn, make the block expression contain unexpanded parameter packs.
13286   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13287     // Drop the parameters.
13288     FunctionProtoType::ExtProtoInfo EPI;
13289     EPI.HasTrailingReturn = false;
13290     EPI.TypeQuals |= DeclSpec::TQ_const;
13291     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13292     Sig = Context.getTrivialTypeSourceInfo(T);
13293   }
13294 
13295   // GetTypeForDeclarator always produces a function type for a block
13296   // literal signature.  Furthermore, it is always a FunctionProtoType
13297   // unless the function was written with a typedef.
13298   assert(T->isFunctionType() &&
13299          "GetTypeForDeclarator made a non-function block signature");
13300 
13301   // Look for an explicit signature in that function type.
13302   FunctionProtoTypeLoc ExplicitSignature;
13303 
13304   if ((ExplicitSignature =
13305            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13306 
13307     // Check whether that explicit signature was synthesized by
13308     // GetTypeForDeclarator.  If so, don't save that as part of the
13309     // written signature.
13310     if (ExplicitSignature.getLocalRangeBegin() ==
13311         ExplicitSignature.getLocalRangeEnd()) {
13312       // This would be much cheaper if we stored TypeLocs instead of
13313       // TypeSourceInfos.
13314       TypeLoc Result = ExplicitSignature.getReturnLoc();
13315       unsigned Size = Result.getFullDataSize();
13316       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13317       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13318 
13319       ExplicitSignature = FunctionProtoTypeLoc();
13320     }
13321   }
13322 
13323   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13324   CurBlock->FunctionType = T;
13325 
13326   const FunctionType *Fn = T->getAs<FunctionType>();
13327   QualType RetTy = Fn->getReturnType();
13328   bool isVariadic =
13329     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13330 
13331   CurBlock->TheDecl->setIsVariadic(isVariadic);
13332 
13333   // Context.DependentTy is used as a placeholder for a missing block
13334   // return type.  TODO:  what should we do with declarators like:
13335   //   ^ * { ... }
13336   // If the answer is "apply template argument deduction"....
13337   if (RetTy != Context.DependentTy) {
13338     CurBlock->ReturnType = RetTy;
13339     CurBlock->TheDecl->setBlockMissingReturnType(false);
13340     CurBlock->HasImplicitReturnType = false;
13341   }
13342 
13343   // Push block parameters from the declarator if we had them.
13344   SmallVector<ParmVarDecl*, 8> Params;
13345   if (ExplicitSignature) {
13346     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13347       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13348       if (Param->getIdentifier() == nullptr &&
13349           !Param->isImplicit() &&
13350           !Param->isInvalidDecl() &&
13351           !getLangOpts().CPlusPlus)
13352         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13353       Params.push_back(Param);
13354     }
13355 
13356   // Fake up parameter variables if we have a typedef, like
13357   //   ^ fntype { ... }
13358   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13359     for (const auto &I : Fn->param_types()) {
13360       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13361           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13362       Params.push_back(Param);
13363     }
13364   }
13365 
13366   // Set the parameters on the block decl.
13367   if (!Params.empty()) {
13368     CurBlock->TheDecl->setParams(Params);
13369     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13370                              /*CheckParameterNames=*/false);
13371   }
13372 
13373   // Finally we can process decl attributes.
13374   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13375 
13376   // Put the parameter variables in scope.
13377   for (auto AI : CurBlock->TheDecl->parameters()) {
13378     AI->setOwningFunction(CurBlock->TheDecl);
13379 
13380     // If this has an identifier, add it to the scope stack.
13381     if (AI->getIdentifier()) {
13382       CheckShadow(CurBlock->TheScope, AI);
13383 
13384       PushOnScopeChains(AI, CurBlock->TheScope);
13385     }
13386   }
13387 }
13388 
13389 /// ActOnBlockError - If there is an error parsing a block, this callback
13390 /// is invoked to pop the information about the block from the action impl.
13391 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13392   // Leave the expression-evaluation context.
13393   DiscardCleanupsInEvaluationContext();
13394   PopExpressionEvaluationContext();
13395 
13396   // Pop off CurBlock, handle nested blocks.
13397   PopDeclContext();
13398   PopFunctionScopeInfo();
13399 }
13400 
13401 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13402 /// literal was successfully completed.  ^(int x){...}
13403 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13404                                     Stmt *Body, Scope *CurScope) {
13405   // If blocks are disabled, emit an error.
13406   if (!LangOpts.Blocks)
13407     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13408 
13409   // Leave the expression-evaluation context.
13410   if (hasAnyUnrecoverableErrorsInThisFunction())
13411     DiscardCleanupsInEvaluationContext();
13412   assert(!Cleanup.exprNeedsCleanups() &&
13413          "cleanups within block not correctly bound!");
13414   PopExpressionEvaluationContext();
13415 
13416   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13417 
13418   if (BSI->HasImplicitReturnType)
13419     deduceClosureReturnType(*BSI);
13420 
13421   PopDeclContext();
13422 
13423   QualType RetTy = Context.VoidTy;
13424   if (!BSI->ReturnType.isNull())
13425     RetTy = BSI->ReturnType;
13426 
13427   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13428   QualType BlockTy;
13429 
13430   // Set the captured variables on the block.
13431   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13432   SmallVector<BlockDecl::Capture, 4> Captures;
13433   for (Capture &Cap : BSI->Captures) {
13434     if (Cap.isThisCapture())
13435       continue;
13436     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13437                               Cap.isNested(), Cap.getInitExpr());
13438     Captures.push_back(NewCap);
13439   }
13440   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13441 
13442   // If the user wrote a function type in some form, try to use that.
13443   if (!BSI->FunctionType.isNull()) {
13444     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13445 
13446     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13447     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13448 
13449     // Turn protoless block types into nullary block types.
13450     if (isa<FunctionNoProtoType>(FTy)) {
13451       FunctionProtoType::ExtProtoInfo EPI;
13452       EPI.ExtInfo = Ext;
13453       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13454 
13455     // Otherwise, if we don't need to change anything about the function type,
13456     // preserve its sugar structure.
13457     } else if (FTy->getReturnType() == RetTy &&
13458                (!NoReturn || FTy->getNoReturnAttr())) {
13459       BlockTy = BSI->FunctionType;
13460 
13461     // Otherwise, make the minimal modifications to the function type.
13462     } else {
13463       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13464       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13465       EPI.TypeQuals = 0; // FIXME: silently?
13466       EPI.ExtInfo = Ext;
13467       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13468     }
13469 
13470   // If we don't have a function type, just build one from nothing.
13471   } else {
13472     FunctionProtoType::ExtProtoInfo EPI;
13473     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13474     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13475   }
13476 
13477   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13478   BlockTy = Context.getBlockPointerType(BlockTy);
13479 
13480   // If needed, diagnose invalid gotos and switches in the block.
13481   if (getCurFunction()->NeedsScopeChecking() &&
13482       !PP.isCodeCompletionEnabled())
13483     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13484 
13485   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13486 
13487   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13488     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13489 
13490   // Try to apply the named return value optimization. We have to check again
13491   // if we can do this, though, because blocks keep return statements around
13492   // to deduce an implicit return type.
13493   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13494       !BSI->TheDecl->isDependentContext())
13495     computeNRVO(Body, BSI);
13496 
13497   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13498   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13499   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13500 
13501   // If the block isn't obviously global, i.e. it captures anything at
13502   // all, then we need to do a few things in the surrounding context:
13503   if (Result->getBlockDecl()->hasCaptures()) {
13504     // First, this expression has a new cleanup object.
13505     ExprCleanupObjects.push_back(Result->getBlockDecl());
13506     Cleanup.setExprNeedsCleanups(true);
13507 
13508     // It also gets a branch-protected scope if any of the captured
13509     // variables needs destruction.
13510     for (const auto &CI : Result->getBlockDecl()->captures()) {
13511       const VarDecl *var = CI.getVariable();
13512       if (var->getType().isDestructedType() != QualType::DK_none) {
13513         setFunctionHasBranchProtectedScope();
13514         break;
13515       }
13516     }
13517   }
13518 
13519   return Result;
13520 }
13521 
13522 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13523                             SourceLocation RPLoc) {
13524   TypeSourceInfo *TInfo;
13525   GetTypeFromParser(Ty, &TInfo);
13526   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13527 }
13528 
13529 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13530                                 Expr *E, TypeSourceInfo *TInfo,
13531                                 SourceLocation RPLoc) {
13532   Expr *OrigExpr = E;
13533   bool IsMS = false;
13534 
13535   // CUDA device code does not support varargs.
13536   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13537     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13538       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13539       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13540         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13541     }
13542   }
13543 
13544   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13545   // as Microsoft ABI on an actual Microsoft platform, where
13546   // __builtin_ms_va_list and __builtin_va_list are the same.)
13547   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13548       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13549     QualType MSVaListType = Context.getBuiltinMSVaListType();
13550     if (Context.hasSameType(MSVaListType, E->getType())) {
13551       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13552         return ExprError();
13553       IsMS = true;
13554     }
13555   }
13556 
13557   // Get the va_list type
13558   QualType VaListType = Context.getBuiltinVaListType();
13559   if (!IsMS) {
13560     if (VaListType->isArrayType()) {
13561       // Deal with implicit array decay; for example, on x86-64,
13562       // va_list is an array, but it's supposed to decay to
13563       // a pointer for va_arg.
13564       VaListType = Context.getArrayDecayedType(VaListType);
13565       // Make sure the input expression also decays appropriately.
13566       ExprResult Result = UsualUnaryConversions(E);
13567       if (Result.isInvalid())
13568         return ExprError();
13569       E = Result.get();
13570     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13571       // If va_list is a record type and we are compiling in C++ mode,
13572       // check the argument using reference binding.
13573       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13574           Context, Context.getLValueReferenceType(VaListType), false);
13575       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13576       if (Init.isInvalid())
13577         return ExprError();
13578       E = Init.getAs<Expr>();
13579     } else {
13580       // Otherwise, the va_list argument must be an l-value because
13581       // it is modified by va_arg.
13582       if (!E->isTypeDependent() &&
13583           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13584         return ExprError();
13585     }
13586   }
13587 
13588   if (!IsMS && !E->isTypeDependent() &&
13589       !Context.hasSameType(VaListType, E->getType()))
13590     return ExprError(Diag(E->getLocStart(),
13591                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13592       << OrigExpr->getType() << E->getSourceRange());
13593 
13594   if (!TInfo->getType()->isDependentType()) {
13595     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13596                             diag::err_second_parameter_to_va_arg_incomplete,
13597                             TInfo->getTypeLoc()))
13598       return ExprError();
13599 
13600     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13601                                TInfo->getType(),
13602                                diag::err_second_parameter_to_va_arg_abstract,
13603                                TInfo->getTypeLoc()))
13604       return ExprError();
13605 
13606     if (!TInfo->getType().isPODType(Context)) {
13607       Diag(TInfo->getTypeLoc().getBeginLoc(),
13608            TInfo->getType()->isObjCLifetimeType()
13609              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13610              : diag::warn_second_parameter_to_va_arg_not_pod)
13611         << TInfo->getType()
13612         << TInfo->getTypeLoc().getSourceRange();
13613     }
13614 
13615     // Check for va_arg where arguments of the given type will be promoted
13616     // (i.e. this va_arg is guaranteed to have undefined behavior).
13617     QualType PromoteType;
13618     if (TInfo->getType()->isPromotableIntegerType()) {
13619       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13620       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13621         PromoteType = QualType();
13622     }
13623     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13624       PromoteType = Context.DoubleTy;
13625     if (!PromoteType.isNull())
13626       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13627                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13628                           << TInfo->getType()
13629                           << PromoteType
13630                           << TInfo->getTypeLoc().getSourceRange());
13631   }
13632 
13633   QualType T = TInfo->getType().getNonLValueExprType(Context);
13634   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13635 }
13636 
13637 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13638   // The type of __null will be int or long, depending on the size of
13639   // pointers on the target.
13640   QualType Ty;
13641   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13642   if (pw == Context.getTargetInfo().getIntWidth())
13643     Ty = Context.IntTy;
13644   else if (pw == Context.getTargetInfo().getLongWidth())
13645     Ty = Context.LongTy;
13646   else if (pw == Context.getTargetInfo().getLongLongWidth())
13647     Ty = Context.LongLongTy;
13648   else {
13649     llvm_unreachable("I don't know size of pointer!");
13650   }
13651 
13652   return new (Context) GNUNullExpr(Ty, TokenLoc);
13653 }
13654 
13655 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13656                                               bool Diagnose) {
13657   if (!getLangOpts().ObjC1)
13658     return false;
13659 
13660   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13661   if (!PT)
13662     return false;
13663 
13664   if (!PT->isObjCIdType()) {
13665     // Check if the destination is the 'NSString' interface.
13666     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13667     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13668       return false;
13669   }
13670 
13671   // Ignore any parens, implicit casts (should only be
13672   // array-to-pointer decays), and not-so-opaque values.  The last is
13673   // important for making this trigger for property assignments.
13674   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13675   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13676     if (OV->getSourceExpr())
13677       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13678 
13679   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13680   if (!SL || !SL->isAscii())
13681     return false;
13682   if (Diagnose) {
13683     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13684       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13685     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13686   }
13687   return true;
13688 }
13689 
13690 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13691                                               const Expr *SrcExpr) {
13692   if (!DstType->isFunctionPointerType() ||
13693       !SrcExpr->getType()->isFunctionType())
13694     return false;
13695 
13696   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13697   if (!DRE)
13698     return false;
13699 
13700   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13701   if (!FD)
13702     return false;
13703 
13704   return !S.checkAddressOfFunctionIsAvailable(FD,
13705                                               /*Complain=*/true,
13706                                               SrcExpr->getLocStart());
13707 }
13708 
13709 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13710                                     SourceLocation Loc,
13711                                     QualType DstType, QualType SrcType,
13712                                     Expr *SrcExpr, AssignmentAction Action,
13713                                     bool *Complained) {
13714   if (Complained)
13715     *Complained = false;
13716 
13717   // Decode the result (notice that AST's are still created for extensions).
13718   bool CheckInferredResultType = false;
13719   bool isInvalid = false;
13720   unsigned DiagKind = 0;
13721   FixItHint Hint;
13722   ConversionFixItGenerator ConvHints;
13723   bool MayHaveConvFixit = false;
13724   bool MayHaveFunctionDiff = false;
13725   const ObjCInterfaceDecl *IFace = nullptr;
13726   const ObjCProtocolDecl *PDecl = nullptr;
13727 
13728   switch (ConvTy) {
13729   case Compatible:
13730       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13731       return false;
13732 
13733   case PointerToInt:
13734     DiagKind = diag::ext_typecheck_convert_pointer_int;
13735     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13736     MayHaveConvFixit = true;
13737     break;
13738   case IntToPointer:
13739     DiagKind = diag::ext_typecheck_convert_int_pointer;
13740     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13741     MayHaveConvFixit = true;
13742     break;
13743   case IncompatiblePointer:
13744     if (Action == AA_Passing_CFAudited)
13745       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13746     else if (SrcType->isFunctionPointerType() &&
13747              DstType->isFunctionPointerType())
13748       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13749     else
13750       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13751 
13752     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13753       SrcType->isObjCObjectPointerType();
13754     if (Hint.isNull() && !CheckInferredResultType) {
13755       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13756     }
13757     else if (CheckInferredResultType) {
13758       SrcType = SrcType.getUnqualifiedType();
13759       DstType = DstType.getUnqualifiedType();
13760     }
13761     MayHaveConvFixit = true;
13762     break;
13763   case IncompatiblePointerSign:
13764     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13765     break;
13766   case FunctionVoidPointer:
13767     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13768     break;
13769   case IncompatiblePointerDiscardsQualifiers: {
13770     // Perform array-to-pointer decay if necessary.
13771     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13772 
13773     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13774     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13775     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13776       DiagKind = diag::err_typecheck_incompatible_address_space;
13777       break;
13778 
13779     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13780       DiagKind = diag::err_typecheck_incompatible_ownership;
13781       break;
13782     }
13783 
13784     llvm_unreachable("unknown error case for discarding qualifiers!");
13785     // fallthrough
13786   }
13787   case CompatiblePointerDiscardsQualifiers:
13788     // If the qualifiers lost were because we were applying the
13789     // (deprecated) C++ conversion from a string literal to a char*
13790     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13791     // Ideally, this check would be performed in
13792     // checkPointerTypesForAssignment. However, that would require a
13793     // bit of refactoring (so that the second argument is an
13794     // expression, rather than a type), which should be done as part
13795     // of a larger effort to fix checkPointerTypesForAssignment for
13796     // C++ semantics.
13797     if (getLangOpts().CPlusPlus &&
13798         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13799       return false;
13800     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13801     break;
13802   case IncompatibleNestedPointerQualifiers:
13803     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13804     break;
13805   case IntToBlockPointer:
13806     DiagKind = diag::err_int_to_block_pointer;
13807     break;
13808   case IncompatibleBlockPointer:
13809     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13810     break;
13811   case IncompatibleObjCQualifiedId: {
13812     if (SrcType->isObjCQualifiedIdType()) {
13813       const ObjCObjectPointerType *srcOPT =
13814                 SrcType->getAs<ObjCObjectPointerType>();
13815       for (auto *srcProto : srcOPT->quals()) {
13816         PDecl = srcProto;
13817         break;
13818       }
13819       if (const ObjCInterfaceType *IFaceT =
13820             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13821         IFace = IFaceT->getDecl();
13822     }
13823     else if (DstType->isObjCQualifiedIdType()) {
13824       const ObjCObjectPointerType *dstOPT =
13825         DstType->getAs<ObjCObjectPointerType>();
13826       for (auto *dstProto : dstOPT->quals()) {
13827         PDecl = dstProto;
13828         break;
13829       }
13830       if (const ObjCInterfaceType *IFaceT =
13831             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13832         IFace = IFaceT->getDecl();
13833     }
13834     DiagKind = diag::warn_incompatible_qualified_id;
13835     break;
13836   }
13837   case IncompatibleVectors:
13838     DiagKind = diag::warn_incompatible_vectors;
13839     break;
13840   case IncompatibleObjCWeakRef:
13841     DiagKind = diag::err_arc_weak_unavailable_assign;
13842     break;
13843   case Incompatible:
13844     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13845       if (Complained)
13846         *Complained = true;
13847       return true;
13848     }
13849 
13850     DiagKind = diag::err_typecheck_convert_incompatible;
13851     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13852     MayHaveConvFixit = true;
13853     isInvalid = true;
13854     MayHaveFunctionDiff = true;
13855     break;
13856   }
13857 
13858   QualType FirstType, SecondType;
13859   switch (Action) {
13860   case AA_Assigning:
13861   case AA_Initializing:
13862     // The destination type comes first.
13863     FirstType = DstType;
13864     SecondType = SrcType;
13865     break;
13866 
13867   case AA_Returning:
13868   case AA_Passing:
13869   case AA_Passing_CFAudited:
13870   case AA_Converting:
13871   case AA_Sending:
13872   case AA_Casting:
13873     // The source type comes first.
13874     FirstType = SrcType;
13875     SecondType = DstType;
13876     break;
13877   }
13878 
13879   PartialDiagnostic FDiag = PDiag(DiagKind);
13880   if (Action == AA_Passing_CFAudited)
13881     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13882   else
13883     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13884 
13885   // If we can fix the conversion, suggest the FixIts.
13886   assert(ConvHints.isNull() || Hint.isNull());
13887   if (!ConvHints.isNull()) {
13888     for (FixItHint &H : ConvHints.Hints)
13889       FDiag << H;
13890   } else {
13891     FDiag << Hint;
13892   }
13893   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13894 
13895   if (MayHaveFunctionDiff)
13896     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13897 
13898   Diag(Loc, FDiag);
13899   if (DiagKind == diag::warn_incompatible_qualified_id &&
13900       PDecl && IFace && !IFace->hasDefinition())
13901       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13902         << IFace << PDecl;
13903 
13904   if (SecondType == Context.OverloadTy)
13905     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13906                               FirstType, /*TakingAddress=*/true);
13907 
13908   if (CheckInferredResultType)
13909     EmitRelatedResultTypeNote(SrcExpr);
13910 
13911   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13912     EmitRelatedResultTypeNoteForReturn(DstType);
13913 
13914   if (Complained)
13915     *Complained = true;
13916   return isInvalid;
13917 }
13918 
13919 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13920                                                  llvm::APSInt *Result) {
13921   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13922   public:
13923     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13924       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13925     }
13926   } Diagnoser;
13927 
13928   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13929 }
13930 
13931 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13932                                                  llvm::APSInt *Result,
13933                                                  unsigned DiagID,
13934                                                  bool AllowFold) {
13935   class IDDiagnoser : public VerifyICEDiagnoser {
13936     unsigned DiagID;
13937 
13938   public:
13939     IDDiagnoser(unsigned DiagID)
13940       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13941 
13942     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13943       S.Diag(Loc, DiagID) << SR;
13944     }
13945   } Diagnoser(DiagID);
13946 
13947   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13948 }
13949 
13950 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13951                                             SourceRange SR) {
13952   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13953 }
13954 
13955 ExprResult
13956 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13957                                       VerifyICEDiagnoser &Diagnoser,
13958                                       bool AllowFold) {
13959   SourceLocation DiagLoc = E->getLocStart();
13960 
13961   if (getLangOpts().CPlusPlus11) {
13962     // C++11 [expr.const]p5:
13963     //   If an expression of literal class type is used in a context where an
13964     //   integral constant expression is required, then that class type shall
13965     //   have a single non-explicit conversion function to an integral or
13966     //   unscoped enumeration type
13967     ExprResult Converted;
13968     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13969     public:
13970       CXX11ConvertDiagnoser(bool Silent)
13971           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13972                                 Silent, true) {}
13973 
13974       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13975                                            QualType T) override {
13976         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13977       }
13978 
13979       SemaDiagnosticBuilder diagnoseIncomplete(
13980           Sema &S, SourceLocation Loc, QualType T) override {
13981         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13982       }
13983 
13984       SemaDiagnosticBuilder diagnoseExplicitConv(
13985           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13986         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13987       }
13988 
13989       SemaDiagnosticBuilder noteExplicitConv(
13990           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13991         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13992                  << ConvTy->isEnumeralType() << ConvTy;
13993       }
13994 
13995       SemaDiagnosticBuilder diagnoseAmbiguous(
13996           Sema &S, SourceLocation Loc, QualType T) override {
13997         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13998       }
13999 
14000       SemaDiagnosticBuilder noteAmbiguous(
14001           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14002         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14003                  << ConvTy->isEnumeralType() << ConvTy;
14004       }
14005 
14006       SemaDiagnosticBuilder diagnoseConversion(
14007           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14008         llvm_unreachable("conversion functions are permitted");
14009       }
14010     } ConvertDiagnoser(Diagnoser.Suppress);
14011 
14012     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14013                                                     ConvertDiagnoser);
14014     if (Converted.isInvalid())
14015       return Converted;
14016     E = Converted.get();
14017     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14018       return ExprError();
14019   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14020     // An ICE must be of integral or unscoped enumeration type.
14021     if (!Diagnoser.Suppress)
14022       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14023     return ExprError();
14024   }
14025 
14026   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14027   // in the non-ICE case.
14028   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14029     if (Result)
14030       *Result = E->EvaluateKnownConstInt(Context);
14031     return E;
14032   }
14033 
14034   Expr::EvalResult EvalResult;
14035   SmallVector<PartialDiagnosticAt, 8> Notes;
14036   EvalResult.Diag = &Notes;
14037 
14038   // Try to evaluate the expression, and produce diagnostics explaining why it's
14039   // not a constant expression as a side-effect.
14040   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14041                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14042 
14043   // In C++11, we can rely on diagnostics being produced for any expression
14044   // which is not a constant expression. If no diagnostics were produced, then
14045   // this is a constant expression.
14046   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14047     if (Result)
14048       *Result = EvalResult.Val.getInt();
14049     return E;
14050   }
14051 
14052   // If our only note is the usual "invalid subexpression" note, just point
14053   // the caret at its location rather than producing an essentially
14054   // redundant note.
14055   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14056         diag::note_invalid_subexpr_in_const_expr) {
14057     DiagLoc = Notes[0].first;
14058     Notes.clear();
14059   }
14060 
14061   if (!Folded || !AllowFold) {
14062     if (!Diagnoser.Suppress) {
14063       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14064       for (const PartialDiagnosticAt &Note : Notes)
14065         Diag(Note.first, Note.second);
14066     }
14067 
14068     return ExprError();
14069   }
14070 
14071   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14072   for (const PartialDiagnosticAt &Note : Notes)
14073     Diag(Note.first, Note.second);
14074 
14075   if (Result)
14076     *Result = EvalResult.Val.getInt();
14077   return E;
14078 }
14079 
14080 namespace {
14081   // Handle the case where we conclude a expression which we speculatively
14082   // considered to be unevaluated is actually evaluated.
14083   class TransformToPE : public TreeTransform<TransformToPE> {
14084     typedef TreeTransform<TransformToPE> BaseTransform;
14085 
14086   public:
14087     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14088 
14089     // Make sure we redo semantic analysis
14090     bool AlwaysRebuild() { return true; }
14091 
14092     // Make sure we handle LabelStmts correctly.
14093     // FIXME: This does the right thing, but maybe we need a more general
14094     // fix to TreeTransform?
14095     StmtResult TransformLabelStmt(LabelStmt *S) {
14096       S->getDecl()->setStmt(nullptr);
14097       return BaseTransform::TransformLabelStmt(S);
14098     }
14099 
14100     // We need to special-case DeclRefExprs referring to FieldDecls which
14101     // are not part of a member pointer formation; normal TreeTransforming
14102     // doesn't catch this case because of the way we represent them in the AST.
14103     // FIXME: This is a bit ugly; is it really the best way to handle this
14104     // case?
14105     //
14106     // Error on DeclRefExprs referring to FieldDecls.
14107     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14108       if (isa<FieldDecl>(E->getDecl()) &&
14109           !SemaRef.isUnevaluatedContext())
14110         return SemaRef.Diag(E->getLocation(),
14111                             diag::err_invalid_non_static_member_use)
14112             << E->getDecl() << E->getSourceRange();
14113 
14114       return BaseTransform::TransformDeclRefExpr(E);
14115     }
14116 
14117     // Exception: filter out member pointer formation
14118     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14119       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14120         return E;
14121 
14122       return BaseTransform::TransformUnaryOperator(E);
14123     }
14124 
14125     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14126       // Lambdas never need to be transformed.
14127       return E;
14128     }
14129   };
14130 }
14131 
14132 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14133   assert(isUnevaluatedContext() &&
14134          "Should only transform unevaluated expressions");
14135   ExprEvalContexts.back().Context =
14136       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14137   if (isUnevaluatedContext())
14138     return E;
14139   return TransformToPE(*this).TransformExpr(E);
14140 }
14141 
14142 void
14143 Sema::PushExpressionEvaluationContext(
14144     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14145     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14146   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14147                                 LambdaContextDecl, ExprContext);
14148   Cleanup.reset();
14149   if (!MaybeODRUseExprs.empty())
14150     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14151 }
14152 
14153 void
14154 Sema::PushExpressionEvaluationContext(
14155     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14156     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14157   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14158   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14159 }
14160 
14161 void Sema::PopExpressionEvaluationContext() {
14162   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14163   unsigned NumTypos = Rec.NumTypos;
14164 
14165   if (!Rec.Lambdas.empty()) {
14166     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14167     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14168         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14169       unsigned D;
14170       if (Rec.isUnevaluated()) {
14171         // C++11 [expr.prim.lambda]p2:
14172         //   A lambda-expression shall not appear in an unevaluated operand
14173         //   (Clause 5).
14174         D = diag::err_lambda_unevaluated_operand;
14175       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14176         // C++1y [expr.const]p2:
14177         //   A conditional-expression e is a core constant expression unless the
14178         //   evaluation of e, following the rules of the abstract machine, would
14179         //   evaluate [...] a lambda-expression.
14180         D = diag::err_lambda_in_constant_expression;
14181       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14182         // C++17 [expr.prim.lamda]p2:
14183         // A lambda-expression shall not appear [...] in a template-argument.
14184         D = diag::err_lambda_in_invalid_context;
14185       } else
14186         llvm_unreachable("Couldn't infer lambda error message.");
14187 
14188       for (const auto *L : Rec.Lambdas)
14189         Diag(L->getLocStart(), D);
14190     } else {
14191       // Mark the capture expressions odr-used. This was deferred
14192       // during lambda expression creation.
14193       for (auto *Lambda : Rec.Lambdas) {
14194         for (auto *C : Lambda->capture_inits())
14195           MarkDeclarationsReferencedInExpr(C);
14196       }
14197     }
14198   }
14199 
14200   // When are coming out of an unevaluated context, clear out any
14201   // temporaries that we may have created as part of the evaluation of
14202   // the expression in that context: they aren't relevant because they
14203   // will never be constructed.
14204   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14205     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14206                              ExprCleanupObjects.end());
14207     Cleanup = Rec.ParentCleanup;
14208     CleanupVarDeclMarking();
14209     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14210   // Otherwise, merge the contexts together.
14211   } else {
14212     Cleanup.mergeFrom(Rec.ParentCleanup);
14213     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14214                             Rec.SavedMaybeODRUseExprs.end());
14215   }
14216 
14217   // Pop the current expression evaluation context off the stack.
14218   ExprEvalContexts.pop_back();
14219 
14220   if (!ExprEvalContexts.empty())
14221     ExprEvalContexts.back().NumTypos += NumTypos;
14222   else
14223     assert(NumTypos == 0 && "There are outstanding typos after popping the "
14224                             "last ExpressionEvaluationContextRecord");
14225 }
14226 
14227 void Sema::DiscardCleanupsInEvaluationContext() {
14228   ExprCleanupObjects.erase(
14229          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14230          ExprCleanupObjects.end());
14231   Cleanup.reset();
14232   MaybeODRUseExprs.clear();
14233 }
14234 
14235 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14236   if (!E->getType()->isVariablyModifiedType())
14237     return E;
14238   return TransformToPotentiallyEvaluated(E);
14239 }
14240 
14241 /// Are we within a context in which some evaluation could be performed (be it
14242 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14243 /// captured by C++'s idea of an "unevaluated context".
14244 static bool isEvaluatableContext(Sema &SemaRef) {
14245   switch (SemaRef.ExprEvalContexts.back().Context) {
14246     case Sema::ExpressionEvaluationContext::Unevaluated:
14247     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14248       // Expressions in this context are never evaluated.
14249       return false;
14250 
14251     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14252     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14253     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14254     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14255       // Expressions in this context could be evaluated.
14256       return true;
14257 
14258     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14259       // Referenced declarations will only be used if the construct in the
14260       // containing expression is used, at which point we'll be given another
14261       // turn to mark them.
14262       return false;
14263   }
14264   llvm_unreachable("Invalid context");
14265 }
14266 
14267 /// Are we within a context in which references to resolved functions or to
14268 /// variables result in odr-use?
14269 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14270   // An expression in a template is not really an expression until it's been
14271   // instantiated, so it doesn't trigger odr-use.
14272   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14273     return false;
14274 
14275   switch (SemaRef.ExprEvalContexts.back().Context) {
14276     case Sema::ExpressionEvaluationContext::Unevaluated:
14277     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14278     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14279     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14280       return false;
14281 
14282     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14283     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14284       return true;
14285 
14286     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14287       return false;
14288   }
14289   llvm_unreachable("Invalid context");
14290 }
14291 
14292 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14293   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14294   return Func->isConstexpr() &&
14295          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14296 }
14297 
14298 /// Mark a function referenced, and check whether it is odr-used
14299 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14300 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14301                                   bool MightBeOdrUse) {
14302   assert(Func && "No function?");
14303 
14304   Func->setReferenced();
14305 
14306   // C++11 [basic.def.odr]p3:
14307   //   A function whose name appears as a potentially-evaluated expression is
14308   //   odr-used if it is the unique lookup result or the selected member of a
14309   //   set of overloaded functions [...].
14310   //
14311   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14312   // can just check that here.
14313   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14314 
14315   // Determine whether we require a function definition to exist, per
14316   // C++11 [temp.inst]p3:
14317   //   Unless a function template specialization has been explicitly
14318   //   instantiated or explicitly specialized, the function template
14319   //   specialization is implicitly instantiated when the specialization is
14320   //   referenced in a context that requires a function definition to exist.
14321   //
14322   // That is either when this is an odr-use, or when a usage of a constexpr
14323   // function occurs within an evaluatable context.
14324   bool NeedDefinition =
14325       OdrUse || (isEvaluatableContext(*this) &&
14326                  isImplicitlyDefinableConstexprFunction(Func));
14327 
14328   // C++14 [temp.expl.spec]p6:
14329   //   If a template [...] is explicitly specialized then that specialization
14330   //   shall be declared before the first use of that specialization that would
14331   //   cause an implicit instantiation to take place, in every translation unit
14332   //   in which such a use occurs
14333   if (NeedDefinition &&
14334       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14335        Func->getMemberSpecializationInfo()))
14336     checkSpecializationVisibility(Loc, Func);
14337 
14338   // C++14 [except.spec]p17:
14339   //   An exception-specification is considered to be needed when:
14340   //   - the function is odr-used or, if it appears in an unevaluated operand,
14341   //     would be odr-used if the expression were potentially-evaluated;
14342   //
14343   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14344   // function is a pure virtual function we're calling, and in that case the
14345   // function was selected by overload resolution and we need to resolve its
14346   // exception specification for a different reason.
14347   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14348   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14349     ResolveExceptionSpec(Loc, FPT);
14350 
14351   // If we don't need to mark the function as used, and we don't need to
14352   // try to provide a definition, there's nothing more to do.
14353   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14354       (!NeedDefinition || Func->getBody()))
14355     return;
14356 
14357   // Note that this declaration has been used.
14358   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14359     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14360     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14361       if (Constructor->isDefaultConstructor()) {
14362         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14363           return;
14364         DefineImplicitDefaultConstructor(Loc, Constructor);
14365       } else if (Constructor->isCopyConstructor()) {
14366         DefineImplicitCopyConstructor(Loc, Constructor);
14367       } else if (Constructor->isMoveConstructor()) {
14368         DefineImplicitMoveConstructor(Loc, Constructor);
14369       }
14370     } else if (Constructor->getInheritedConstructor()) {
14371       DefineInheritingConstructor(Loc, Constructor);
14372     }
14373   } else if (CXXDestructorDecl *Destructor =
14374                  dyn_cast<CXXDestructorDecl>(Func)) {
14375     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14376     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14377       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14378         return;
14379       DefineImplicitDestructor(Loc, Destructor);
14380     }
14381     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14382       MarkVTableUsed(Loc, Destructor->getParent());
14383   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14384     if (MethodDecl->isOverloadedOperator() &&
14385         MethodDecl->getOverloadedOperator() == OO_Equal) {
14386       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14387       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14388         if (MethodDecl->isCopyAssignmentOperator())
14389           DefineImplicitCopyAssignment(Loc, MethodDecl);
14390         else if (MethodDecl->isMoveAssignmentOperator())
14391           DefineImplicitMoveAssignment(Loc, MethodDecl);
14392       }
14393     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14394                MethodDecl->getParent()->isLambda()) {
14395       CXXConversionDecl *Conversion =
14396           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14397       if (Conversion->isLambdaToBlockPointerConversion())
14398         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14399       else
14400         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14401     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14402       MarkVTableUsed(Loc, MethodDecl->getParent());
14403   }
14404 
14405   // Recursive functions should be marked when used from another function.
14406   // FIXME: Is this really right?
14407   if (CurContext == Func) return;
14408 
14409   // Implicit instantiation of function templates and member functions of
14410   // class templates.
14411   if (Func->isImplicitlyInstantiable()) {
14412     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14413     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14414     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14415     if (FirstInstantiation) {
14416       PointOfInstantiation = Loc;
14417       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14418     } else if (TSK != TSK_ImplicitInstantiation) {
14419       // Use the point of use as the point of instantiation, instead of the
14420       // point of explicit instantiation (which we track as the actual point of
14421       // instantiation). This gives better backtraces in diagnostics.
14422       PointOfInstantiation = Loc;
14423     }
14424 
14425     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14426         Func->isConstexpr()) {
14427       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14428           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14429           CodeSynthesisContexts.size())
14430         PendingLocalImplicitInstantiations.push_back(
14431             std::make_pair(Func, PointOfInstantiation));
14432       else if (Func->isConstexpr())
14433         // Do not defer instantiations of constexpr functions, to avoid the
14434         // expression evaluator needing to call back into Sema if it sees a
14435         // call to such a function.
14436         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14437       else {
14438         Func->setInstantiationIsPending(true);
14439         PendingInstantiations.push_back(std::make_pair(Func,
14440                                                        PointOfInstantiation));
14441         // Notify the consumer that a function was implicitly instantiated.
14442         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14443       }
14444     }
14445   } else {
14446     // Walk redefinitions, as some of them may be instantiable.
14447     for (auto i : Func->redecls()) {
14448       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14449         MarkFunctionReferenced(Loc, i, OdrUse);
14450     }
14451   }
14452 
14453   if (!OdrUse) return;
14454 
14455   // Keep track of used but undefined functions.
14456   if (!Func->isDefined()) {
14457     if (mightHaveNonExternalLinkage(Func))
14458       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14459     else if (Func->getMostRecentDecl()->isInlined() &&
14460              !LangOpts.GNUInline &&
14461              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14462       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14463     else if (isExternalWithNoLinkageType(Func))
14464       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14465   }
14466 
14467   Func->markUsed(Context);
14468 }
14469 
14470 static void
14471 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14472                                    ValueDecl *var, DeclContext *DC) {
14473   DeclContext *VarDC = var->getDeclContext();
14474 
14475   //  If the parameter still belongs to the translation unit, then
14476   //  we're actually just using one parameter in the declaration of
14477   //  the next.
14478   if (isa<ParmVarDecl>(var) &&
14479       isa<TranslationUnitDecl>(VarDC))
14480     return;
14481 
14482   // For C code, don't diagnose about capture if we're not actually in code
14483   // right now; it's impossible to write a non-constant expression outside of
14484   // function context, so we'll get other (more useful) diagnostics later.
14485   //
14486   // For C++, things get a bit more nasty... it would be nice to suppress this
14487   // diagnostic for certain cases like using a local variable in an array bound
14488   // for a member of a local class, but the correct predicate is not obvious.
14489   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14490     return;
14491 
14492   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14493   unsigned ContextKind = 3; // unknown
14494   if (isa<CXXMethodDecl>(VarDC) &&
14495       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14496     ContextKind = 2;
14497   } else if (isa<FunctionDecl>(VarDC)) {
14498     ContextKind = 0;
14499   } else if (isa<BlockDecl>(VarDC)) {
14500     ContextKind = 1;
14501   }
14502 
14503   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14504     << var << ValueKind << ContextKind << VarDC;
14505   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14506       << var;
14507 
14508   // FIXME: Add additional diagnostic info about class etc. which prevents
14509   // capture.
14510 }
14511 
14512 
14513 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14514                                       bool &SubCapturesAreNested,
14515                                       QualType &CaptureType,
14516                                       QualType &DeclRefType) {
14517    // Check whether we've already captured it.
14518   if (CSI->CaptureMap.count(Var)) {
14519     // If we found a capture, any subcaptures are nested.
14520     SubCapturesAreNested = true;
14521 
14522     // Retrieve the capture type for this variable.
14523     CaptureType = CSI->getCapture(Var).getCaptureType();
14524 
14525     // Compute the type of an expression that refers to this variable.
14526     DeclRefType = CaptureType.getNonReferenceType();
14527 
14528     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14529     // are mutable in the sense that user can change their value - they are
14530     // private instances of the captured declarations.
14531     const Capture &Cap = CSI->getCapture(Var);
14532     if (Cap.isCopyCapture() &&
14533         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14534         !(isa<CapturedRegionScopeInfo>(CSI) &&
14535           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14536       DeclRefType.addConst();
14537     return true;
14538   }
14539   return false;
14540 }
14541 
14542 // Only block literals, captured statements, and lambda expressions can
14543 // capture; other scopes don't work.
14544 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14545                                  SourceLocation Loc,
14546                                  const bool Diagnose, Sema &S) {
14547   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14548     return getLambdaAwareParentOfDeclContext(DC);
14549   else if (Var->hasLocalStorage()) {
14550     if (Diagnose)
14551        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14552   }
14553   return nullptr;
14554 }
14555 
14556 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14557 // certain types of variables (unnamed, variably modified types etc.)
14558 // so check for eligibility.
14559 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14560                                  SourceLocation Loc,
14561                                  const bool Diagnose, Sema &S) {
14562 
14563   bool IsBlock = isa<BlockScopeInfo>(CSI);
14564   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14565 
14566   // Lambdas are not allowed to capture unnamed variables
14567   // (e.g. anonymous unions).
14568   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14569   // assuming that's the intent.
14570   if (IsLambda && !Var->getDeclName()) {
14571     if (Diagnose) {
14572       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14573       S.Diag(Var->getLocation(), diag::note_declared_at);
14574     }
14575     return false;
14576   }
14577 
14578   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14579   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14580     if (Diagnose) {
14581       S.Diag(Loc, diag::err_ref_vm_type);
14582       S.Diag(Var->getLocation(), diag::note_previous_decl)
14583         << Var->getDeclName();
14584     }
14585     return false;
14586   }
14587   // Prohibit structs with flexible array members too.
14588   // We cannot capture what is in the tail end of the struct.
14589   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14590     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14591       if (Diagnose) {
14592         if (IsBlock)
14593           S.Diag(Loc, diag::err_ref_flexarray_type);
14594         else
14595           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14596             << Var->getDeclName();
14597         S.Diag(Var->getLocation(), diag::note_previous_decl)
14598           << Var->getDeclName();
14599       }
14600       return false;
14601     }
14602   }
14603   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14604   // Lambdas and captured statements are not allowed to capture __block
14605   // variables; they don't support the expected semantics.
14606   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14607     if (Diagnose) {
14608       S.Diag(Loc, diag::err_capture_block_variable)
14609         << Var->getDeclName() << !IsLambda;
14610       S.Diag(Var->getLocation(), diag::note_previous_decl)
14611         << Var->getDeclName();
14612     }
14613     return false;
14614   }
14615   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14616   if (S.getLangOpts().OpenCL && IsBlock &&
14617       Var->getType()->isBlockPointerType()) {
14618     if (Diagnose)
14619       S.Diag(Loc, diag::err_opencl_block_ref_block);
14620     return false;
14621   }
14622 
14623   return true;
14624 }
14625 
14626 // Returns true if the capture by block was successful.
14627 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14628                                  SourceLocation Loc,
14629                                  const bool BuildAndDiagnose,
14630                                  QualType &CaptureType,
14631                                  QualType &DeclRefType,
14632                                  const bool Nested,
14633                                  Sema &S) {
14634   Expr *CopyExpr = nullptr;
14635   bool ByRef = false;
14636 
14637   // Blocks are not allowed to capture arrays.
14638   if (CaptureType->isArrayType()) {
14639     if (BuildAndDiagnose) {
14640       S.Diag(Loc, diag::err_ref_array_type);
14641       S.Diag(Var->getLocation(), diag::note_previous_decl)
14642       << Var->getDeclName();
14643     }
14644     return false;
14645   }
14646 
14647   // Forbid the block-capture of autoreleasing variables.
14648   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14649     if (BuildAndDiagnose) {
14650       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14651         << /*block*/ 0;
14652       S.Diag(Var->getLocation(), diag::note_previous_decl)
14653         << Var->getDeclName();
14654     }
14655     return false;
14656   }
14657 
14658   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14659   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14660     // This function finds out whether there is an AttributedType of kind
14661     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14662     // attr_objc_ownership implies __autoreleasing was explicitly specified
14663     // rather than being added implicitly by the compiler.
14664     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14665       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14666         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14667           return true;
14668 
14669         // Peel off AttributedTypes that are not of kind objc_ownership.
14670         Ty = AttrTy->getModifiedType();
14671       }
14672 
14673       return false;
14674     };
14675 
14676     QualType PointeeTy = PT->getPointeeType();
14677 
14678     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14679         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14680         !IsObjCOwnershipAttributedType(PointeeTy)) {
14681       if (BuildAndDiagnose) {
14682         SourceLocation VarLoc = Var->getLocation();
14683         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14684         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14685       }
14686     }
14687   }
14688 
14689   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14690   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14691       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14692     // Block capture by reference does not change the capture or
14693     // declaration reference types.
14694     ByRef = true;
14695   } else {
14696     // Block capture by copy introduces 'const'.
14697     CaptureType = CaptureType.getNonReferenceType().withConst();
14698     DeclRefType = CaptureType;
14699 
14700     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14701       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14702         // The capture logic needs the destructor, so make sure we mark it.
14703         // Usually this is unnecessary because most local variables have
14704         // their destructors marked at declaration time, but parameters are
14705         // an exception because it's technically only the call site that
14706         // actually requires the destructor.
14707         if (isa<ParmVarDecl>(Var))
14708           S.FinalizeVarWithDestructor(Var, Record);
14709 
14710         // Enter a new evaluation context to insulate the copy
14711         // full-expression.
14712         EnterExpressionEvaluationContext scope(
14713             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14714 
14715         // According to the blocks spec, the capture of a variable from
14716         // the stack requires a const copy constructor.  This is not true
14717         // of the copy/move done to move a __block variable to the heap.
14718         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14719                                                   DeclRefType.withConst(),
14720                                                   VK_LValue, Loc);
14721 
14722         ExprResult Result
14723           = S.PerformCopyInitialization(
14724               InitializedEntity::InitializeBlock(Var->getLocation(),
14725                                                   CaptureType, false),
14726               Loc, DeclRef);
14727 
14728         // Build a full-expression copy expression if initialization
14729         // succeeded and used a non-trivial constructor.  Recover from
14730         // errors by pretending that the copy isn't necessary.
14731         if (!Result.isInvalid() &&
14732             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14733                 ->isTrivial()) {
14734           Result = S.MaybeCreateExprWithCleanups(Result);
14735           CopyExpr = Result.get();
14736         }
14737       }
14738     }
14739   }
14740 
14741   // Actually capture the variable.
14742   if (BuildAndDiagnose)
14743     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14744                     SourceLocation(), CaptureType, CopyExpr);
14745 
14746   return true;
14747 
14748 }
14749 
14750 
14751 /// Capture the given variable in the captured region.
14752 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14753                                     VarDecl *Var,
14754                                     SourceLocation Loc,
14755                                     const bool BuildAndDiagnose,
14756                                     QualType &CaptureType,
14757                                     QualType &DeclRefType,
14758                                     const bool RefersToCapturedVariable,
14759                                     Sema &S) {
14760   // By default, capture variables by reference.
14761   bool ByRef = true;
14762   // Using an LValue reference type is consistent with Lambdas (see below).
14763   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14764     if (S.isOpenMPCapturedDecl(Var)) {
14765       bool HasConst = DeclRefType.isConstQualified();
14766       DeclRefType = DeclRefType.getUnqualifiedType();
14767       // Don't lose diagnostics about assignments to const.
14768       if (HasConst)
14769         DeclRefType.addConst();
14770     }
14771     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14772   }
14773 
14774   if (ByRef)
14775     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14776   else
14777     CaptureType = DeclRefType;
14778 
14779   Expr *CopyExpr = nullptr;
14780   if (BuildAndDiagnose) {
14781     // The current implementation assumes that all variables are captured
14782     // by references. Since there is no capture by copy, no expression
14783     // evaluation will be needed.
14784     RecordDecl *RD = RSI->TheRecordDecl;
14785 
14786     FieldDecl *Field
14787       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14788                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14789                           nullptr, false, ICIS_NoInit);
14790     Field->setImplicit(true);
14791     Field->setAccess(AS_private);
14792     RD->addDecl(Field);
14793     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14794       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14795 
14796     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14797                                             DeclRefType, VK_LValue, Loc);
14798     Var->setReferenced(true);
14799     Var->markUsed(S.Context);
14800   }
14801 
14802   // Actually capture the variable.
14803   if (BuildAndDiagnose)
14804     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14805                     SourceLocation(), CaptureType, CopyExpr);
14806 
14807 
14808   return true;
14809 }
14810 
14811 /// Create a field within the lambda class for the variable
14812 /// being captured.
14813 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14814                                     QualType FieldType, QualType DeclRefType,
14815                                     SourceLocation Loc,
14816                                     bool RefersToCapturedVariable) {
14817   CXXRecordDecl *Lambda = LSI->Lambda;
14818 
14819   // Build the non-static data member.
14820   FieldDecl *Field
14821     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14822                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14823                         nullptr, false, ICIS_NoInit);
14824   Field->setImplicit(true);
14825   Field->setAccess(AS_private);
14826   Lambda->addDecl(Field);
14827 }
14828 
14829 /// Capture the given variable in the lambda.
14830 static bool captureInLambda(LambdaScopeInfo *LSI,
14831                             VarDecl *Var,
14832                             SourceLocation Loc,
14833                             const bool BuildAndDiagnose,
14834                             QualType &CaptureType,
14835                             QualType &DeclRefType,
14836                             const bool RefersToCapturedVariable,
14837                             const Sema::TryCaptureKind Kind,
14838                             SourceLocation EllipsisLoc,
14839                             const bool IsTopScope,
14840                             Sema &S) {
14841 
14842   // Determine whether we are capturing by reference or by value.
14843   bool ByRef = false;
14844   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14845     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14846   } else {
14847     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14848   }
14849 
14850   // Compute the type of the field that will capture this variable.
14851   if (ByRef) {
14852     // C++11 [expr.prim.lambda]p15:
14853     //   An entity is captured by reference if it is implicitly or
14854     //   explicitly captured but not captured by copy. It is
14855     //   unspecified whether additional unnamed non-static data
14856     //   members are declared in the closure type for entities
14857     //   captured by reference.
14858     //
14859     // FIXME: It is not clear whether we want to build an lvalue reference
14860     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14861     // to do the former, while EDG does the latter. Core issue 1249 will
14862     // clarify, but for now we follow GCC because it's a more permissive and
14863     // easily defensible position.
14864     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14865   } else {
14866     // C++11 [expr.prim.lambda]p14:
14867     //   For each entity captured by copy, an unnamed non-static
14868     //   data member is declared in the closure type. The
14869     //   declaration order of these members is unspecified. The type
14870     //   of such a data member is the type of the corresponding
14871     //   captured entity if the entity is not a reference to an
14872     //   object, or the referenced type otherwise. [Note: If the
14873     //   captured entity is a reference to a function, the
14874     //   corresponding data member is also a reference to a
14875     //   function. - end note ]
14876     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14877       if (!RefType->getPointeeType()->isFunctionType())
14878         CaptureType = RefType->getPointeeType();
14879     }
14880 
14881     // Forbid the lambda copy-capture of autoreleasing variables.
14882     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14883       if (BuildAndDiagnose) {
14884         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14885         S.Diag(Var->getLocation(), diag::note_previous_decl)
14886           << Var->getDeclName();
14887       }
14888       return false;
14889     }
14890 
14891     // Make sure that by-copy captures are of a complete and non-abstract type.
14892     if (BuildAndDiagnose) {
14893       if (!CaptureType->isDependentType() &&
14894           S.RequireCompleteType(Loc, CaptureType,
14895                                 diag::err_capture_of_incomplete_type,
14896                                 Var->getDeclName()))
14897         return false;
14898 
14899       if (S.RequireNonAbstractType(Loc, CaptureType,
14900                                    diag::err_capture_of_abstract_type))
14901         return false;
14902     }
14903   }
14904 
14905   // Capture this variable in the lambda.
14906   if (BuildAndDiagnose)
14907     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14908                             RefersToCapturedVariable);
14909 
14910   // Compute the type of a reference to this captured variable.
14911   if (ByRef)
14912     DeclRefType = CaptureType.getNonReferenceType();
14913   else {
14914     // C++ [expr.prim.lambda]p5:
14915     //   The closure type for a lambda-expression has a public inline
14916     //   function call operator [...]. This function call operator is
14917     //   declared const (9.3.1) if and only if the lambda-expression's
14918     //   parameter-declaration-clause is not followed by mutable.
14919     DeclRefType = CaptureType.getNonReferenceType();
14920     if (!LSI->Mutable && !CaptureType->isReferenceType())
14921       DeclRefType.addConst();
14922   }
14923 
14924   // Add the capture.
14925   if (BuildAndDiagnose)
14926     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14927                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14928 
14929   return true;
14930 }
14931 
14932 bool Sema::tryCaptureVariable(
14933     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14934     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14935     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14936   // An init-capture is notionally from the context surrounding its
14937   // declaration, but its parent DC is the lambda class.
14938   DeclContext *VarDC = Var->getDeclContext();
14939   if (Var->isInitCapture())
14940     VarDC = VarDC->getParent();
14941 
14942   DeclContext *DC = CurContext;
14943   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14944       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14945   // We need to sync up the Declaration Context with the
14946   // FunctionScopeIndexToStopAt
14947   if (FunctionScopeIndexToStopAt) {
14948     unsigned FSIndex = FunctionScopes.size() - 1;
14949     while (FSIndex != MaxFunctionScopesIndex) {
14950       DC = getLambdaAwareParentOfDeclContext(DC);
14951       --FSIndex;
14952     }
14953   }
14954 
14955 
14956   // If the variable is declared in the current context, there is no need to
14957   // capture it.
14958   if (VarDC == DC) return true;
14959 
14960   // Capture global variables if it is required to use private copy of this
14961   // variable.
14962   bool IsGlobal = !Var->hasLocalStorage();
14963   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14964     return true;
14965   Var = Var->getCanonicalDecl();
14966 
14967   // Walk up the stack to determine whether we can capture the variable,
14968   // performing the "simple" checks that don't depend on type. We stop when
14969   // we've either hit the declared scope of the variable or find an existing
14970   // capture of that variable.  We start from the innermost capturing-entity
14971   // (the DC) and ensure that all intervening capturing-entities
14972   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14973   // declcontext can either capture the variable or have already captured
14974   // the variable.
14975   CaptureType = Var->getType();
14976   DeclRefType = CaptureType.getNonReferenceType();
14977   bool Nested = false;
14978   bool Explicit = (Kind != TryCapture_Implicit);
14979   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14980   do {
14981     // Only block literals, captured statements, and lambda expressions can
14982     // capture; other scopes don't work.
14983     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14984                                                               ExprLoc,
14985                                                               BuildAndDiagnose,
14986                                                               *this);
14987     // We need to check for the parent *first* because, if we *have*
14988     // private-captured a global variable, we need to recursively capture it in
14989     // intermediate blocks, lambdas, etc.
14990     if (!ParentDC) {
14991       if (IsGlobal) {
14992         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14993         break;
14994       }
14995       return true;
14996     }
14997 
14998     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14999     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15000 
15001 
15002     // Check whether we've already captured it.
15003     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15004                                              DeclRefType)) {
15005       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15006       break;
15007     }
15008     // If we are instantiating a generic lambda call operator body,
15009     // we do not want to capture new variables.  What was captured
15010     // during either a lambdas transformation or initial parsing
15011     // should be used.
15012     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15013       if (BuildAndDiagnose) {
15014         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15015         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15016           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15017           Diag(Var->getLocation(), diag::note_previous_decl)
15018              << Var->getDeclName();
15019           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
15020         } else
15021           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15022       }
15023       return true;
15024     }
15025     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15026     // certain types of variables (unnamed, variably modified types etc.)
15027     // so check for eligibility.
15028     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15029        return true;
15030 
15031     // Try to capture variable-length arrays types.
15032     if (Var->getType()->isVariablyModifiedType()) {
15033       // We're going to walk down into the type and look for VLA
15034       // expressions.
15035       QualType QTy = Var->getType();
15036       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15037         QTy = PVD->getOriginalType();
15038       captureVariablyModifiedType(Context, QTy, CSI);
15039     }
15040 
15041     if (getLangOpts().OpenMP) {
15042       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15043         // OpenMP private variables should not be captured in outer scope, so
15044         // just break here. Similarly, global variables that are captured in a
15045         // target region should not be captured outside the scope of the region.
15046         if (RSI->CapRegionKind == CR_OpenMP) {
15047           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15048           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15049                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15050           // When we detect target captures we are looking from inside the
15051           // target region, therefore we need to propagate the capture from the
15052           // enclosing region. Therefore, the capture is not initially nested.
15053           if (IsTargetCap)
15054             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15055 
15056           if (IsTargetCap || IsOpenMPPrivateDecl) {
15057             Nested = !IsTargetCap;
15058             DeclRefType = DeclRefType.getUnqualifiedType();
15059             CaptureType = Context.getLValueReferenceType(DeclRefType);
15060             break;
15061           }
15062         }
15063       }
15064     }
15065     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15066       // No capture-default, and this is not an explicit capture
15067       // so cannot capture this variable.
15068       if (BuildAndDiagnose) {
15069         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15070         Diag(Var->getLocation(), diag::note_previous_decl)
15071           << Var->getDeclName();
15072         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15073           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
15074                diag::note_lambda_decl);
15075         // FIXME: If we error out because an outer lambda can not implicitly
15076         // capture a variable that an inner lambda explicitly captures, we
15077         // should have the inner lambda do the explicit capture - because
15078         // it makes for cleaner diagnostics later.  This would purely be done
15079         // so that the diagnostic does not misleadingly claim that a variable
15080         // can not be captured by a lambda implicitly even though it is captured
15081         // explicitly.  Suggestion:
15082         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15083         //    at the function head
15084         //  - cache the StartingDeclContext - this must be a lambda
15085         //  - captureInLambda in the innermost lambda the variable.
15086       }
15087       return true;
15088     }
15089 
15090     FunctionScopesIndex--;
15091     DC = ParentDC;
15092     Explicit = false;
15093   } while (!VarDC->Equals(DC));
15094 
15095   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15096   // computing the type of the capture at each step, checking type-specific
15097   // requirements, and adding captures if requested.
15098   // If the variable had already been captured previously, we start capturing
15099   // at the lambda nested within that one.
15100   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15101        ++I) {
15102     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15103 
15104     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15105       if (!captureInBlock(BSI, Var, ExprLoc,
15106                           BuildAndDiagnose, CaptureType,
15107                           DeclRefType, Nested, *this))
15108         return true;
15109       Nested = true;
15110     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15111       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15112                                    BuildAndDiagnose, CaptureType,
15113                                    DeclRefType, Nested, *this))
15114         return true;
15115       Nested = true;
15116     } else {
15117       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15118       if (!captureInLambda(LSI, Var, ExprLoc,
15119                            BuildAndDiagnose, CaptureType,
15120                            DeclRefType, Nested, Kind, EllipsisLoc,
15121                             /*IsTopScope*/I == N - 1, *this))
15122         return true;
15123       Nested = true;
15124     }
15125   }
15126   return false;
15127 }
15128 
15129 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15130                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15131   QualType CaptureType;
15132   QualType DeclRefType;
15133   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15134                             /*BuildAndDiagnose=*/true, CaptureType,
15135                             DeclRefType, nullptr);
15136 }
15137 
15138 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15139   QualType CaptureType;
15140   QualType DeclRefType;
15141   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15142                              /*BuildAndDiagnose=*/false, CaptureType,
15143                              DeclRefType, nullptr);
15144 }
15145 
15146 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15147   QualType CaptureType;
15148   QualType DeclRefType;
15149 
15150   // Determine whether we can capture this variable.
15151   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15152                          /*BuildAndDiagnose=*/false, CaptureType,
15153                          DeclRefType, nullptr))
15154     return QualType();
15155 
15156   return DeclRefType;
15157 }
15158 
15159 
15160 
15161 // If either the type of the variable or the initializer is dependent,
15162 // return false. Otherwise, determine whether the variable is a constant
15163 // expression. Use this if you need to know if a variable that might or
15164 // might not be dependent is truly a constant expression.
15165 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15166     ASTContext &Context) {
15167 
15168   if (Var->getType()->isDependentType())
15169     return false;
15170   const VarDecl *DefVD = nullptr;
15171   Var->getAnyInitializer(DefVD);
15172   if (!DefVD)
15173     return false;
15174   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15175   Expr *Init = cast<Expr>(Eval->Value);
15176   if (Init->isValueDependent())
15177     return false;
15178   return IsVariableAConstantExpression(Var, Context);
15179 }
15180 
15181 
15182 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15183   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15184   // an object that satisfies the requirements for appearing in a
15185   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15186   // is immediately applied."  This function handles the lvalue-to-rvalue
15187   // conversion part.
15188   MaybeODRUseExprs.erase(E->IgnoreParens());
15189 
15190   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15191   // to a variable that is a constant expression, and if so, identify it as
15192   // a reference to a variable that does not involve an odr-use of that
15193   // variable.
15194   if (LambdaScopeInfo *LSI = getCurLambda()) {
15195     Expr *SansParensExpr = E->IgnoreParens();
15196     VarDecl *Var = nullptr;
15197     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15198       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15199     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15200       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15201 
15202     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15203       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15204   }
15205 }
15206 
15207 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15208   Res = CorrectDelayedTyposInExpr(Res);
15209 
15210   if (!Res.isUsable())
15211     return Res;
15212 
15213   // If a constant-expression is a reference to a variable where we delay
15214   // deciding whether it is an odr-use, just assume we will apply the
15215   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15216   // (a non-type template argument), we have special handling anyway.
15217   UpdateMarkingForLValueToRValue(Res.get());
15218   return Res;
15219 }
15220 
15221 void Sema::CleanupVarDeclMarking() {
15222   for (Expr *E : MaybeODRUseExprs) {
15223     VarDecl *Var;
15224     SourceLocation Loc;
15225     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15226       Var = cast<VarDecl>(DRE->getDecl());
15227       Loc = DRE->getLocation();
15228     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15229       Var = cast<VarDecl>(ME->getMemberDecl());
15230       Loc = ME->getMemberLoc();
15231     } else {
15232       llvm_unreachable("Unexpected expression");
15233     }
15234 
15235     MarkVarDeclODRUsed(Var, Loc, *this,
15236                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15237   }
15238 
15239   MaybeODRUseExprs.clear();
15240 }
15241 
15242 
15243 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15244                                     VarDecl *Var, Expr *E) {
15245   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15246          "Invalid Expr argument to DoMarkVarDeclReferenced");
15247   Var->setReferenced();
15248 
15249   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15250 
15251   bool OdrUseContext = isOdrUseContext(SemaRef);
15252   bool UsableInConstantExpr =
15253       Var->isUsableInConstantExpressions(SemaRef.Context);
15254   bool NeedDefinition =
15255       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15256 
15257   VarTemplateSpecializationDecl *VarSpec =
15258       dyn_cast<VarTemplateSpecializationDecl>(Var);
15259   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15260          "Can't instantiate a partial template specialization.");
15261 
15262   // If this might be a member specialization of a static data member, check
15263   // the specialization is visible. We already did the checks for variable
15264   // template specializations when we created them.
15265   if (NeedDefinition && TSK != TSK_Undeclared &&
15266       !isa<VarTemplateSpecializationDecl>(Var))
15267     SemaRef.checkSpecializationVisibility(Loc, Var);
15268 
15269   // Perform implicit instantiation of static data members, static data member
15270   // templates of class templates, and variable template specializations. Delay
15271   // instantiations of variable templates, except for those that could be used
15272   // in a constant expression.
15273   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15274     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15275     // instantiation declaration if a variable is usable in a constant
15276     // expression (among other cases).
15277     bool TryInstantiating =
15278         TSK == TSK_ImplicitInstantiation ||
15279         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15280 
15281     if (TryInstantiating) {
15282       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15283       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15284       if (FirstInstantiation) {
15285         PointOfInstantiation = Loc;
15286         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15287       }
15288 
15289       bool InstantiationDependent = false;
15290       bool IsNonDependent =
15291           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15292                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15293                   : true;
15294 
15295       // Do not instantiate specializations that are still type-dependent.
15296       if (IsNonDependent) {
15297         if (UsableInConstantExpr) {
15298           // Do not defer instantiations of variables that could be used in a
15299           // constant expression.
15300           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15301         } else if (FirstInstantiation ||
15302                    isa<VarTemplateSpecializationDecl>(Var)) {
15303           // FIXME: For a specialization of a variable template, we don't
15304           // distinguish between "declaration and type implicitly instantiated"
15305           // and "implicit instantiation of definition requested", so we have
15306           // no direct way to avoid enqueueing the pending instantiation
15307           // multiple times.
15308           SemaRef.PendingInstantiations
15309               .push_back(std::make_pair(Var, PointOfInstantiation));
15310         }
15311       }
15312     }
15313   }
15314 
15315   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15316   // the requirements for appearing in a constant expression (5.19) and, if
15317   // it is an object, the lvalue-to-rvalue conversion (4.1)
15318   // is immediately applied."  We check the first part here, and
15319   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15320   // Note that we use the C++11 definition everywhere because nothing in
15321   // C++03 depends on whether we get the C++03 version correct. The second
15322   // part does not apply to references, since they are not objects.
15323   if (OdrUseContext && E &&
15324       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15325     // A reference initialized by a constant expression can never be
15326     // odr-used, so simply ignore it.
15327     if (!Var->getType()->isReferenceType() ||
15328         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15329       SemaRef.MaybeODRUseExprs.insert(E);
15330   } else if (OdrUseContext) {
15331     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15332                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15333   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15334     // If this is a dependent context, we don't need to mark variables as
15335     // odr-used, but we may still need to track them for lambda capture.
15336     // FIXME: Do we also need to do this inside dependent typeid expressions
15337     // (which are modeled as unevaluated at this point)?
15338     const bool RefersToEnclosingScope =
15339         (SemaRef.CurContext != Var->getDeclContext() &&
15340          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15341     if (RefersToEnclosingScope) {
15342       LambdaScopeInfo *const LSI =
15343           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15344       if (LSI && (!LSI->CallOperator ||
15345                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15346         // If a variable could potentially be odr-used, defer marking it so
15347         // until we finish analyzing the full expression for any
15348         // lvalue-to-rvalue
15349         // or discarded value conversions that would obviate odr-use.
15350         // Add it to the list of potential captures that will be analyzed
15351         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15352         // unless the variable is a reference that was initialized by a constant
15353         // expression (this will never need to be captured or odr-used).
15354         assert(E && "Capture variable should be used in an expression.");
15355         if (!Var->getType()->isReferenceType() ||
15356             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15357           LSI->addPotentialCapture(E->IgnoreParens());
15358       }
15359     }
15360   }
15361 }
15362 
15363 /// Mark a variable referenced, and check whether it is odr-used
15364 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15365 /// used directly for normal expressions referring to VarDecl.
15366 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15367   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15368 }
15369 
15370 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15371                                Decl *D, Expr *E, bool MightBeOdrUse) {
15372   if (SemaRef.isInOpenMPDeclareTargetContext())
15373     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15374 
15375   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15376     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15377     return;
15378   }
15379 
15380   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15381 
15382   // If this is a call to a method via a cast, also mark the method in the
15383   // derived class used in case codegen can devirtualize the call.
15384   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15385   if (!ME)
15386     return;
15387   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15388   if (!MD)
15389     return;
15390   // Only attempt to devirtualize if this is truly a virtual call.
15391   bool IsVirtualCall = MD->isVirtual() &&
15392                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15393   if (!IsVirtualCall)
15394     return;
15395 
15396   // If it's possible to devirtualize the call, mark the called function
15397   // referenced.
15398   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15399       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15400   if (DM)
15401     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15402 }
15403 
15404 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15405 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15406   // TODO: update this with DR# once a defect report is filed.
15407   // C++11 defect. The address of a pure member should not be an ODR use, even
15408   // if it's a qualified reference.
15409   bool OdrUse = true;
15410   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15411     if (Method->isVirtual() &&
15412         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15413       OdrUse = false;
15414   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15415 }
15416 
15417 /// Perform reference-marking and odr-use handling for a MemberExpr.
15418 void Sema::MarkMemberReferenced(MemberExpr *E) {
15419   // C++11 [basic.def.odr]p2:
15420   //   A non-overloaded function whose name appears as a potentially-evaluated
15421   //   expression or a member of a set of candidate functions, if selected by
15422   //   overload resolution when referred to from a potentially-evaluated
15423   //   expression, is odr-used, unless it is a pure virtual function and its
15424   //   name is not explicitly qualified.
15425   bool MightBeOdrUse = true;
15426   if (E->performsVirtualDispatch(getLangOpts())) {
15427     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15428       if (Method->isPure())
15429         MightBeOdrUse = false;
15430   }
15431   SourceLocation Loc = E->getMemberLoc().isValid() ?
15432                             E->getMemberLoc() : E->getLocStart();
15433   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15434 }
15435 
15436 /// Perform marking for a reference to an arbitrary declaration.  It
15437 /// marks the declaration referenced, and performs odr-use checking for
15438 /// functions and variables. This method should not be used when building a
15439 /// normal expression which refers to a variable.
15440 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15441                                  bool MightBeOdrUse) {
15442   if (MightBeOdrUse) {
15443     if (auto *VD = dyn_cast<VarDecl>(D)) {
15444       MarkVariableReferenced(Loc, VD);
15445       return;
15446     }
15447   }
15448   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15449     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15450     return;
15451   }
15452   D->setReferenced();
15453 }
15454 
15455 namespace {
15456   // Mark all of the declarations used by a type as referenced.
15457   // FIXME: Not fully implemented yet! We need to have a better understanding
15458   // of when we're entering a context we should not recurse into.
15459   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15460   // TreeTransforms rebuilding the type in a new context. Rather than
15461   // duplicating the TreeTransform logic, we should consider reusing it here.
15462   // Currently that causes problems when rebuilding LambdaExprs.
15463   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15464     Sema &S;
15465     SourceLocation Loc;
15466 
15467   public:
15468     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15469 
15470     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15471 
15472     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15473   };
15474 }
15475 
15476 bool MarkReferencedDecls::TraverseTemplateArgument(
15477     const TemplateArgument &Arg) {
15478   {
15479     // A non-type template argument is a constant-evaluated context.
15480     EnterExpressionEvaluationContext Evaluated(
15481         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15482     if (Arg.getKind() == TemplateArgument::Declaration) {
15483       if (Decl *D = Arg.getAsDecl())
15484         S.MarkAnyDeclReferenced(Loc, D, true);
15485     } else if (Arg.getKind() == TemplateArgument::Expression) {
15486       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15487     }
15488   }
15489 
15490   return Inherited::TraverseTemplateArgument(Arg);
15491 }
15492 
15493 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15494   MarkReferencedDecls Marker(*this, Loc);
15495   Marker.TraverseType(T);
15496 }
15497 
15498 namespace {
15499   /// Helper class that marks all of the declarations referenced by
15500   /// potentially-evaluated subexpressions as "referenced".
15501   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15502     Sema &S;
15503     bool SkipLocalVariables;
15504 
15505   public:
15506     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15507 
15508     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15509       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15510 
15511     void VisitDeclRefExpr(DeclRefExpr *E) {
15512       // If we were asked not to visit local variables, don't.
15513       if (SkipLocalVariables) {
15514         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15515           if (VD->hasLocalStorage())
15516             return;
15517       }
15518 
15519       S.MarkDeclRefReferenced(E);
15520     }
15521 
15522     void VisitMemberExpr(MemberExpr *E) {
15523       S.MarkMemberReferenced(E);
15524       Inherited::VisitMemberExpr(E);
15525     }
15526 
15527     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15528       S.MarkFunctionReferenced(E->getLocStart(),
15529             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15530       Visit(E->getSubExpr());
15531     }
15532 
15533     void VisitCXXNewExpr(CXXNewExpr *E) {
15534       if (E->getOperatorNew())
15535         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15536       if (E->getOperatorDelete())
15537         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15538       Inherited::VisitCXXNewExpr(E);
15539     }
15540 
15541     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15542       if (E->getOperatorDelete())
15543         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15544       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15545       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15546         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15547         S.MarkFunctionReferenced(E->getLocStart(),
15548                                     S.LookupDestructor(Record));
15549       }
15550 
15551       Inherited::VisitCXXDeleteExpr(E);
15552     }
15553 
15554     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15555       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15556       Inherited::VisitCXXConstructExpr(E);
15557     }
15558 
15559     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15560       Visit(E->getExpr());
15561     }
15562 
15563     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15564       Inherited::VisitImplicitCastExpr(E);
15565 
15566       if (E->getCastKind() == CK_LValueToRValue)
15567         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15568     }
15569   };
15570 }
15571 
15572 /// Mark any declarations that appear within this expression or any
15573 /// potentially-evaluated subexpressions as "referenced".
15574 ///
15575 /// \param SkipLocalVariables If true, don't mark local variables as
15576 /// 'referenced'.
15577 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15578                                             bool SkipLocalVariables) {
15579   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15580 }
15581 
15582 /// Emit a diagnostic that describes an effect on the run-time behavior
15583 /// of the program being compiled.
15584 ///
15585 /// This routine emits the given diagnostic when the code currently being
15586 /// type-checked is "potentially evaluated", meaning that there is a
15587 /// possibility that the code will actually be executable. Code in sizeof()
15588 /// expressions, code used only during overload resolution, etc., are not
15589 /// potentially evaluated. This routine will suppress such diagnostics or,
15590 /// in the absolutely nutty case of potentially potentially evaluated
15591 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15592 /// later.
15593 ///
15594 /// This routine should be used for all diagnostics that describe the run-time
15595 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15596 /// Failure to do so will likely result in spurious diagnostics or failures
15597 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15598 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15599                                const PartialDiagnostic &PD) {
15600   switch (ExprEvalContexts.back().Context) {
15601   case ExpressionEvaluationContext::Unevaluated:
15602   case ExpressionEvaluationContext::UnevaluatedList:
15603   case ExpressionEvaluationContext::UnevaluatedAbstract:
15604   case ExpressionEvaluationContext::DiscardedStatement:
15605     // The argument will never be evaluated, so don't complain.
15606     break;
15607 
15608   case ExpressionEvaluationContext::ConstantEvaluated:
15609     // Relevant diagnostics should be produced by constant evaluation.
15610     break;
15611 
15612   case ExpressionEvaluationContext::PotentiallyEvaluated:
15613   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15614     if (Statement && getCurFunctionOrMethodDecl()) {
15615       FunctionScopes.back()->PossiblyUnreachableDiags.
15616         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15617       return true;
15618     }
15619 
15620     // The initializer of a constexpr variable or of the first declaration of a
15621     // static data member is not syntactically a constant evaluated constant,
15622     // but nonetheless is always required to be a constant expression, so we
15623     // can skip diagnosing.
15624     // FIXME: Using the mangling context here is a hack.
15625     if (auto *VD = dyn_cast_or_null<VarDecl>(
15626             ExprEvalContexts.back().ManglingContextDecl)) {
15627       if (VD->isConstexpr() ||
15628           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15629         break;
15630       // FIXME: For any other kind of variable, we should build a CFG for its
15631       // initializer and check whether the context in question is reachable.
15632     }
15633 
15634     Diag(Loc, PD);
15635     return true;
15636   }
15637 
15638   return false;
15639 }
15640 
15641 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15642                                CallExpr *CE, FunctionDecl *FD) {
15643   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15644     return false;
15645 
15646   // If we're inside a decltype's expression, don't check for a valid return
15647   // type or construct temporaries until we know whether this is the last call.
15648   if (ExprEvalContexts.back().ExprContext ==
15649       ExpressionEvaluationContextRecord::EK_Decltype) {
15650     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15651     return false;
15652   }
15653 
15654   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15655     FunctionDecl *FD;
15656     CallExpr *CE;
15657 
15658   public:
15659     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15660       : FD(FD), CE(CE) { }
15661 
15662     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15663       if (!FD) {
15664         S.Diag(Loc, diag::err_call_incomplete_return)
15665           << T << CE->getSourceRange();
15666         return;
15667       }
15668 
15669       S.Diag(Loc, diag::err_call_function_incomplete_return)
15670         << CE->getSourceRange() << FD->getDeclName() << T;
15671       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15672           << FD->getDeclName();
15673     }
15674   } Diagnoser(FD, CE);
15675 
15676   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15677     return true;
15678 
15679   return false;
15680 }
15681 
15682 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15683 // will prevent this condition from triggering, which is what we want.
15684 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15685   SourceLocation Loc;
15686 
15687   unsigned diagnostic = diag::warn_condition_is_assignment;
15688   bool IsOrAssign = false;
15689 
15690   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15691     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15692       return;
15693 
15694     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15695 
15696     // Greylist some idioms by putting them into a warning subcategory.
15697     if (ObjCMessageExpr *ME
15698           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15699       Selector Sel = ME->getSelector();
15700 
15701       // self = [<foo> init...]
15702       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15703         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15704 
15705       // <foo> = [<bar> nextObject]
15706       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15707         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15708     }
15709 
15710     Loc = Op->getOperatorLoc();
15711   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15712     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15713       return;
15714 
15715     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15716     Loc = Op->getOperatorLoc();
15717   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15718     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15719   else {
15720     // Not an assignment.
15721     return;
15722   }
15723 
15724   Diag(Loc, diagnostic) << E->getSourceRange();
15725 
15726   SourceLocation Open = E->getLocStart();
15727   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15728   Diag(Loc, diag::note_condition_assign_silence)
15729         << FixItHint::CreateInsertion(Open, "(")
15730         << FixItHint::CreateInsertion(Close, ")");
15731 
15732   if (IsOrAssign)
15733     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15734       << FixItHint::CreateReplacement(Loc, "!=");
15735   else
15736     Diag(Loc, diag::note_condition_assign_to_comparison)
15737       << FixItHint::CreateReplacement(Loc, "==");
15738 }
15739 
15740 /// Redundant parentheses over an equality comparison can indicate
15741 /// that the user intended an assignment used as condition.
15742 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15743   // Don't warn if the parens came from a macro.
15744   SourceLocation parenLoc = ParenE->getLocStart();
15745   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15746     return;
15747   // Don't warn for dependent expressions.
15748   if (ParenE->isTypeDependent())
15749     return;
15750 
15751   Expr *E = ParenE->IgnoreParens();
15752 
15753   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15754     if (opE->getOpcode() == BO_EQ &&
15755         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15756                                                            == Expr::MLV_Valid) {
15757       SourceLocation Loc = opE->getOperatorLoc();
15758 
15759       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15760       SourceRange ParenERange = ParenE->getSourceRange();
15761       Diag(Loc, diag::note_equality_comparison_silence)
15762         << FixItHint::CreateRemoval(ParenERange.getBegin())
15763         << FixItHint::CreateRemoval(ParenERange.getEnd());
15764       Diag(Loc, diag::note_equality_comparison_to_assign)
15765         << FixItHint::CreateReplacement(Loc, "=");
15766     }
15767 }
15768 
15769 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15770                                        bool IsConstexpr) {
15771   DiagnoseAssignmentAsCondition(E);
15772   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15773     DiagnoseEqualityWithExtraParens(parenE);
15774 
15775   ExprResult result = CheckPlaceholderExpr(E);
15776   if (result.isInvalid()) return ExprError();
15777   E = result.get();
15778 
15779   if (!E->isTypeDependent()) {
15780     if (getLangOpts().CPlusPlus)
15781       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15782 
15783     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15784     if (ERes.isInvalid())
15785       return ExprError();
15786     E = ERes.get();
15787 
15788     QualType T = E->getType();
15789     if (!T->isScalarType()) { // C99 6.8.4.1p1
15790       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15791         << T << E->getSourceRange();
15792       return ExprError();
15793     }
15794     CheckBoolLikeConversion(E, Loc);
15795   }
15796 
15797   return E;
15798 }
15799 
15800 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15801                                            Expr *SubExpr, ConditionKind CK) {
15802   // Empty conditions are valid in for-statements.
15803   if (!SubExpr)
15804     return ConditionResult();
15805 
15806   ExprResult Cond;
15807   switch (CK) {
15808   case ConditionKind::Boolean:
15809     Cond = CheckBooleanCondition(Loc, SubExpr);
15810     break;
15811 
15812   case ConditionKind::ConstexprIf:
15813     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15814     break;
15815 
15816   case ConditionKind::Switch:
15817     Cond = CheckSwitchCondition(Loc, SubExpr);
15818     break;
15819   }
15820   if (Cond.isInvalid())
15821     return ConditionError();
15822 
15823   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15824   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15825   if (!FullExpr.get())
15826     return ConditionError();
15827 
15828   return ConditionResult(*this, nullptr, FullExpr,
15829                          CK == ConditionKind::ConstexprIf);
15830 }
15831 
15832 namespace {
15833   /// A visitor for rebuilding a call to an __unknown_any expression
15834   /// to have an appropriate type.
15835   struct RebuildUnknownAnyFunction
15836     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15837 
15838     Sema &S;
15839 
15840     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15841 
15842     ExprResult VisitStmt(Stmt *S) {
15843       llvm_unreachable("unexpected statement!");
15844     }
15845 
15846     ExprResult VisitExpr(Expr *E) {
15847       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15848         << E->getSourceRange();
15849       return ExprError();
15850     }
15851 
15852     /// Rebuild an expression which simply semantically wraps another
15853     /// expression which it shares the type and value kind of.
15854     template <class T> ExprResult rebuildSugarExpr(T *E) {
15855       ExprResult SubResult = Visit(E->getSubExpr());
15856       if (SubResult.isInvalid()) return ExprError();
15857 
15858       Expr *SubExpr = SubResult.get();
15859       E->setSubExpr(SubExpr);
15860       E->setType(SubExpr->getType());
15861       E->setValueKind(SubExpr->getValueKind());
15862       assert(E->getObjectKind() == OK_Ordinary);
15863       return E;
15864     }
15865 
15866     ExprResult VisitParenExpr(ParenExpr *E) {
15867       return rebuildSugarExpr(E);
15868     }
15869 
15870     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15871       return rebuildSugarExpr(E);
15872     }
15873 
15874     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15875       ExprResult SubResult = Visit(E->getSubExpr());
15876       if (SubResult.isInvalid()) return ExprError();
15877 
15878       Expr *SubExpr = SubResult.get();
15879       E->setSubExpr(SubExpr);
15880       E->setType(S.Context.getPointerType(SubExpr->getType()));
15881       assert(E->getValueKind() == VK_RValue);
15882       assert(E->getObjectKind() == OK_Ordinary);
15883       return E;
15884     }
15885 
15886     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15887       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15888 
15889       E->setType(VD->getType());
15890 
15891       assert(E->getValueKind() == VK_RValue);
15892       if (S.getLangOpts().CPlusPlus &&
15893           !(isa<CXXMethodDecl>(VD) &&
15894             cast<CXXMethodDecl>(VD)->isInstance()))
15895         E->setValueKind(VK_LValue);
15896 
15897       return E;
15898     }
15899 
15900     ExprResult VisitMemberExpr(MemberExpr *E) {
15901       return resolveDecl(E, E->getMemberDecl());
15902     }
15903 
15904     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15905       return resolveDecl(E, E->getDecl());
15906     }
15907   };
15908 }
15909 
15910 /// Given a function expression of unknown-any type, try to rebuild it
15911 /// to have a function type.
15912 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15913   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15914   if (Result.isInvalid()) return ExprError();
15915   return S.DefaultFunctionArrayConversion(Result.get());
15916 }
15917 
15918 namespace {
15919   /// A visitor for rebuilding an expression of type __unknown_anytype
15920   /// into one which resolves the type directly on the referring
15921   /// expression.  Strict preservation of the original source
15922   /// structure is not a goal.
15923   struct RebuildUnknownAnyExpr
15924     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15925 
15926     Sema &S;
15927 
15928     /// The current destination type.
15929     QualType DestType;
15930 
15931     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15932       : S(S), DestType(CastType) {}
15933 
15934     ExprResult VisitStmt(Stmt *S) {
15935       llvm_unreachable("unexpected statement!");
15936     }
15937 
15938     ExprResult VisitExpr(Expr *E) {
15939       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15940         << E->getSourceRange();
15941       return ExprError();
15942     }
15943 
15944     ExprResult VisitCallExpr(CallExpr *E);
15945     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15946 
15947     /// Rebuild an expression which simply semantically wraps another
15948     /// expression which it shares the type and value kind of.
15949     template <class T> ExprResult rebuildSugarExpr(T *E) {
15950       ExprResult SubResult = Visit(E->getSubExpr());
15951       if (SubResult.isInvalid()) return ExprError();
15952       Expr *SubExpr = SubResult.get();
15953       E->setSubExpr(SubExpr);
15954       E->setType(SubExpr->getType());
15955       E->setValueKind(SubExpr->getValueKind());
15956       assert(E->getObjectKind() == OK_Ordinary);
15957       return E;
15958     }
15959 
15960     ExprResult VisitParenExpr(ParenExpr *E) {
15961       return rebuildSugarExpr(E);
15962     }
15963 
15964     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15965       return rebuildSugarExpr(E);
15966     }
15967 
15968     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15969       const PointerType *Ptr = DestType->getAs<PointerType>();
15970       if (!Ptr) {
15971         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15972           << E->getSourceRange();
15973         return ExprError();
15974       }
15975 
15976       if (isa<CallExpr>(E->getSubExpr())) {
15977         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15978           << E->getSourceRange();
15979         return ExprError();
15980       }
15981 
15982       assert(E->getValueKind() == VK_RValue);
15983       assert(E->getObjectKind() == OK_Ordinary);
15984       E->setType(DestType);
15985 
15986       // Build the sub-expression as if it were an object of the pointee type.
15987       DestType = Ptr->getPointeeType();
15988       ExprResult SubResult = Visit(E->getSubExpr());
15989       if (SubResult.isInvalid()) return ExprError();
15990       E->setSubExpr(SubResult.get());
15991       return E;
15992     }
15993 
15994     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15995 
15996     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15997 
15998     ExprResult VisitMemberExpr(MemberExpr *E) {
15999       return resolveDecl(E, E->getMemberDecl());
16000     }
16001 
16002     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16003       return resolveDecl(E, E->getDecl());
16004     }
16005   };
16006 }
16007 
16008 /// Rebuilds a call expression which yielded __unknown_anytype.
16009 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16010   Expr *CalleeExpr = E->getCallee();
16011 
16012   enum FnKind {
16013     FK_MemberFunction,
16014     FK_FunctionPointer,
16015     FK_BlockPointer
16016   };
16017 
16018   FnKind Kind;
16019   QualType CalleeType = CalleeExpr->getType();
16020   if (CalleeType == S.Context.BoundMemberTy) {
16021     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16022     Kind = FK_MemberFunction;
16023     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16024   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16025     CalleeType = Ptr->getPointeeType();
16026     Kind = FK_FunctionPointer;
16027   } else {
16028     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16029     Kind = FK_BlockPointer;
16030   }
16031   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16032 
16033   // Verify that this is a legal result type of a function.
16034   if (DestType->isArrayType() || DestType->isFunctionType()) {
16035     unsigned diagID = diag::err_func_returning_array_function;
16036     if (Kind == FK_BlockPointer)
16037       diagID = diag::err_block_returning_array_function;
16038 
16039     S.Diag(E->getExprLoc(), diagID)
16040       << DestType->isFunctionType() << DestType;
16041     return ExprError();
16042   }
16043 
16044   // Otherwise, go ahead and set DestType as the call's result.
16045   E->setType(DestType.getNonLValueExprType(S.Context));
16046   E->setValueKind(Expr::getValueKindForType(DestType));
16047   assert(E->getObjectKind() == OK_Ordinary);
16048 
16049   // Rebuild the function type, replacing the result type with DestType.
16050   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16051   if (Proto) {
16052     // __unknown_anytype(...) is a special case used by the debugger when
16053     // it has no idea what a function's signature is.
16054     //
16055     // We want to build this call essentially under the K&R
16056     // unprototyped rules, but making a FunctionNoProtoType in C++
16057     // would foul up all sorts of assumptions.  However, we cannot
16058     // simply pass all arguments as variadic arguments, nor can we
16059     // portably just call the function under a non-variadic type; see
16060     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16061     // However, it turns out that in practice it is generally safe to
16062     // call a function declared as "A foo(B,C,D);" under the prototype
16063     // "A foo(B,C,D,...);".  The only known exception is with the
16064     // Windows ABI, where any variadic function is implicitly cdecl
16065     // regardless of its normal CC.  Therefore we change the parameter
16066     // types to match the types of the arguments.
16067     //
16068     // This is a hack, but it is far superior to moving the
16069     // corresponding target-specific code from IR-gen to Sema/AST.
16070 
16071     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16072     SmallVector<QualType, 8> ArgTypes;
16073     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16074       ArgTypes.reserve(E->getNumArgs());
16075       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16076         Expr *Arg = E->getArg(i);
16077         QualType ArgType = Arg->getType();
16078         if (E->isLValue()) {
16079           ArgType = S.Context.getLValueReferenceType(ArgType);
16080         } else if (E->isXValue()) {
16081           ArgType = S.Context.getRValueReferenceType(ArgType);
16082         }
16083         ArgTypes.push_back(ArgType);
16084       }
16085       ParamTypes = ArgTypes;
16086     }
16087     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16088                                          Proto->getExtProtoInfo());
16089   } else {
16090     DestType = S.Context.getFunctionNoProtoType(DestType,
16091                                                 FnType->getExtInfo());
16092   }
16093 
16094   // Rebuild the appropriate pointer-to-function type.
16095   switch (Kind) {
16096   case FK_MemberFunction:
16097     // Nothing to do.
16098     break;
16099 
16100   case FK_FunctionPointer:
16101     DestType = S.Context.getPointerType(DestType);
16102     break;
16103 
16104   case FK_BlockPointer:
16105     DestType = S.Context.getBlockPointerType(DestType);
16106     break;
16107   }
16108 
16109   // Finally, we can recurse.
16110   ExprResult CalleeResult = Visit(CalleeExpr);
16111   if (!CalleeResult.isUsable()) return ExprError();
16112   E->setCallee(CalleeResult.get());
16113 
16114   // Bind a temporary if necessary.
16115   return S.MaybeBindToTemporary(E);
16116 }
16117 
16118 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16119   // Verify that this is a legal result type of a call.
16120   if (DestType->isArrayType() || DestType->isFunctionType()) {
16121     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16122       << DestType->isFunctionType() << DestType;
16123     return ExprError();
16124   }
16125 
16126   // Rewrite the method result type if available.
16127   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16128     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16129     Method->setReturnType(DestType);
16130   }
16131 
16132   // Change the type of the message.
16133   E->setType(DestType.getNonReferenceType());
16134   E->setValueKind(Expr::getValueKindForType(DestType));
16135 
16136   return S.MaybeBindToTemporary(E);
16137 }
16138 
16139 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16140   // The only case we should ever see here is a function-to-pointer decay.
16141   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16142     assert(E->getValueKind() == VK_RValue);
16143     assert(E->getObjectKind() == OK_Ordinary);
16144 
16145     E->setType(DestType);
16146 
16147     // Rebuild the sub-expression as the pointee (function) type.
16148     DestType = DestType->castAs<PointerType>()->getPointeeType();
16149 
16150     ExprResult Result = Visit(E->getSubExpr());
16151     if (!Result.isUsable()) return ExprError();
16152 
16153     E->setSubExpr(Result.get());
16154     return E;
16155   } else if (E->getCastKind() == CK_LValueToRValue) {
16156     assert(E->getValueKind() == VK_RValue);
16157     assert(E->getObjectKind() == OK_Ordinary);
16158 
16159     assert(isa<BlockPointerType>(E->getType()));
16160 
16161     E->setType(DestType);
16162 
16163     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16164     DestType = S.Context.getLValueReferenceType(DestType);
16165 
16166     ExprResult Result = Visit(E->getSubExpr());
16167     if (!Result.isUsable()) return ExprError();
16168 
16169     E->setSubExpr(Result.get());
16170     return E;
16171   } else {
16172     llvm_unreachable("Unhandled cast type!");
16173   }
16174 }
16175 
16176 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16177   ExprValueKind ValueKind = VK_LValue;
16178   QualType Type = DestType;
16179 
16180   // We know how to make this work for certain kinds of decls:
16181 
16182   //  - functions
16183   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16184     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16185       DestType = Ptr->getPointeeType();
16186       ExprResult Result = resolveDecl(E, VD);
16187       if (Result.isInvalid()) return ExprError();
16188       return S.ImpCastExprToType(Result.get(), Type,
16189                                  CK_FunctionToPointerDecay, VK_RValue);
16190     }
16191 
16192     if (!Type->isFunctionType()) {
16193       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16194         << VD << E->getSourceRange();
16195       return ExprError();
16196     }
16197     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16198       // We must match the FunctionDecl's type to the hack introduced in
16199       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16200       // type. See the lengthy commentary in that routine.
16201       QualType FDT = FD->getType();
16202       const FunctionType *FnType = FDT->castAs<FunctionType>();
16203       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16204       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16205       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16206         SourceLocation Loc = FD->getLocation();
16207         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16208                                       FD->getDeclContext(),
16209                                       Loc, Loc, FD->getNameInfo().getName(),
16210                                       DestType, FD->getTypeSourceInfo(),
16211                                       SC_None, false/*isInlineSpecified*/,
16212                                       FD->hasPrototype(),
16213                                       false/*isConstexprSpecified*/);
16214 
16215         if (FD->getQualifier())
16216           NewFD->setQualifierInfo(FD->getQualifierLoc());
16217 
16218         SmallVector<ParmVarDecl*, 16> Params;
16219         for (const auto &AI : FT->param_types()) {
16220           ParmVarDecl *Param =
16221             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16222           Param->setScopeInfo(0, Params.size());
16223           Params.push_back(Param);
16224         }
16225         NewFD->setParams(Params);
16226         DRE->setDecl(NewFD);
16227         VD = DRE->getDecl();
16228       }
16229     }
16230 
16231     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16232       if (MD->isInstance()) {
16233         ValueKind = VK_RValue;
16234         Type = S.Context.BoundMemberTy;
16235       }
16236 
16237     // Function references aren't l-values in C.
16238     if (!S.getLangOpts().CPlusPlus)
16239       ValueKind = VK_RValue;
16240 
16241   //  - variables
16242   } else if (isa<VarDecl>(VD)) {
16243     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16244       Type = RefTy->getPointeeType();
16245     } else if (Type->isFunctionType()) {
16246       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16247         << VD << E->getSourceRange();
16248       return ExprError();
16249     }
16250 
16251   //  - nothing else
16252   } else {
16253     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16254       << VD << E->getSourceRange();
16255     return ExprError();
16256   }
16257 
16258   // Modifying the declaration like this is friendly to IR-gen but
16259   // also really dangerous.
16260   VD->setType(DestType);
16261   E->setType(Type);
16262   E->setValueKind(ValueKind);
16263   return E;
16264 }
16265 
16266 /// Check a cast of an unknown-any type.  We intentionally only
16267 /// trigger this for C-style casts.
16268 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16269                                      Expr *CastExpr, CastKind &CastKind,
16270                                      ExprValueKind &VK, CXXCastPath &Path) {
16271   // The type we're casting to must be either void or complete.
16272   if (!CastType->isVoidType() &&
16273       RequireCompleteType(TypeRange.getBegin(), CastType,
16274                           diag::err_typecheck_cast_to_incomplete))
16275     return ExprError();
16276 
16277   // Rewrite the casted expression from scratch.
16278   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16279   if (!result.isUsable()) return ExprError();
16280 
16281   CastExpr = result.get();
16282   VK = CastExpr->getValueKind();
16283   CastKind = CK_NoOp;
16284 
16285   return CastExpr;
16286 }
16287 
16288 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16289   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16290 }
16291 
16292 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16293                                     Expr *arg, QualType &paramType) {
16294   // If the syntactic form of the argument is not an explicit cast of
16295   // any sort, just do default argument promotion.
16296   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16297   if (!castArg) {
16298     ExprResult result = DefaultArgumentPromotion(arg);
16299     if (result.isInvalid()) return ExprError();
16300     paramType = result.get()->getType();
16301     return result;
16302   }
16303 
16304   // Otherwise, use the type that was written in the explicit cast.
16305   assert(!arg->hasPlaceholderType());
16306   paramType = castArg->getTypeAsWritten();
16307 
16308   // Copy-initialize a parameter of that type.
16309   InitializedEntity entity =
16310     InitializedEntity::InitializeParameter(Context, paramType,
16311                                            /*consumed*/ false);
16312   return PerformCopyInitialization(entity, callLoc, arg);
16313 }
16314 
16315 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16316   Expr *orig = E;
16317   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16318   while (true) {
16319     E = E->IgnoreParenImpCasts();
16320     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16321       E = call->getCallee();
16322       diagID = diag::err_uncasted_call_of_unknown_any;
16323     } else {
16324       break;
16325     }
16326   }
16327 
16328   SourceLocation loc;
16329   NamedDecl *d;
16330   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16331     loc = ref->getLocation();
16332     d = ref->getDecl();
16333   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16334     loc = mem->getMemberLoc();
16335     d = mem->getMemberDecl();
16336   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16337     diagID = diag::err_uncasted_call_of_unknown_any;
16338     loc = msg->getSelectorStartLoc();
16339     d = msg->getMethodDecl();
16340     if (!d) {
16341       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16342         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16343         << orig->getSourceRange();
16344       return ExprError();
16345     }
16346   } else {
16347     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16348       << E->getSourceRange();
16349     return ExprError();
16350   }
16351 
16352   S.Diag(loc, diagID) << d << orig->getSourceRange();
16353 
16354   // Never recoverable.
16355   return ExprError();
16356 }
16357 
16358 /// Check for operands with placeholder types and complain if found.
16359 /// Returns ExprError() if there was an error and no recovery was possible.
16360 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16361   if (!getLangOpts().CPlusPlus) {
16362     // C cannot handle TypoExpr nodes on either side of a binop because it
16363     // doesn't handle dependent types properly, so make sure any TypoExprs have
16364     // been dealt with before checking the operands.
16365     ExprResult Result = CorrectDelayedTyposInExpr(E);
16366     if (!Result.isUsable()) return ExprError();
16367     E = Result.get();
16368   }
16369 
16370   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16371   if (!placeholderType) return E;
16372 
16373   switch (placeholderType->getKind()) {
16374 
16375   // Overloaded expressions.
16376   case BuiltinType::Overload: {
16377     // Try to resolve a single function template specialization.
16378     // This is obligatory.
16379     ExprResult Result = E;
16380     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16381       return Result;
16382 
16383     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16384     // leaves Result unchanged on failure.
16385     Result = E;
16386     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16387       return Result;
16388 
16389     // If that failed, try to recover with a call.
16390     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16391                          /*complain*/ true);
16392     return Result;
16393   }
16394 
16395   // Bound member functions.
16396   case BuiltinType::BoundMember: {
16397     ExprResult result = E;
16398     const Expr *BME = E->IgnoreParens();
16399     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16400     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16401     if (isa<CXXPseudoDestructorExpr>(BME)) {
16402       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16403     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16404       if (ME->getMemberNameInfo().getName().getNameKind() ==
16405           DeclarationName::CXXDestructorName)
16406         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16407     }
16408     tryToRecoverWithCall(result, PD,
16409                          /*complain*/ true);
16410     return result;
16411   }
16412 
16413   // ARC unbridged casts.
16414   case BuiltinType::ARCUnbridgedCast: {
16415     Expr *realCast = stripARCUnbridgedCast(E);
16416     diagnoseARCUnbridgedCast(realCast);
16417     return realCast;
16418   }
16419 
16420   // Expressions of unknown type.
16421   case BuiltinType::UnknownAny:
16422     return diagnoseUnknownAnyExpr(*this, E);
16423 
16424   // Pseudo-objects.
16425   case BuiltinType::PseudoObject:
16426     return checkPseudoObjectRValue(E);
16427 
16428   case BuiltinType::BuiltinFn: {
16429     // Accept __noop without parens by implicitly converting it to a call expr.
16430     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16431     if (DRE) {
16432       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16433       if (FD->getBuiltinID() == Builtin::BI__noop) {
16434         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16435                               CK_BuiltinFnToFnPtr).get();
16436         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16437                                       VK_RValue, SourceLocation());
16438       }
16439     }
16440 
16441     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16442     return ExprError();
16443   }
16444 
16445   // Expressions of unknown type.
16446   case BuiltinType::OMPArraySection:
16447     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16448     return ExprError();
16449 
16450   // Everything else should be impossible.
16451 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16452   case BuiltinType::Id:
16453 #include "clang/Basic/OpenCLImageTypes.def"
16454 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16455 #define PLACEHOLDER_TYPE(Id, SingletonId)
16456 #include "clang/AST/BuiltinTypes.def"
16457     break;
16458   }
16459 
16460   llvm_unreachable("invalid placeholder type!");
16461 }
16462 
16463 bool Sema::CheckCaseExpression(Expr *E) {
16464   if (E->isTypeDependent())
16465     return true;
16466   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16467     return E->getType()->isIntegralOrEnumerationType();
16468   return false;
16469 }
16470 
16471 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16472 ExprResult
16473 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16474   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16475          "Unknown Objective-C Boolean value!");
16476   QualType BoolT = Context.ObjCBuiltinBoolTy;
16477   if (!Context.getBOOLDecl()) {
16478     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16479                         Sema::LookupOrdinaryName);
16480     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16481       NamedDecl *ND = Result.getFoundDecl();
16482       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16483         Context.setBOOLDecl(TD);
16484     }
16485   }
16486   if (Context.getBOOLDecl())
16487     BoolT = Context.getBOOLType();
16488   return new (Context)
16489       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16490 }
16491 
16492 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16493     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16494     SourceLocation RParen) {
16495 
16496   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16497 
16498   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16499                            [&](const AvailabilitySpec &Spec) {
16500                              return Spec.getPlatform() == Platform;
16501                            });
16502 
16503   VersionTuple Version;
16504   if (Spec != AvailSpecs.end())
16505     Version = Spec->getVersion();
16506 
16507   // The use of `@available` in the enclosing function should be analyzed to
16508   // warn when it's used inappropriately (i.e. not if(@available)).
16509   if (getCurFunctionOrMethodDecl())
16510     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16511   else if (getCurBlock() || getCurLambda())
16512     getCurFunction()->HasPotentialAvailabilityViolations = true;
16513 
16514   return new (Context)
16515       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16516 }
16517