1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
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 extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
43 
44 using namespace clang;
45 using namespace sema;
46 
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48                                                     unsigned ByteNo) const {
49   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50                                Context.getTargetInfo());
51 }
52 
53 /// Checks that a call expression's argument count is the desired number.
54 /// This is useful when doing custom type-checking.  Returns true on error.
55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56   unsigned argCount = call->getNumArgs();
57   if (argCount == desiredArgCount) return false;
58 
59   if (argCount < desiredArgCount)
60     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61         << 0 /*function call*/ << desiredArgCount << argCount
62         << call->getSourceRange();
63 
64   // Highlight all the excess arguments.
65   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66                     call->getArg(argCount - 1)->getLocEnd());
67 
68   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69     << 0 /*function call*/ << desiredArgCount << argCount
70     << call->getArg(1)->getSourceRange();
71 }
72 
73 /// Check that the first argument to __builtin_annotation is an integer
74 /// and the second argument is a non-wide string literal.
75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76   if (checkArgCount(S, TheCall, 2))
77     return true;
78 
79   // First argument should be an integer.
80   Expr *ValArg = TheCall->getArg(0);
81   QualType Ty = ValArg->getType();
82   if (!Ty->isIntegerType()) {
83     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84       << ValArg->getSourceRange();
85     return true;
86   }
87 
88   // Second argument should be a constant string.
89   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91   if (!Literal || !Literal->isAscii()) {
92     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93       << StrArg->getSourceRange();
94     return true;
95   }
96 
97   TheCall->setType(Ty);
98   return false;
99 }
100 
101 /// Check that the argument to __builtin_addressof is a glvalue, and set the
102 /// result type to the corresponding pointer type.
103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104   if (checkArgCount(S, TheCall, 1))
105     return true;
106 
107   ExprResult Arg(TheCall->getArg(0));
108   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109   if (ResultType.isNull())
110     return true;
111 
112   TheCall->setArg(0, Arg.get());
113   TheCall->setType(ResultType);
114   return false;
115 }
116 
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118   if (checkArgCount(S, TheCall, 3))
119     return true;
120 
121   // First two arguments should be integers.
122   for (unsigned I = 0; I < 2; ++I) {
123     Expr *Arg = TheCall->getArg(I);
124     QualType Ty = Arg->getType();
125     if (!Ty->isIntegerType()) {
126       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127           << Ty << Arg->getSourceRange();
128       return true;
129     }
130   }
131 
132   // Third argument should be a pointer to a non-const integer.
133   // IRGen correctly handles volatile, restrict, and address spaces, and
134   // the other qualifiers aren't possible.
135   {
136     Expr *Arg = TheCall->getArg(2);
137     QualType Ty = Arg->getType();
138     const auto *PtrTy = Ty->getAs<PointerType>();
139     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140           !PtrTy->getPointeeType().isConstQualified())) {
141       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142           << Ty << Arg->getSourceRange();
143       return true;
144     }
145   }
146 
147   return false;
148 }
149 
150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 		                  CallExpr *TheCall, unsigned SizeIdx,
152                                   unsigned DstSizeIdx) {
153   if (TheCall->getNumArgs() <= SizeIdx ||
154       TheCall->getNumArgs() <= DstSizeIdx)
155     return;
156 
157   const Expr *SizeArg = TheCall->getArg(SizeIdx);
158   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159 
160   llvm::APSInt Size, DstSize;
161 
162   // find out if both sizes are known at compile time
163   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165     return;
166 
167   if (Size.ule(DstSize))
168     return;
169 
170   // confirmed overflow so generate the diagnostic.
171   IdentifierInfo *FnName = FDecl->getIdentifier();
172   SourceLocation SL = TheCall->getLocStart();
173   SourceRange SR = TheCall->getSourceRange();
174 
175   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176 }
177 
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179   if (checkArgCount(S, BuiltinCall, 2))
180     return true;
181 
182   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184   Expr *Call = BuiltinCall->getArg(0);
185   Expr *Chain = BuiltinCall->getArg(1);
186 
187   if (Call->getStmtClass() != Stmt::CallExprClass) {
188     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189         << Call->getSourceRange();
190     return true;
191   }
192 
193   auto CE = cast<CallExpr>(Call);
194   if (CE->getCallee()->getType()->isBlockPointerType()) {
195     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196         << Call->getSourceRange();
197     return true;
198   }
199 
200   const Decl *TargetDecl = CE->getCalleeDecl();
201   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202     if (FD->getBuiltinID()) {
203       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204           << Call->getSourceRange();
205       return true;
206     }
207 
208   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210         << Call->getSourceRange();
211     return true;
212   }
213 
214   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215   if (ChainResult.isInvalid())
216     return true;
217   if (!ChainResult.get()->getType()->isPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219         << Chain->getSourceRange();
220     return true;
221   }
222 
223   QualType ReturnTy = CE->getCallReturnType(S.Context);
224   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225   QualType BuiltinTy = S.Context.getFunctionType(
226       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228 
229   Builtin =
230       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231 
232   BuiltinCall->setType(CE->getType());
233   BuiltinCall->setValueKind(CE->getValueKind());
234   BuiltinCall->setObjectKind(CE->getObjectKind());
235   BuiltinCall->setCallee(Builtin);
236   BuiltinCall->setArg(1, ChainResult.get());
237 
238   return false;
239 }
240 
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242                                      Scope::ScopeFlags NeededScopeFlags,
243                                      unsigned DiagID) {
244   // Scopes aren't available during instantiation. Fortunately, builtin
245   // functions cannot be template args so they cannot be formed through template
246   // instantiation. Therefore checking once during the parse is sufficient.
247   if (SemaRef.inTemplateInstantiation())
248     return false;
249 
250   Scope *S = SemaRef.getCurScope();
251   while (S && !S->isSEHExceptScope())
252     S = S->getParent();
253   if (!S || !(S->getFlags() & NeededScopeFlags)) {
254     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256         << DRE->getDecl()->getIdentifier();
257     return true;
258   }
259 
260   return false;
261 }
262 
263 static inline bool isBlockPointer(Expr *Arg) {
264   return Arg->getType()->isBlockPointerType();
265 }
266 
267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268 /// void*, which is a requirement of device side enqueue.
269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270   const BlockPointerType *BPT =
271       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272   ArrayRef<QualType> Params =
273       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274   unsigned ArgCounter = 0;
275   bool IllegalParams = false;
276   // Iterate through the block parameters until either one is found that is not
277   // a local void*, or the block is valid.
278   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279        I != E; ++I, ++ArgCounter) {
280     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282             LangAS::opencl_local) {
283       // Get the location of the error. If a block literal has been passed
284       // (BlockExpr) then we can point straight to the offending argument,
285       // else we just point to the variable reference.
286       SourceLocation ErrorLoc;
287       if (isa<BlockExpr>(BlockArg)) {
288         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290       } else if (isa<DeclRefExpr>(BlockArg)) {
291         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292       }
293       S.Diag(ErrorLoc,
294              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295       IllegalParams = true;
296     }
297   }
298 
299   return IllegalParams;
300 }
301 
302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303 /// get_kernel_work_group_size
304 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306   if (checkArgCount(S, TheCall, 1))
307     return true;
308 
309   Expr *BlockArg = TheCall->getArg(0);
310   if (!isBlockPointer(BlockArg)) {
311     S.Diag(BlockArg->getLocStart(),
312            diag::err_opencl_builtin_expected_type)
313         << TheCall->getDirectCallee() << "block";
314     return true;
315   }
316   return checkOpenCLBlockArgs(S, BlockArg);
317 }
318 
319 /// Diagnose integer type and any valid implicit conversion to it.
320 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
321                                       const QualType &IntType);
322 
323 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
324                                             unsigned Start, unsigned End) {
325   bool IllegalParams = false;
326   for (unsigned I = Start; I <= End; ++I)
327     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
328                                               S.Context.getSizeType());
329   return IllegalParams;
330 }
331 
332 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
333 /// 'local void*' parameter of passed block.
334 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
335                                            Expr *BlockArg,
336                                            unsigned NumNonVarArgs) {
337   const BlockPointerType *BPT =
338       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
339   unsigned NumBlockParams =
340       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
341   unsigned TotalNumArgs = TheCall->getNumArgs();
342 
343   // For each argument passed to the block, a corresponding uint needs to
344   // be passed to describe the size of the local memory.
345   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
346     S.Diag(TheCall->getLocStart(),
347            diag::err_opencl_enqueue_kernel_local_size_args);
348     return true;
349   }
350 
351   // Check that the sizes of the local memory are specified by integers.
352   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
353                                          TotalNumArgs - 1);
354 }
355 
356 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
357 /// overload formats specified in Table 6.13.17.1.
358 /// int enqueue_kernel(queue_t queue,
359 ///                    kernel_enqueue_flags_t flags,
360 ///                    const ndrange_t ndrange,
361 ///                    void (^block)(void))
362 /// int enqueue_kernel(queue_t queue,
363 ///                    kernel_enqueue_flags_t flags,
364 ///                    const ndrange_t ndrange,
365 ///                    uint num_events_in_wait_list,
366 ///                    clk_event_t *event_wait_list,
367 ///                    clk_event_t *event_ret,
368 ///                    void (^block)(void))
369 /// int enqueue_kernel(queue_t queue,
370 ///                    kernel_enqueue_flags_t flags,
371 ///                    const ndrange_t ndrange,
372 ///                    void (^block)(local void*, ...),
373 ///                    uint size0, ...)
374 /// int enqueue_kernel(queue_t queue,
375 ///                    kernel_enqueue_flags_t flags,
376 ///                    const ndrange_t ndrange,
377 ///                    uint num_events_in_wait_list,
378 ///                    clk_event_t *event_wait_list,
379 ///                    clk_event_t *event_ret,
380 ///                    void (^block)(local void*, ...),
381 ///                    uint size0, ...)
382 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
383   unsigned NumArgs = TheCall->getNumArgs();
384 
385   if (NumArgs < 4) {
386     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
387     return true;
388   }
389 
390   Expr *Arg0 = TheCall->getArg(0);
391   Expr *Arg1 = TheCall->getArg(1);
392   Expr *Arg2 = TheCall->getArg(2);
393   Expr *Arg3 = TheCall->getArg(3);
394 
395   // First argument always needs to be a queue_t type.
396   if (!Arg0->getType()->isQueueT()) {
397     S.Diag(TheCall->getArg(0)->getLocStart(),
398            diag::err_opencl_builtin_expected_type)
399         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
400     return true;
401   }
402 
403   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
404   if (!Arg1->getType()->isIntegerType()) {
405     S.Diag(TheCall->getArg(1)->getLocStart(),
406            diag::err_opencl_builtin_expected_type)
407         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
408     return true;
409   }
410 
411   // Third argument is always an ndrange_t type.
412   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
413     S.Diag(TheCall->getArg(2)->getLocStart(),
414            diag::err_opencl_builtin_expected_type)
415         << TheCall->getDirectCallee() << "'ndrange_t'";
416     return true;
417   }
418 
419   // With four arguments, there is only one form that the function could be
420   // called in: no events and no variable arguments.
421   if (NumArgs == 4) {
422     // check that the last argument is the right block type.
423     if (!isBlockPointer(Arg3)) {
424       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
425           << TheCall->getDirectCallee() << "block";
426       return true;
427     }
428     // we have a block type, check the prototype
429     const BlockPointerType *BPT =
430         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
431     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
432       S.Diag(Arg3->getLocStart(),
433              diag::err_opencl_enqueue_kernel_blocks_no_args);
434       return true;
435     }
436     return false;
437   }
438   // we can have block + varargs.
439   if (isBlockPointer(Arg3))
440     return (checkOpenCLBlockArgs(S, Arg3) ||
441             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
442   // last two cases with either exactly 7 args or 7 args and varargs.
443   if (NumArgs >= 7) {
444     // check common block argument.
445     Expr *Arg6 = TheCall->getArg(6);
446     if (!isBlockPointer(Arg6)) {
447       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
448           << TheCall->getDirectCallee() << "block";
449       return true;
450     }
451     if (checkOpenCLBlockArgs(S, Arg6))
452       return true;
453 
454     // Forth argument has to be any integer type.
455     if (!Arg3->getType()->isIntegerType()) {
456       S.Diag(TheCall->getArg(3)->getLocStart(),
457              diag::err_opencl_builtin_expected_type)
458           << TheCall->getDirectCallee() << "integer";
459       return true;
460     }
461     // check remaining common arguments.
462     Expr *Arg4 = TheCall->getArg(4);
463     Expr *Arg5 = TheCall->getArg(5);
464 
465     // Fifth argument is always passed as a pointer to clk_event_t.
466     if (!Arg4->isNullPointerConstant(S.Context,
467                                      Expr::NPC_ValueDependentIsNotNull) &&
468         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
469       S.Diag(TheCall->getArg(4)->getLocStart(),
470              diag::err_opencl_builtin_expected_type)
471           << TheCall->getDirectCallee()
472           << S.Context.getPointerType(S.Context.OCLClkEventTy);
473       return true;
474     }
475 
476     // Sixth argument is always passed as a pointer to clk_event_t.
477     if (!Arg5->isNullPointerConstant(S.Context,
478                                      Expr::NPC_ValueDependentIsNotNull) &&
479         !(Arg5->getType()->isPointerType() &&
480           Arg5->getType()->getPointeeType()->isClkEventT())) {
481       S.Diag(TheCall->getArg(5)->getLocStart(),
482              diag::err_opencl_builtin_expected_type)
483           << TheCall->getDirectCallee()
484           << S.Context.getPointerType(S.Context.OCLClkEventTy);
485       return true;
486     }
487 
488     if (NumArgs == 7)
489       return false;
490 
491     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
492   }
493 
494   // None of the specific case has been detected, give generic error
495   S.Diag(TheCall->getLocStart(),
496          diag::err_opencl_enqueue_kernel_incorrect_args);
497   return true;
498 }
499 
500 /// Returns OpenCL access qual.
501 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
502     return D->getAttr<OpenCLAccessAttr>();
503 }
504 
505 /// Returns true if pipe element type is different from the pointer.
506 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
507   const Expr *Arg0 = Call->getArg(0);
508   // First argument type should always be pipe.
509   if (!Arg0->getType()->isPipeType()) {
510     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
511         << Call->getDirectCallee() << Arg0->getSourceRange();
512     return true;
513   }
514   OpenCLAccessAttr *AccessQual =
515       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
516   // Validates the access qualifier is compatible with the call.
517   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
518   // read_only and write_only, and assumed to be read_only if no qualifier is
519   // specified.
520   switch (Call->getDirectCallee()->getBuiltinID()) {
521   case Builtin::BIread_pipe:
522   case Builtin::BIreserve_read_pipe:
523   case Builtin::BIcommit_read_pipe:
524   case Builtin::BIwork_group_reserve_read_pipe:
525   case Builtin::BIsub_group_reserve_read_pipe:
526   case Builtin::BIwork_group_commit_read_pipe:
527   case Builtin::BIsub_group_commit_read_pipe:
528     if (!(!AccessQual || AccessQual->isReadOnly())) {
529       S.Diag(Arg0->getLocStart(),
530              diag::err_opencl_builtin_pipe_invalid_access_modifier)
531           << "read_only" << Arg0->getSourceRange();
532       return true;
533     }
534     break;
535   case Builtin::BIwrite_pipe:
536   case Builtin::BIreserve_write_pipe:
537   case Builtin::BIcommit_write_pipe:
538   case Builtin::BIwork_group_reserve_write_pipe:
539   case Builtin::BIsub_group_reserve_write_pipe:
540   case Builtin::BIwork_group_commit_write_pipe:
541   case Builtin::BIsub_group_commit_write_pipe:
542     if (!(AccessQual && AccessQual->isWriteOnly())) {
543       S.Diag(Arg0->getLocStart(),
544              diag::err_opencl_builtin_pipe_invalid_access_modifier)
545           << "write_only" << Arg0->getSourceRange();
546       return true;
547     }
548     break;
549   default:
550     break;
551   }
552   return false;
553 }
554 
555 /// Returns true if pipe element type is different from the pointer.
556 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
557   const Expr *Arg0 = Call->getArg(0);
558   const Expr *ArgIdx = Call->getArg(Idx);
559   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
560   const QualType EltTy = PipeTy->getElementType();
561   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
562   // The Idx argument should be a pointer and the type of the pointer and
563   // the type of pipe element should also be the same.
564   if (!ArgTy ||
565       !S.Context.hasSameType(
566           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
567     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
568         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
569         << ArgIdx->getType() << ArgIdx->getSourceRange();
570     return true;
571   }
572   return false;
573 }
574 
575 // \brief Performs semantic analysis for the read/write_pipe call.
576 // \param S Reference to the semantic analyzer.
577 // \param Call A pointer to the builtin call.
578 // \return True if a semantic error has been found, false otherwise.
579 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
580   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
581   // functions have two forms.
582   switch (Call->getNumArgs()) {
583   case 2: {
584     if (checkOpenCLPipeArg(S, Call))
585       return true;
586     // The call with 2 arguments should be
587     // read/write_pipe(pipe T, T*).
588     // Check packet type T.
589     if (checkOpenCLPipePacketType(S, Call, 1))
590       return true;
591   } break;
592 
593   case 4: {
594     if (checkOpenCLPipeArg(S, Call))
595       return true;
596     // The call with 4 arguments should be
597     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
598     // Check reserve_id_t.
599     if (!Call->getArg(1)->getType()->isReserveIDT()) {
600       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
601           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
602           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
603       return true;
604     }
605 
606     // Check the index.
607     const Expr *Arg2 = Call->getArg(2);
608     if (!Arg2->getType()->isIntegerType() &&
609         !Arg2->getType()->isUnsignedIntegerType()) {
610       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
611           << Call->getDirectCallee() << S.Context.UnsignedIntTy
612           << Arg2->getType() << Arg2->getSourceRange();
613       return true;
614     }
615 
616     // Check packet type T.
617     if (checkOpenCLPipePacketType(S, Call, 3))
618       return true;
619   } break;
620   default:
621     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
622         << Call->getDirectCallee() << Call->getSourceRange();
623     return true;
624   }
625 
626   return false;
627 }
628 
629 // \brief Performs a semantic analysis on the {work_group_/sub_group_
630 //        /_}reserve_{read/write}_pipe
631 // \param S Reference to the semantic analyzer.
632 // \param Call The call to the builtin function to be analyzed.
633 // \return True if a semantic error was found, false otherwise.
634 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
635   if (checkArgCount(S, Call, 2))
636     return true;
637 
638   if (checkOpenCLPipeArg(S, Call))
639     return true;
640 
641   // Check the reserve size.
642   if (!Call->getArg(1)->getType()->isIntegerType() &&
643       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
644     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
645         << Call->getDirectCallee() << S.Context.UnsignedIntTy
646         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
647     return true;
648   }
649 
650   return false;
651 }
652 
653 // \brief Performs a semantic analysis on {work_group_/sub_group_
654 //        /_}commit_{read/write}_pipe
655 // \param S Reference to the semantic analyzer.
656 // \param Call The call to the builtin function to be analyzed.
657 // \return True if a semantic error was found, false otherwise.
658 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
659   if (checkArgCount(S, Call, 2))
660     return true;
661 
662   if (checkOpenCLPipeArg(S, Call))
663     return true;
664 
665   // Check reserve_id_t.
666   if (!Call->getArg(1)->getType()->isReserveIDT()) {
667     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
668         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
669         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
670     return true;
671   }
672 
673   return false;
674 }
675 
676 // \brief Performs a semantic analysis on the call to built-in Pipe
677 //        Query Functions.
678 // \param S Reference to the semantic analyzer.
679 // \param Call The call to the builtin function to be analyzed.
680 // \return True if a semantic error was found, false otherwise.
681 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
682   if (checkArgCount(S, Call, 1))
683     return true;
684 
685   if (!Call->getArg(0)->getType()->isPipeType()) {
686     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
687         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
688     return true;
689   }
690 
691   return false;
692 }
693 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
694 // \brief Performs semantic analysis for the to_global/local/private call.
695 // \param S Reference to the semantic analyzer.
696 // \param BuiltinID ID of the builtin function.
697 // \param Call A pointer to the builtin call.
698 // \return True if a semantic error has been found, false otherwise.
699 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
700                                     CallExpr *Call) {
701   if (Call->getNumArgs() != 1) {
702     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
703         << Call->getDirectCallee() << Call->getSourceRange();
704     return true;
705   }
706 
707   auto RT = Call->getArg(0)->getType();
708   if (!RT->isPointerType() || RT->getPointeeType()
709       .getAddressSpace() == LangAS::opencl_constant) {
710     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
711         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
712     return true;
713   }
714 
715   RT = RT->getPointeeType();
716   auto Qual = RT.getQualifiers();
717   switch (BuiltinID) {
718   case Builtin::BIto_global:
719     Qual.setAddressSpace(LangAS::opencl_global);
720     break;
721   case Builtin::BIto_local:
722     Qual.setAddressSpace(LangAS::opencl_local);
723     break;
724   default:
725     Qual.removeAddressSpace();
726   }
727   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
728       RT.getUnqualifiedType(), Qual)));
729 
730   return false;
731 }
732 
733 ExprResult
734 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
735                                CallExpr *TheCall) {
736   ExprResult TheCallResult(TheCall);
737 
738   // Find out if any arguments are required to be integer constant expressions.
739   unsigned ICEArguments = 0;
740   ASTContext::GetBuiltinTypeError Error;
741   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
742   if (Error != ASTContext::GE_None)
743     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
744 
745   // If any arguments are required to be ICE's, check and diagnose.
746   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
747     // Skip arguments not required to be ICE's.
748     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
749 
750     llvm::APSInt Result;
751     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
752       return true;
753     ICEArguments &= ~(1 << ArgNo);
754   }
755 
756   switch (BuiltinID) {
757   case Builtin::BI__builtin___CFStringMakeConstantString:
758     assert(TheCall->getNumArgs() == 1 &&
759            "Wrong # arguments to builtin CFStringMakeConstantString");
760     if (CheckObjCString(TheCall->getArg(0)))
761       return ExprError();
762     break;
763   case Builtin::BI__builtin_stdarg_start:
764   case Builtin::BI__builtin_va_start:
765     if (SemaBuiltinVAStart(BuiltinID, TheCall))
766       return ExprError();
767     break;
768   case Builtin::BI__va_start: {
769     switch (Context.getTargetInfo().getTriple().getArch()) {
770     case llvm::Triple::arm:
771     case llvm::Triple::thumb:
772       if (SemaBuiltinVAStartARM(TheCall))
773         return ExprError();
774       break;
775     default:
776       if (SemaBuiltinVAStart(BuiltinID, TheCall))
777         return ExprError();
778       break;
779     }
780     break;
781   }
782   case Builtin::BI__builtin_isgreater:
783   case Builtin::BI__builtin_isgreaterequal:
784   case Builtin::BI__builtin_isless:
785   case Builtin::BI__builtin_islessequal:
786   case Builtin::BI__builtin_islessgreater:
787   case Builtin::BI__builtin_isunordered:
788     if (SemaBuiltinUnorderedCompare(TheCall))
789       return ExprError();
790     break;
791   case Builtin::BI__builtin_fpclassify:
792     if (SemaBuiltinFPClassification(TheCall, 6))
793       return ExprError();
794     break;
795   case Builtin::BI__builtin_isfinite:
796   case Builtin::BI__builtin_isinf:
797   case Builtin::BI__builtin_isinf_sign:
798   case Builtin::BI__builtin_isnan:
799   case Builtin::BI__builtin_isnormal:
800     if (SemaBuiltinFPClassification(TheCall, 1))
801       return ExprError();
802     break;
803   case Builtin::BI__builtin_shufflevector:
804     return SemaBuiltinShuffleVector(TheCall);
805     // TheCall will be freed by the smart pointer here, but that's fine, since
806     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
807   case Builtin::BI__builtin_prefetch:
808     if (SemaBuiltinPrefetch(TheCall))
809       return ExprError();
810     break;
811   case Builtin::BI__builtin_alloca_with_align:
812     if (SemaBuiltinAllocaWithAlign(TheCall))
813       return ExprError();
814     break;
815   case Builtin::BI__assume:
816   case Builtin::BI__builtin_assume:
817     if (SemaBuiltinAssume(TheCall))
818       return ExprError();
819     break;
820   case Builtin::BI__builtin_assume_aligned:
821     if (SemaBuiltinAssumeAligned(TheCall))
822       return ExprError();
823     break;
824   case Builtin::BI__builtin_object_size:
825     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
826       return ExprError();
827     break;
828   case Builtin::BI__builtin_longjmp:
829     if (SemaBuiltinLongjmp(TheCall))
830       return ExprError();
831     break;
832   case Builtin::BI__builtin_setjmp:
833     if (SemaBuiltinSetjmp(TheCall))
834       return ExprError();
835     break;
836   case Builtin::BI_setjmp:
837   case Builtin::BI_setjmpex:
838     if (checkArgCount(*this, TheCall, 1))
839       return true;
840     break;
841 
842   case Builtin::BI__builtin_classify_type:
843     if (checkArgCount(*this, TheCall, 1)) return true;
844     TheCall->setType(Context.IntTy);
845     break;
846   case Builtin::BI__builtin_constant_p:
847     if (checkArgCount(*this, TheCall, 1)) return true;
848     TheCall->setType(Context.IntTy);
849     break;
850   case Builtin::BI__sync_fetch_and_add:
851   case Builtin::BI__sync_fetch_and_add_1:
852   case Builtin::BI__sync_fetch_and_add_2:
853   case Builtin::BI__sync_fetch_and_add_4:
854   case Builtin::BI__sync_fetch_and_add_8:
855   case Builtin::BI__sync_fetch_and_add_16:
856   case Builtin::BI__sync_fetch_and_sub:
857   case Builtin::BI__sync_fetch_and_sub_1:
858   case Builtin::BI__sync_fetch_and_sub_2:
859   case Builtin::BI__sync_fetch_and_sub_4:
860   case Builtin::BI__sync_fetch_and_sub_8:
861   case Builtin::BI__sync_fetch_and_sub_16:
862   case Builtin::BI__sync_fetch_and_or:
863   case Builtin::BI__sync_fetch_and_or_1:
864   case Builtin::BI__sync_fetch_and_or_2:
865   case Builtin::BI__sync_fetch_and_or_4:
866   case Builtin::BI__sync_fetch_and_or_8:
867   case Builtin::BI__sync_fetch_and_or_16:
868   case Builtin::BI__sync_fetch_and_and:
869   case Builtin::BI__sync_fetch_and_and_1:
870   case Builtin::BI__sync_fetch_and_and_2:
871   case Builtin::BI__sync_fetch_and_and_4:
872   case Builtin::BI__sync_fetch_and_and_8:
873   case Builtin::BI__sync_fetch_and_and_16:
874   case Builtin::BI__sync_fetch_and_xor:
875   case Builtin::BI__sync_fetch_and_xor_1:
876   case Builtin::BI__sync_fetch_and_xor_2:
877   case Builtin::BI__sync_fetch_and_xor_4:
878   case Builtin::BI__sync_fetch_and_xor_8:
879   case Builtin::BI__sync_fetch_and_xor_16:
880   case Builtin::BI__sync_fetch_and_nand:
881   case Builtin::BI__sync_fetch_and_nand_1:
882   case Builtin::BI__sync_fetch_and_nand_2:
883   case Builtin::BI__sync_fetch_and_nand_4:
884   case Builtin::BI__sync_fetch_and_nand_8:
885   case Builtin::BI__sync_fetch_and_nand_16:
886   case Builtin::BI__sync_add_and_fetch:
887   case Builtin::BI__sync_add_and_fetch_1:
888   case Builtin::BI__sync_add_and_fetch_2:
889   case Builtin::BI__sync_add_and_fetch_4:
890   case Builtin::BI__sync_add_and_fetch_8:
891   case Builtin::BI__sync_add_and_fetch_16:
892   case Builtin::BI__sync_sub_and_fetch:
893   case Builtin::BI__sync_sub_and_fetch_1:
894   case Builtin::BI__sync_sub_and_fetch_2:
895   case Builtin::BI__sync_sub_and_fetch_4:
896   case Builtin::BI__sync_sub_and_fetch_8:
897   case Builtin::BI__sync_sub_and_fetch_16:
898   case Builtin::BI__sync_and_and_fetch:
899   case Builtin::BI__sync_and_and_fetch_1:
900   case Builtin::BI__sync_and_and_fetch_2:
901   case Builtin::BI__sync_and_and_fetch_4:
902   case Builtin::BI__sync_and_and_fetch_8:
903   case Builtin::BI__sync_and_and_fetch_16:
904   case Builtin::BI__sync_or_and_fetch:
905   case Builtin::BI__sync_or_and_fetch_1:
906   case Builtin::BI__sync_or_and_fetch_2:
907   case Builtin::BI__sync_or_and_fetch_4:
908   case Builtin::BI__sync_or_and_fetch_8:
909   case Builtin::BI__sync_or_and_fetch_16:
910   case Builtin::BI__sync_xor_and_fetch:
911   case Builtin::BI__sync_xor_and_fetch_1:
912   case Builtin::BI__sync_xor_and_fetch_2:
913   case Builtin::BI__sync_xor_and_fetch_4:
914   case Builtin::BI__sync_xor_and_fetch_8:
915   case Builtin::BI__sync_xor_and_fetch_16:
916   case Builtin::BI__sync_nand_and_fetch:
917   case Builtin::BI__sync_nand_and_fetch_1:
918   case Builtin::BI__sync_nand_and_fetch_2:
919   case Builtin::BI__sync_nand_and_fetch_4:
920   case Builtin::BI__sync_nand_and_fetch_8:
921   case Builtin::BI__sync_nand_and_fetch_16:
922   case Builtin::BI__sync_val_compare_and_swap:
923   case Builtin::BI__sync_val_compare_and_swap_1:
924   case Builtin::BI__sync_val_compare_and_swap_2:
925   case Builtin::BI__sync_val_compare_and_swap_4:
926   case Builtin::BI__sync_val_compare_and_swap_8:
927   case Builtin::BI__sync_val_compare_and_swap_16:
928   case Builtin::BI__sync_bool_compare_and_swap:
929   case Builtin::BI__sync_bool_compare_and_swap_1:
930   case Builtin::BI__sync_bool_compare_and_swap_2:
931   case Builtin::BI__sync_bool_compare_and_swap_4:
932   case Builtin::BI__sync_bool_compare_and_swap_8:
933   case Builtin::BI__sync_bool_compare_and_swap_16:
934   case Builtin::BI__sync_lock_test_and_set:
935   case Builtin::BI__sync_lock_test_and_set_1:
936   case Builtin::BI__sync_lock_test_and_set_2:
937   case Builtin::BI__sync_lock_test_and_set_4:
938   case Builtin::BI__sync_lock_test_and_set_8:
939   case Builtin::BI__sync_lock_test_and_set_16:
940   case Builtin::BI__sync_lock_release:
941   case Builtin::BI__sync_lock_release_1:
942   case Builtin::BI__sync_lock_release_2:
943   case Builtin::BI__sync_lock_release_4:
944   case Builtin::BI__sync_lock_release_8:
945   case Builtin::BI__sync_lock_release_16:
946   case Builtin::BI__sync_swap:
947   case Builtin::BI__sync_swap_1:
948   case Builtin::BI__sync_swap_2:
949   case Builtin::BI__sync_swap_4:
950   case Builtin::BI__sync_swap_8:
951   case Builtin::BI__sync_swap_16:
952     return SemaBuiltinAtomicOverloaded(TheCallResult);
953   case Builtin::BI__builtin_nontemporal_load:
954   case Builtin::BI__builtin_nontemporal_store:
955     return SemaBuiltinNontemporalOverloaded(TheCallResult);
956 #define BUILTIN(ID, TYPE, ATTRS)
957 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
958   case Builtin::BI##ID: \
959     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
960 #include "clang/Basic/Builtins.def"
961   case Builtin::BI__builtin_annotation:
962     if (SemaBuiltinAnnotation(*this, TheCall))
963       return ExprError();
964     break;
965   case Builtin::BI__builtin_addressof:
966     if (SemaBuiltinAddressof(*this, TheCall))
967       return ExprError();
968     break;
969   case Builtin::BI__builtin_add_overflow:
970   case Builtin::BI__builtin_sub_overflow:
971   case Builtin::BI__builtin_mul_overflow:
972     if (SemaBuiltinOverflow(*this, TheCall))
973       return ExprError();
974     break;
975   case Builtin::BI__builtin_operator_new:
976   case Builtin::BI__builtin_operator_delete:
977     if (!getLangOpts().CPlusPlus) {
978       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
979         << (BuiltinID == Builtin::BI__builtin_operator_new
980                 ? "__builtin_operator_new"
981                 : "__builtin_operator_delete")
982         << "C++";
983       return ExprError();
984     }
985     // CodeGen assumes it can find the global new and delete to call,
986     // so ensure that they are declared.
987     DeclareGlobalNewDelete();
988     break;
989 
990   // check secure string manipulation functions where overflows
991   // are detectable at compile time
992   case Builtin::BI__builtin___memcpy_chk:
993   case Builtin::BI__builtin___memmove_chk:
994   case Builtin::BI__builtin___memset_chk:
995   case Builtin::BI__builtin___strlcat_chk:
996   case Builtin::BI__builtin___strlcpy_chk:
997   case Builtin::BI__builtin___strncat_chk:
998   case Builtin::BI__builtin___strncpy_chk:
999   case Builtin::BI__builtin___stpncpy_chk:
1000     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1001     break;
1002   case Builtin::BI__builtin___memccpy_chk:
1003     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1004     break;
1005   case Builtin::BI__builtin___snprintf_chk:
1006   case Builtin::BI__builtin___vsnprintf_chk:
1007     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1008     break;
1009   case Builtin::BI__builtin_call_with_static_chain:
1010     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1011       return ExprError();
1012     break;
1013   case Builtin::BI__exception_code:
1014   case Builtin::BI_exception_code:
1015     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1016                                  diag::err_seh___except_block))
1017       return ExprError();
1018     break;
1019   case Builtin::BI__exception_info:
1020   case Builtin::BI_exception_info:
1021     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1022                                  diag::err_seh___except_filter))
1023       return ExprError();
1024     break;
1025   case Builtin::BI__GetExceptionInfo:
1026     if (checkArgCount(*this, TheCall, 1))
1027       return ExprError();
1028 
1029     if (CheckCXXThrowOperand(
1030             TheCall->getLocStart(),
1031             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1032             TheCall))
1033       return ExprError();
1034 
1035     TheCall->setType(Context.VoidPtrTy);
1036     break;
1037   // OpenCL v2.0, s6.13.16 - Pipe functions
1038   case Builtin::BIread_pipe:
1039   case Builtin::BIwrite_pipe:
1040     // Since those two functions are declared with var args, we need a semantic
1041     // check for the argument.
1042     if (SemaBuiltinRWPipe(*this, TheCall))
1043       return ExprError();
1044     TheCall->setType(Context.IntTy);
1045     break;
1046   case Builtin::BIreserve_read_pipe:
1047   case Builtin::BIreserve_write_pipe:
1048   case Builtin::BIwork_group_reserve_read_pipe:
1049   case Builtin::BIwork_group_reserve_write_pipe:
1050   case Builtin::BIsub_group_reserve_read_pipe:
1051   case Builtin::BIsub_group_reserve_write_pipe:
1052     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1053       return ExprError();
1054     // Since return type of reserve_read/write_pipe built-in function is
1055     // reserve_id_t, which is not defined in the builtin def file , we used int
1056     // as return type and need to override the return type of these functions.
1057     TheCall->setType(Context.OCLReserveIDTy);
1058     break;
1059   case Builtin::BIcommit_read_pipe:
1060   case Builtin::BIcommit_write_pipe:
1061   case Builtin::BIwork_group_commit_read_pipe:
1062   case Builtin::BIwork_group_commit_write_pipe:
1063   case Builtin::BIsub_group_commit_read_pipe:
1064   case Builtin::BIsub_group_commit_write_pipe:
1065     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1066       return ExprError();
1067     break;
1068   case Builtin::BIget_pipe_num_packets:
1069   case Builtin::BIget_pipe_max_packets:
1070     if (SemaBuiltinPipePackets(*this, TheCall))
1071       return ExprError();
1072     TheCall->setType(Context.UnsignedIntTy);
1073     break;
1074   case Builtin::BIto_global:
1075   case Builtin::BIto_local:
1076   case Builtin::BIto_private:
1077     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1078       return ExprError();
1079     break;
1080   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1081   case Builtin::BIenqueue_kernel:
1082     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1083       return ExprError();
1084     break;
1085   case Builtin::BIget_kernel_work_group_size:
1086   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1087     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1088       return ExprError();
1089     break;
1090   case Builtin::BI__builtin_os_log_format:
1091   case Builtin::BI__builtin_os_log_format_buffer_size:
1092     if (SemaBuiltinOSLogFormat(TheCall)) {
1093       return ExprError();
1094     }
1095     break;
1096   }
1097 
1098   // Since the target specific builtins for each arch overlap, only check those
1099   // of the arch we are compiling for.
1100   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1101     switch (Context.getTargetInfo().getTriple().getArch()) {
1102       case llvm::Triple::arm:
1103       case llvm::Triple::armeb:
1104       case llvm::Triple::thumb:
1105       case llvm::Triple::thumbeb:
1106         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1107           return ExprError();
1108         break;
1109       case llvm::Triple::aarch64:
1110       case llvm::Triple::aarch64_be:
1111         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1112           return ExprError();
1113         break;
1114       case llvm::Triple::mips:
1115       case llvm::Triple::mipsel:
1116       case llvm::Triple::mips64:
1117       case llvm::Triple::mips64el:
1118         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1119           return ExprError();
1120         break;
1121       case llvm::Triple::systemz:
1122         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1123           return ExprError();
1124         break;
1125       case llvm::Triple::x86:
1126       case llvm::Triple::x86_64:
1127         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1128           return ExprError();
1129         break;
1130       case llvm::Triple::ppc:
1131       case llvm::Triple::ppc64:
1132       case llvm::Triple::ppc64le:
1133         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1134           return ExprError();
1135         break;
1136       default:
1137         break;
1138     }
1139   }
1140 
1141   return TheCallResult;
1142 }
1143 
1144 // Get the valid immediate range for the specified NEON type code.
1145 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1146   NeonTypeFlags Type(t);
1147   int IsQuad = ForceQuad ? true : Type.isQuad();
1148   switch (Type.getEltType()) {
1149   case NeonTypeFlags::Int8:
1150   case NeonTypeFlags::Poly8:
1151     return shift ? 7 : (8 << IsQuad) - 1;
1152   case NeonTypeFlags::Int16:
1153   case NeonTypeFlags::Poly16:
1154     return shift ? 15 : (4 << IsQuad) - 1;
1155   case NeonTypeFlags::Int32:
1156     return shift ? 31 : (2 << IsQuad) - 1;
1157   case NeonTypeFlags::Int64:
1158   case NeonTypeFlags::Poly64:
1159     return shift ? 63 : (1 << IsQuad) - 1;
1160   case NeonTypeFlags::Poly128:
1161     return shift ? 127 : (1 << IsQuad) - 1;
1162   case NeonTypeFlags::Float16:
1163     assert(!shift && "cannot shift float types!");
1164     return (4 << IsQuad) - 1;
1165   case NeonTypeFlags::Float32:
1166     assert(!shift && "cannot shift float types!");
1167     return (2 << IsQuad) - 1;
1168   case NeonTypeFlags::Float64:
1169     assert(!shift && "cannot shift float types!");
1170     return (1 << IsQuad) - 1;
1171   }
1172   llvm_unreachable("Invalid NeonTypeFlag!");
1173 }
1174 
1175 /// getNeonEltType - Return the QualType corresponding to the elements of
1176 /// the vector type specified by the NeonTypeFlags.  This is used to check
1177 /// the pointer arguments for Neon load/store intrinsics.
1178 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1179                                bool IsPolyUnsigned, bool IsInt64Long) {
1180   switch (Flags.getEltType()) {
1181   case NeonTypeFlags::Int8:
1182     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1183   case NeonTypeFlags::Int16:
1184     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1185   case NeonTypeFlags::Int32:
1186     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1187   case NeonTypeFlags::Int64:
1188     if (IsInt64Long)
1189       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1190     else
1191       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1192                                 : Context.LongLongTy;
1193   case NeonTypeFlags::Poly8:
1194     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1195   case NeonTypeFlags::Poly16:
1196     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1197   case NeonTypeFlags::Poly64:
1198     if (IsInt64Long)
1199       return Context.UnsignedLongTy;
1200     else
1201       return Context.UnsignedLongLongTy;
1202   case NeonTypeFlags::Poly128:
1203     break;
1204   case NeonTypeFlags::Float16:
1205     return Context.HalfTy;
1206   case NeonTypeFlags::Float32:
1207     return Context.FloatTy;
1208   case NeonTypeFlags::Float64:
1209     return Context.DoubleTy;
1210   }
1211   llvm_unreachable("Invalid NeonTypeFlag!");
1212 }
1213 
1214 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1215   llvm::APSInt Result;
1216   uint64_t mask = 0;
1217   unsigned TV = 0;
1218   int PtrArgNum = -1;
1219   bool HasConstPtr = false;
1220   switch (BuiltinID) {
1221 #define GET_NEON_OVERLOAD_CHECK
1222 #include "clang/Basic/arm_neon.inc"
1223 #undef GET_NEON_OVERLOAD_CHECK
1224   }
1225 
1226   // For NEON intrinsics which are overloaded on vector element type, validate
1227   // the immediate which specifies which variant to emit.
1228   unsigned ImmArg = TheCall->getNumArgs()-1;
1229   if (mask) {
1230     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1231       return true;
1232 
1233     TV = Result.getLimitedValue(64);
1234     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1235       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1236         << TheCall->getArg(ImmArg)->getSourceRange();
1237   }
1238 
1239   if (PtrArgNum >= 0) {
1240     // Check that pointer arguments have the specified type.
1241     Expr *Arg = TheCall->getArg(PtrArgNum);
1242     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1243       Arg = ICE->getSubExpr();
1244     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1245     QualType RHSTy = RHS.get()->getType();
1246 
1247     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1248     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1249                           Arch == llvm::Triple::aarch64_be;
1250     bool IsInt64Long =
1251         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1252     QualType EltTy =
1253         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1254     if (HasConstPtr)
1255       EltTy = EltTy.withConst();
1256     QualType LHSTy = Context.getPointerType(EltTy);
1257     AssignConvertType ConvTy;
1258     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1259     if (RHS.isInvalid())
1260       return true;
1261     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1262                                  RHS.get(), AA_Assigning))
1263       return true;
1264   }
1265 
1266   // For NEON intrinsics which take an immediate value as part of the
1267   // instruction, range check them here.
1268   unsigned i = 0, l = 0, u = 0;
1269   switch (BuiltinID) {
1270   default:
1271     return false;
1272 #define GET_NEON_IMMEDIATE_CHECK
1273 #include "clang/Basic/arm_neon.inc"
1274 #undef GET_NEON_IMMEDIATE_CHECK
1275   }
1276 
1277   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1278 }
1279 
1280 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1281                                         unsigned MaxWidth) {
1282   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1283           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1284           BuiltinID == ARM::BI__builtin_arm_strex ||
1285           BuiltinID == ARM::BI__builtin_arm_stlex ||
1286           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1287           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1288           BuiltinID == AArch64::BI__builtin_arm_strex ||
1289           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1290          "unexpected ARM builtin");
1291   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1292                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1293                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1294                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1295 
1296   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1297 
1298   // Ensure that we have the proper number of arguments.
1299   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1300     return true;
1301 
1302   // Inspect the pointer argument of the atomic builtin.  This should always be
1303   // a pointer type, whose element is an integral scalar or pointer type.
1304   // Because it is a pointer type, we don't have to worry about any implicit
1305   // casts here.
1306   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1307   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1308   if (PointerArgRes.isInvalid())
1309     return true;
1310   PointerArg = PointerArgRes.get();
1311 
1312   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1313   if (!pointerType) {
1314     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1315       << PointerArg->getType() << PointerArg->getSourceRange();
1316     return true;
1317   }
1318 
1319   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1320   // task is to insert the appropriate casts into the AST. First work out just
1321   // what the appropriate type is.
1322   QualType ValType = pointerType->getPointeeType();
1323   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1324   if (IsLdrex)
1325     AddrType.addConst();
1326 
1327   // Issue a warning if the cast is dodgy.
1328   CastKind CastNeeded = CK_NoOp;
1329   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1330     CastNeeded = CK_BitCast;
1331     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1332       << PointerArg->getType()
1333       << Context.getPointerType(AddrType)
1334       << AA_Passing << PointerArg->getSourceRange();
1335   }
1336 
1337   // Finally, do the cast and replace the argument with the corrected version.
1338   AddrType = Context.getPointerType(AddrType);
1339   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1340   if (PointerArgRes.isInvalid())
1341     return true;
1342   PointerArg = PointerArgRes.get();
1343 
1344   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1345 
1346   // In general, we allow ints, floats and pointers to be loaded and stored.
1347   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1348       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1349     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1350       << PointerArg->getType() << PointerArg->getSourceRange();
1351     return true;
1352   }
1353 
1354   // But ARM doesn't have instructions to deal with 128-bit versions.
1355   if (Context.getTypeSize(ValType) > MaxWidth) {
1356     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1357     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1358       << PointerArg->getType() << PointerArg->getSourceRange();
1359     return true;
1360   }
1361 
1362   switch (ValType.getObjCLifetime()) {
1363   case Qualifiers::OCL_None:
1364   case Qualifiers::OCL_ExplicitNone:
1365     // okay
1366     break;
1367 
1368   case Qualifiers::OCL_Weak:
1369   case Qualifiers::OCL_Strong:
1370   case Qualifiers::OCL_Autoreleasing:
1371     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1372       << ValType << PointerArg->getSourceRange();
1373     return true;
1374   }
1375 
1376   if (IsLdrex) {
1377     TheCall->setType(ValType);
1378     return false;
1379   }
1380 
1381   // Initialize the argument to be stored.
1382   ExprResult ValArg = TheCall->getArg(0);
1383   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1384       Context, ValType, /*consume*/ false);
1385   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1386   if (ValArg.isInvalid())
1387     return true;
1388   TheCall->setArg(0, ValArg.get());
1389 
1390   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1391   // but the custom checker bypasses all default analysis.
1392   TheCall->setType(Context.IntTy);
1393   return false;
1394 }
1395 
1396 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1397   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1398       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1399       BuiltinID == ARM::BI__builtin_arm_strex ||
1400       BuiltinID == ARM::BI__builtin_arm_stlex) {
1401     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1402   }
1403 
1404   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1405     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1406       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1407   }
1408 
1409   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1410       BuiltinID == ARM::BI__builtin_arm_wsr64)
1411     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1412 
1413   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1414       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1415       BuiltinID == ARM::BI__builtin_arm_wsr ||
1416       BuiltinID == ARM::BI__builtin_arm_wsrp)
1417     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1418 
1419   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1420     return true;
1421 
1422   // For intrinsics which take an immediate value as part of the instruction,
1423   // range check them here.
1424   unsigned i = 0, l = 0, u = 0;
1425   switch (BuiltinID) {
1426   default: return false;
1427   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1428   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1429   case ARM::BI__builtin_arm_vcvtr_f:
1430   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1431   case ARM::BI__builtin_arm_dmb:
1432   case ARM::BI__builtin_arm_dsb:
1433   case ARM::BI__builtin_arm_isb:
1434   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1435   }
1436 
1437   // FIXME: VFP Intrinsics should error if VFP not present.
1438   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1439 }
1440 
1441 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1442                                          CallExpr *TheCall) {
1443   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1444       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445       BuiltinID == AArch64::BI__builtin_arm_strex ||
1446       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1447     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448   }
1449 
1450   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455   }
1456 
1457   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1459     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1460 
1461   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466 
1467   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468     return true;
1469 
1470   // For intrinsics which take an immediate value as part of the instruction,
1471   // range check them here.
1472   unsigned i = 0, l = 0, u = 0;
1473   switch (BuiltinID) {
1474   default: return false;
1475   case AArch64::BI__builtin_arm_dmb:
1476   case AArch64::BI__builtin_arm_dsb:
1477   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478   }
1479 
1480   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1481 }
1482 
1483 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485 // ordering for DSP is unspecified. MSA is ordered by the data format used
1486 // by the underlying instruction i.e., df/m, df/n and then by size.
1487 //
1488 // FIXME: The size tests here should instead be tablegen'd along with the
1489 //        definitions from include/clang/Basic/BuiltinsMips.def.
1490 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491 //        be too.
1492 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1493   unsigned i = 0, l = 0, u = 0, m = 0;
1494   switch (BuiltinID) {
1495   default: return false;
1496   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1498   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1503   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504   // df/m field.
1505   // These intrinsics take an unsigned 3 bit immediate.
1506   case Mips::BI__builtin_msa_bclri_b:
1507   case Mips::BI__builtin_msa_bnegi_b:
1508   case Mips::BI__builtin_msa_bseti_b:
1509   case Mips::BI__builtin_msa_sat_s_b:
1510   case Mips::BI__builtin_msa_sat_u_b:
1511   case Mips::BI__builtin_msa_slli_b:
1512   case Mips::BI__builtin_msa_srai_b:
1513   case Mips::BI__builtin_msa_srari_b:
1514   case Mips::BI__builtin_msa_srli_b:
1515   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516   case Mips::BI__builtin_msa_binsli_b:
1517   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518   // These intrinsics take an unsigned 4 bit immediate.
1519   case Mips::BI__builtin_msa_bclri_h:
1520   case Mips::BI__builtin_msa_bnegi_h:
1521   case Mips::BI__builtin_msa_bseti_h:
1522   case Mips::BI__builtin_msa_sat_s_h:
1523   case Mips::BI__builtin_msa_sat_u_h:
1524   case Mips::BI__builtin_msa_slli_h:
1525   case Mips::BI__builtin_msa_srai_h:
1526   case Mips::BI__builtin_msa_srari_h:
1527   case Mips::BI__builtin_msa_srli_h:
1528   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529   case Mips::BI__builtin_msa_binsli_h:
1530   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531   // These intrinsics take an unsigned 5 bit immedate.
1532   // The first block of intrinsics actually have an unsigned 5 bit field,
1533   // not a df/n field.
1534   case Mips::BI__builtin_msa_clei_u_b:
1535   case Mips::BI__builtin_msa_clei_u_h:
1536   case Mips::BI__builtin_msa_clei_u_w:
1537   case Mips::BI__builtin_msa_clei_u_d:
1538   case Mips::BI__builtin_msa_clti_u_b:
1539   case Mips::BI__builtin_msa_clti_u_h:
1540   case Mips::BI__builtin_msa_clti_u_w:
1541   case Mips::BI__builtin_msa_clti_u_d:
1542   case Mips::BI__builtin_msa_maxi_u_b:
1543   case Mips::BI__builtin_msa_maxi_u_h:
1544   case Mips::BI__builtin_msa_maxi_u_w:
1545   case Mips::BI__builtin_msa_maxi_u_d:
1546   case Mips::BI__builtin_msa_mini_u_b:
1547   case Mips::BI__builtin_msa_mini_u_h:
1548   case Mips::BI__builtin_msa_mini_u_w:
1549   case Mips::BI__builtin_msa_mini_u_d:
1550   case Mips::BI__builtin_msa_addvi_b:
1551   case Mips::BI__builtin_msa_addvi_h:
1552   case Mips::BI__builtin_msa_addvi_w:
1553   case Mips::BI__builtin_msa_addvi_d:
1554   case Mips::BI__builtin_msa_bclri_w:
1555   case Mips::BI__builtin_msa_bnegi_w:
1556   case Mips::BI__builtin_msa_bseti_w:
1557   case Mips::BI__builtin_msa_sat_s_w:
1558   case Mips::BI__builtin_msa_sat_u_w:
1559   case Mips::BI__builtin_msa_slli_w:
1560   case Mips::BI__builtin_msa_srai_w:
1561   case Mips::BI__builtin_msa_srari_w:
1562   case Mips::BI__builtin_msa_srli_w:
1563   case Mips::BI__builtin_msa_srlri_w:
1564   case Mips::BI__builtin_msa_subvi_b:
1565   case Mips::BI__builtin_msa_subvi_h:
1566   case Mips::BI__builtin_msa_subvi_w:
1567   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568   case Mips::BI__builtin_msa_binsli_w:
1569   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570   // These intrinsics take an unsigned 6 bit immediate.
1571   case Mips::BI__builtin_msa_bclri_d:
1572   case Mips::BI__builtin_msa_bnegi_d:
1573   case Mips::BI__builtin_msa_bseti_d:
1574   case Mips::BI__builtin_msa_sat_s_d:
1575   case Mips::BI__builtin_msa_sat_u_d:
1576   case Mips::BI__builtin_msa_slli_d:
1577   case Mips::BI__builtin_msa_srai_d:
1578   case Mips::BI__builtin_msa_srari_d:
1579   case Mips::BI__builtin_msa_srli_d:
1580   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581   case Mips::BI__builtin_msa_binsli_d:
1582   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583   // These intrinsics take a signed 5 bit immediate.
1584   case Mips::BI__builtin_msa_ceqi_b:
1585   case Mips::BI__builtin_msa_ceqi_h:
1586   case Mips::BI__builtin_msa_ceqi_w:
1587   case Mips::BI__builtin_msa_ceqi_d:
1588   case Mips::BI__builtin_msa_clti_s_b:
1589   case Mips::BI__builtin_msa_clti_s_h:
1590   case Mips::BI__builtin_msa_clti_s_w:
1591   case Mips::BI__builtin_msa_clti_s_d:
1592   case Mips::BI__builtin_msa_clei_s_b:
1593   case Mips::BI__builtin_msa_clei_s_h:
1594   case Mips::BI__builtin_msa_clei_s_w:
1595   case Mips::BI__builtin_msa_clei_s_d:
1596   case Mips::BI__builtin_msa_maxi_s_b:
1597   case Mips::BI__builtin_msa_maxi_s_h:
1598   case Mips::BI__builtin_msa_maxi_s_w:
1599   case Mips::BI__builtin_msa_maxi_s_d:
1600   case Mips::BI__builtin_msa_mini_s_b:
1601   case Mips::BI__builtin_msa_mini_s_h:
1602   case Mips::BI__builtin_msa_mini_s_w:
1603   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604   // These intrinsics take an unsigned 8 bit immediate.
1605   case Mips::BI__builtin_msa_andi_b:
1606   case Mips::BI__builtin_msa_nori_b:
1607   case Mips::BI__builtin_msa_ori_b:
1608   case Mips::BI__builtin_msa_shf_b:
1609   case Mips::BI__builtin_msa_shf_h:
1610   case Mips::BI__builtin_msa_shf_w:
1611   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612   case Mips::BI__builtin_msa_bseli_b:
1613   case Mips::BI__builtin_msa_bmnzi_b:
1614   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615   // df/n format
1616   // These intrinsics take an unsigned 4 bit immediate.
1617   case Mips::BI__builtin_msa_copy_s_b:
1618   case Mips::BI__builtin_msa_copy_u_b:
1619   case Mips::BI__builtin_msa_insve_b:
1620   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1621   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1622   // These intrinsics take an unsigned 3 bit immediate.
1623   case Mips::BI__builtin_msa_copy_s_h:
1624   case Mips::BI__builtin_msa_copy_u_h:
1625   case Mips::BI__builtin_msa_insve_h:
1626   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1627   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1628   // These intrinsics take an unsigned 2 bit immediate.
1629   case Mips::BI__builtin_msa_copy_s_w:
1630   case Mips::BI__builtin_msa_copy_u_w:
1631   case Mips::BI__builtin_msa_insve_w:
1632   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1633   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1634   // These intrinsics take an unsigned 1 bit immediate.
1635   case Mips::BI__builtin_msa_copy_s_d:
1636   case Mips::BI__builtin_msa_copy_u_d:
1637   case Mips::BI__builtin_msa_insve_d:
1638   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1639   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1640   // Memory offsets and immediate loads.
1641   // These intrinsics take a signed 10 bit immediate.
1642   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1643   case Mips::BI__builtin_msa_ldi_h:
1644   case Mips::BI__builtin_msa_ldi_w:
1645   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1646   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1647   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1648   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1649   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1650   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1651   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1652   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1653   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1654   }
1655 
1656   if (!m)
1657     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1658 
1659   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1660          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1661 }
1662 
1663 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1664   unsigned i = 0, l = 0, u = 0;
1665   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1666                       BuiltinID == PPC::BI__builtin_divdeu ||
1667                       BuiltinID == PPC::BI__builtin_bpermd;
1668   bool IsTarget64Bit = Context.getTargetInfo()
1669                               .getTypeWidth(Context
1670                                             .getTargetInfo()
1671                                             .getIntPtrType()) == 64;
1672   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1673                        BuiltinID == PPC::BI__builtin_divweu ||
1674                        BuiltinID == PPC::BI__builtin_divde ||
1675                        BuiltinID == PPC::BI__builtin_divdeu;
1676 
1677   if (Is64BitBltin && !IsTarget64Bit)
1678       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1679              << TheCall->getSourceRange();
1680 
1681   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1682       (BuiltinID == PPC::BI__builtin_bpermd &&
1683        !Context.getTargetInfo().hasFeature("bpermd")))
1684     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1685            << TheCall->getSourceRange();
1686 
1687   switch (BuiltinID) {
1688   default: return false;
1689   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1690   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1691     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1692            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1693   case PPC::BI__builtin_tbegin:
1694   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1695   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1696   case PPC::BI__builtin_tabortwc:
1697   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1698   case PPC::BI__builtin_tabortwci:
1699   case PPC::BI__builtin_tabortdci:
1700     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1701            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1702   case PPC::BI__builtin_vsx_xxpermdi:
1703   case PPC::BI__builtin_vsx_xxsldwi:
1704     return SemaBuiltinVSX(TheCall);
1705   }
1706   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1707 }
1708 
1709 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1710                                            CallExpr *TheCall) {
1711   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1712     Expr *Arg = TheCall->getArg(0);
1713     llvm::APSInt AbortCode(32);
1714     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1715         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1716       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1717              << Arg->getSourceRange();
1718   }
1719 
1720   // For intrinsics which take an immediate value as part of the instruction,
1721   // range check them here.
1722   unsigned i = 0, l = 0, u = 0;
1723   switch (BuiltinID) {
1724   default: return false;
1725   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1726   case SystemZ::BI__builtin_s390_verimb:
1727   case SystemZ::BI__builtin_s390_verimh:
1728   case SystemZ::BI__builtin_s390_verimf:
1729   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1730   case SystemZ::BI__builtin_s390_vfaeb:
1731   case SystemZ::BI__builtin_s390_vfaeh:
1732   case SystemZ::BI__builtin_s390_vfaef:
1733   case SystemZ::BI__builtin_s390_vfaebs:
1734   case SystemZ::BI__builtin_s390_vfaehs:
1735   case SystemZ::BI__builtin_s390_vfaefs:
1736   case SystemZ::BI__builtin_s390_vfaezb:
1737   case SystemZ::BI__builtin_s390_vfaezh:
1738   case SystemZ::BI__builtin_s390_vfaezf:
1739   case SystemZ::BI__builtin_s390_vfaezbs:
1740   case SystemZ::BI__builtin_s390_vfaezhs:
1741   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1742   case SystemZ::BI__builtin_s390_vfidb:
1743     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1744            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1745   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1746   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1747   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1748   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1749   case SystemZ::BI__builtin_s390_vstrcb:
1750   case SystemZ::BI__builtin_s390_vstrch:
1751   case SystemZ::BI__builtin_s390_vstrcf:
1752   case SystemZ::BI__builtin_s390_vstrczb:
1753   case SystemZ::BI__builtin_s390_vstrczh:
1754   case SystemZ::BI__builtin_s390_vstrczf:
1755   case SystemZ::BI__builtin_s390_vstrcbs:
1756   case SystemZ::BI__builtin_s390_vstrchs:
1757   case SystemZ::BI__builtin_s390_vstrcfs:
1758   case SystemZ::BI__builtin_s390_vstrczbs:
1759   case SystemZ::BI__builtin_s390_vstrczhs:
1760   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1761   }
1762   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1763 }
1764 
1765 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1766 /// This checks that the target supports __builtin_cpu_supports and
1767 /// that the string argument is constant and valid.
1768 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1769   Expr *Arg = TheCall->getArg(0);
1770 
1771   // Check if the argument is a string literal.
1772   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1773     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1774            << Arg->getSourceRange();
1775 
1776   // Check the contents of the string.
1777   StringRef Feature =
1778       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1779   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1780     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1781            << Arg->getSourceRange();
1782   return false;
1783 }
1784 
1785 // Check if the rounding mode is legal.
1786 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1787   // Indicates if this instruction has rounding control or just SAE.
1788   bool HasRC = false;
1789 
1790   unsigned ArgNum = 0;
1791   switch (BuiltinID) {
1792   default:
1793     return false;
1794   case X86::BI__builtin_ia32_vcvttsd2si32:
1795   case X86::BI__builtin_ia32_vcvttsd2si64:
1796   case X86::BI__builtin_ia32_vcvttsd2usi32:
1797   case X86::BI__builtin_ia32_vcvttsd2usi64:
1798   case X86::BI__builtin_ia32_vcvttss2si32:
1799   case X86::BI__builtin_ia32_vcvttss2si64:
1800   case X86::BI__builtin_ia32_vcvttss2usi32:
1801   case X86::BI__builtin_ia32_vcvttss2usi64:
1802     ArgNum = 1;
1803     break;
1804   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1805   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1806   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1807   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1808   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1809   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1810   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1811   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1812   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1813   case X86::BI__builtin_ia32_exp2pd_mask:
1814   case X86::BI__builtin_ia32_exp2ps_mask:
1815   case X86::BI__builtin_ia32_getexppd512_mask:
1816   case X86::BI__builtin_ia32_getexpps512_mask:
1817   case X86::BI__builtin_ia32_rcp28pd_mask:
1818   case X86::BI__builtin_ia32_rcp28ps_mask:
1819   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1820   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1821   case X86::BI__builtin_ia32_vcomisd:
1822   case X86::BI__builtin_ia32_vcomiss:
1823   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1824     ArgNum = 3;
1825     break;
1826   case X86::BI__builtin_ia32_cmppd512_mask:
1827   case X86::BI__builtin_ia32_cmpps512_mask:
1828   case X86::BI__builtin_ia32_cmpsd_mask:
1829   case X86::BI__builtin_ia32_cmpss_mask:
1830   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1831   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1832   case X86::BI__builtin_ia32_getexpss128_round_mask:
1833   case X86::BI__builtin_ia32_maxpd512_mask:
1834   case X86::BI__builtin_ia32_maxps512_mask:
1835   case X86::BI__builtin_ia32_maxsd_round_mask:
1836   case X86::BI__builtin_ia32_maxss_round_mask:
1837   case X86::BI__builtin_ia32_minpd512_mask:
1838   case X86::BI__builtin_ia32_minps512_mask:
1839   case X86::BI__builtin_ia32_minsd_round_mask:
1840   case X86::BI__builtin_ia32_minss_round_mask:
1841   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1842   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1843   case X86::BI__builtin_ia32_reducepd512_mask:
1844   case X86::BI__builtin_ia32_reduceps512_mask:
1845   case X86::BI__builtin_ia32_rndscalepd_mask:
1846   case X86::BI__builtin_ia32_rndscaleps_mask:
1847   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1848   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1849     ArgNum = 4;
1850     break;
1851   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1852   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1853   case X86::BI__builtin_ia32_fixupimmps512_mask:
1854   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1855   case X86::BI__builtin_ia32_fixupimmsd_mask:
1856   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1857   case X86::BI__builtin_ia32_fixupimmss_mask:
1858   case X86::BI__builtin_ia32_fixupimmss_maskz:
1859   case X86::BI__builtin_ia32_rangepd512_mask:
1860   case X86::BI__builtin_ia32_rangeps512_mask:
1861   case X86::BI__builtin_ia32_rangesd128_round_mask:
1862   case X86::BI__builtin_ia32_rangess128_round_mask:
1863   case X86::BI__builtin_ia32_reducesd_mask:
1864   case X86::BI__builtin_ia32_reducess_mask:
1865   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1866   case X86::BI__builtin_ia32_rndscaless_round_mask:
1867     ArgNum = 5;
1868     break;
1869   case X86::BI__builtin_ia32_vcvtsd2si64:
1870   case X86::BI__builtin_ia32_vcvtsd2si32:
1871   case X86::BI__builtin_ia32_vcvtsd2usi32:
1872   case X86::BI__builtin_ia32_vcvtsd2usi64:
1873   case X86::BI__builtin_ia32_vcvtss2si32:
1874   case X86::BI__builtin_ia32_vcvtss2si64:
1875   case X86::BI__builtin_ia32_vcvtss2usi32:
1876   case X86::BI__builtin_ia32_vcvtss2usi64:
1877     ArgNum = 1;
1878     HasRC = true;
1879     break;
1880   case X86::BI__builtin_ia32_cvtsi2sd64:
1881   case X86::BI__builtin_ia32_cvtsi2ss32:
1882   case X86::BI__builtin_ia32_cvtsi2ss64:
1883   case X86::BI__builtin_ia32_cvtusi2sd64:
1884   case X86::BI__builtin_ia32_cvtusi2ss32:
1885   case X86::BI__builtin_ia32_cvtusi2ss64:
1886     ArgNum = 2;
1887     HasRC = true;
1888     break;
1889   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1890   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1891   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1892   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1893   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1894   case X86::BI__builtin_ia32_cvtps2qq512_mask:
1895   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1896   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1897   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1898   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1899   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1900   case X86::BI__builtin_ia32_sqrtpd512_mask:
1901   case X86::BI__builtin_ia32_sqrtps512_mask:
1902     ArgNum = 3;
1903     HasRC = true;
1904     break;
1905   case X86::BI__builtin_ia32_addpd512_mask:
1906   case X86::BI__builtin_ia32_addps512_mask:
1907   case X86::BI__builtin_ia32_divpd512_mask:
1908   case X86::BI__builtin_ia32_divps512_mask:
1909   case X86::BI__builtin_ia32_mulpd512_mask:
1910   case X86::BI__builtin_ia32_mulps512_mask:
1911   case X86::BI__builtin_ia32_subpd512_mask:
1912   case X86::BI__builtin_ia32_subps512_mask:
1913   case X86::BI__builtin_ia32_addss_round_mask:
1914   case X86::BI__builtin_ia32_addsd_round_mask:
1915   case X86::BI__builtin_ia32_divss_round_mask:
1916   case X86::BI__builtin_ia32_divsd_round_mask:
1917   case X86::BI__builtin_ia32_mulss_round_mask:
1918   case X86::BI__builtin_ia32_mulsd_round_mask:
1919   case X86::BI__builtin_ia32_subss_round_mask:
1920   case X86::BI__builtin_ia32_subsd_round_mask:
1921   case X86::BI__builtin_ia32_scalefpd512_mask:
1922   case X86::BI__builtin_ia32_scalefps512_mask:
1923   case X86::BI__builtin_ia32_scalefsd_round_mask:
1924   case X86::BI__builtin_ia32_scalefss_round_mask:
1925   case X86::BI__builtin_ia32_getmantpd512_mask:
1926   case X86::BI__builtin_ia32_getmantps512_mask:
1927   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1928   case X86::BI__builtin_ia32_sqrtsd_round_mask:
1929   case X86::BI__builtin_ia32_sqrtss_round_mask:
1930   case X86::BI__builtin_ia32_vfmaddpd512_mask:
1931   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1932   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1933   case X86::BI__builtin_ia32_vfmaddps512_mask:
1934   case X86::BI__builtin_ia32_vfmaddps512_mask3:
1935   case X86::BI__builtin_ia32_vfmaddps512_maskz:
1936   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1937   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1938   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1939   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1940   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1941   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1942   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1943   case X86::BI__builtin_ia32_vfmsubps512_mask3:
1944   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1945   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1946   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1947   case X86::BI__builtin_ia32_vfnmaddps512_mask:
1948   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1949   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1950   case X86::BI__builtin_ia32_vfnmsubps512_mask:
1951   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1952   case X86::BI__builtin_ia32_vfmaddsd3_mask:
1953   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1954   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1955   case X86::BI__builtin_ia32_vfmaddss3_mask:
1956   case X86::BI__builtin_ia32_vfmaddss3_maskz:
1957   case X86::BI__builtin_ia32_vfmaddss3_mask3:
1958     ArgNum = 4;
1959     HasRC = true;
1960     break;
1961   case X86::BI__builtin_ia32_getmantsd_round_mask:
1962   case X86::BI__builtin_ia32_getmantss_round_mask:
1963     ArgNum = 5;
1964     HasRC = true;
1965     break;
1966   }
1967 
1968   llvm::APSInt Result;
1969 
1970   // We can't check the value of a dependent argument.
1971   Expr *Arg = TheCall->getArg(ArgNum);
1972   if (Arg->isTypeDependent() || Arg->isValueDependent())
1973     return false;
1974 
1975   // Check constant-ness first.
1976   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1977     return true;
1978 
1979   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1980   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1981   // combined with ROUND_NO_EXC.
1982   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1983       Result == 8/*ROUND_NO_EXC*/ ||
1984       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1985     return false;
1986 
1987   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1988     << Arg->getSourceRange();
1989 }
1990 
1991 // Check if the gather/scatter scale is legal.
1992 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
1993                                              CallExpr *TheCall) {
1994   unsigned ArgNum = 0;
1995   switch (BuiltinID) {
1996   default:
1997     return false;
1998   case X86::BI__builtin_ia32_gatherpfdpd:
1999   case X86::BI__builtin_ia32_gatherpfdps:
2000   case X86::BI__builtin_ia32_gatherpfqpd:
2001   case X86::BI__builtin_ia32_gatherpfqps:
2002   case X86::BI__builtin_ia32_scatterpfdpd:
2003   case X86::BI__builtin_ia32_scatterpfdps:
2004   case X86::BI__builtin_ia32_scatterpfqpd:
2005   case X86::BI__builtin_ia32_scatterpfqps:
2006     ArgNum = 3;
2007     break;
2008   case X86::BI__builtin_ia32_gatherd_pd:
2009   case X86::BI__builtin_ia32_gatherd_pd256:
2010   case X86::BI__builtin_ia32_gatherq_pd:
2011   case X86::BI__builtin_ia32_gatherq_pd256:
2012   case X86::BI__builtin_ia32_gatherd_ps:
2013   case X86::BI__builtin_ia32_gatherd_ps256:
2014   case X86::BI__builtin_ia32_gatherq_ps:
2015   case X86::BI__builtin_ia32_gatherq_ps256:
2016   case X86::BI__builtin_ia32_gatherd_q:
2017   case X86::BI__builtin_ia32_gatherd_q256:
2018   case X86::BI__builtin_ia32_gatherq_q:
2019   case X86::BI__builtin_ia32_gatherq_q256:
2020   case X86::BI__builtin_ia32_gatherd_d:
2021   case X86::BI__builtin_ia32_gatherd_d256:
2022   case X86::BI__builtin_ia32_gatherq_d:
2023   case X86::BI__builtin_ia32_gatherq_d256:
2024   case X86::BI__builtin_ia32_gather3div2df:
2025   case X86::BI__builtin_ia32_gather3div2di:
2026   case X86::BI__builtin_ia32_gather3div4df:
2027   case X86::BI__builtin_ia32_gather3div4di:
2028   case X86::BI__builtin_ia32_gather3div4sf:
2029   case X86::BI__builtin_ia32_gather3div4si:
2030   case X86::BI__builtin_ia32_gather3div8sf:
2031   case X86::BI__builtin_ia32_gather3div8si:
2032   case X86::BI__builtin_ia32_gather3siv2df:
2033   case X86::BI__builtin_ia32_gather3siv2di:
2034   case X86::BI__builtin_ia32_gather3siv4df:
2035   case X86::BI__builtin_ia32_gather3siv4di:
2036   case X86::BI__builtin_ia32_gather3siv4sf:
2037   case X86::BI__builtin_ia32_gather3siv4si:
2038   case X86::BI__builtin_ia32_gather3siv8sf:
2039   case X86::BI__builtin_ia32_gather3siv8si:
2040   case X86::BI__builtin_ia32_gathersiv8df:
2041   case X86::BI__builtin_ia32_gathersiv16sf:
2042   case X86::BI__builtin_ia32_gatherdiv8df:
2043   case X86::BI__builtin_ia32_gatherdiv16sf:
2044   case X86::BI__builtin_ia32_gathersiv8di:
2045   case X86::BI__builtin_ia32_gathersiv16si:
2046   case X86::BI__builtin_ia32_gatherdiv8di:
2047   case X86::BI__builtin_ia32_gatherdiv16si:
2048   case X86::BI__builtin_ia32_scatterdiv2df:
2049   case X86::BI__builtin_ia32_scatterdiv2di:
2050   case X86::BI__builtin_ia32_scatterdiv4df:
2051   case X86::BI__builtin_ia32_scatterdiv4di:
2052   case X86::BI__builtin_ia32_scatterdiv4sf:
2053   case X86::BI__builtin_ia32_scatterdiv4si:
2054   case X86::BI__builtin_ia32_scatterdiv8sf:
2055   case X86::BI__builtin_ia32_scatterdiv8si:
2056   case X86::BI__builtin_ia32_scattersiv2df:
2057   case X86::BI__builtin_ia32_scattersiv2di:
2058   case X86::BI__builtin_ia32_scattersiv4df:
2059   case X86::BI__builtin_ia32_scattersiv4di:
2060   case X86::BI__builtin_ia32_scattersiv4sf:
2061   case X86::BI__builtin_ia32_scattersiv4si:
2062   case X86::BI__builtin_ia32_scattersiv8sf:
2063   case X86::BI__builtin_ia32_scattersiv8si:
2064   case X86::BI__builtin_ia32_scattersiv8df:
2065   case X86::BI__builtin_ia32_scattersiv16sf:
2066   case X86::BI__builtin_ia32_scatterdiv8df:
2067   case X86::BI__builtin_ia32_scatterdiv16sf:
2068   case X86::BI__builtin_ia32_scattersiv8di:
2069   case X86::BI__builtin_ia32_scattersiv16si:
2070   case X86::BI__builtin_ia32_scatterdiv8di:
2071   case X86::BI__builtin_ia32_scatterdiv16si:
2072     ArgNum = 4;
2073     break;
2074   }
2075 
2076   llvm::APSInt Result;
2077 
2078   // We can't check the value of a dependent argument.
2079   Expr *Arg = TheCall->getArg(ArgNum);
2080   if (Arg->isTypeDependent() || Arg->isValueDependent())
2081     return false;
2082 
2083   // Check constant-ness first.
2084   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2085     return true;
2086 
2087   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2088     return false;
2089 
2090   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2091     << Arg->getSourceRange();
2092 }
2093 
2094 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2095   if (BuiltinID == X86::BI__builtin_cpu_supports)
2096     return SemaBuiltinCpuSupports(*this, TheCall);
2097 
2098   if (BuiltinID == X86::BI__builtin_ms_va_start)
2099     return SemaBuiltinVAStart(BuiltinID, TheCall);
2100 
2101   // If the intrinsic has rounding or SAE make sure its valid.
2102   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2103     return true;
2104 
2105   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2106   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2107     return true;
2108 
2109   // For intrinsics which take an immediate value as part of the instruction,
2110   // range check them here.
2111   int i = 0, l = 0, u = 0;
2112   switch (BuiltinID) {
2113   default:
2114     return false;
2115   case X86::BI_mm_prefetch:
2116     i = 1; l = 0; u = 3;
2117     break;
2118   case X86::BI__builtin_ia32_sha1rnds4:
2119   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2120   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2121   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2122   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2123     i = 2; l = 0; u = 3;
2124     break;
2125   case X86::BI__builtin_ia32_vpermil2pd:
2126   case X86::BI__builtin_ia32_vpermil2pd256:
2127   case X86::BI__builtin_ia32_vpermil2ps:
2128   case X86::BI__builtin_ia32_vpermil2ps256:
2129     i = 3; l = 0; u = 3;
2130     break;
2131   case X86::BI__builtin_ia32_cmpb128_mask:
2132   case X86::BI__builtin_ia32_cmpw128_mask:
2133   case X86::BI__builtin_ia32_cmpd128_mask:
2134   case X86::BI__builtin_ia32_cmpq128_mask:
2135   case X86::BI__builtin_ia32_cmpb256_mask:
2136   case X86::BI__builtin_ia32_cmpw256_mask:
2137   case X86::BI__builtin_ia32_cmpd256_mask:
2138   case X86::BI__builtin_ia32_cmpq256_mask:
2139   case X86::BI__builtin_ia32_cmpb512_mask:
2140   case X86::BI__builtin_ia32_cmpw512_mask:
2141   case X86::BI__builtin_ia32_cmpd512_mask:
2142   case X86::BI__builtin_ia32_cmpq512_mask:
2143   case X86::BI__builtin_ia32_ucmpb128_mask:
2144   case X86::BI__builtin_ia32_ucmpw128_mask:
2145   case X86::BI__builtin_ia32_ucmpd128_mask:
2146   case X86::BI__builtin_ia32_ucmpq128_mask:
2147   case X86::BI__builtin_ia32_ucmpb256_mask:
2148   case X86::BI__builtin_ia32_ucmpw256_mask:
2149   case X86::BI__builtin_ia32_ucmpd256_mask:
2150   case X86::BI__builtin_ia32_ucmpq256_mask:
2151   case X86::BI__builtin_ia32_ucmpb512_mask:
2152   case X86::BI__builtin_ia32_ucmpw512_mask:
2153   case X86::BI__builtin_ia32_ucmpd512_mask:
2154   case X86::BI__builtin_ia32_ucmpq512_mask:
2155   case X86::BI__builtin_ia32_vpcomub:
2156   case X86::BI__builtin_ia32_vpcomuw:
2157   case X86::BI__builtin_ia32_vpcomud:
2158   case X86::BI__builtin_ia32_vpcomuq:
2159   case X86::BI__builtin_ia32_vpcomb:
2160   case X86::BI__builtin_ia32_vpcomw:
2161   case X86::BI__builtin_ia32_vpcomd:
2162   case X86::BI__builtin_ia32_vpcomq:
2163     i = 2; l = 0; u = 7;
2164     break;
2165   case X86::BI__builtin_ia32_roundps:
2166   case X86::BI__builtin_ia32_roundpd:
2167   case X86::BI__builtin_ia32_roundps256:
2168   case X86::BI__builtin_ia32_roundpd256:
2169     i = 1; l = 0; u = 15;
2170     break;
2171   case X86::BI__builtin_ia32_roundss:
2172   case X86::BI__builtin_ia32_roundsd:
2173   case X86::BI__builtin_ia32_rangepd128_mask:
2174   case X86::BI__builtin_ia32_rangepd256_mask:
2175   case X86::BI__builtin_ia32_rangepd512_mask:
2176   case X86::BI__builtin_ia32_rangeps128_mask:
2177   case X86::BI__builtin_ia32_rangeps256_mask:
2178   case X86::BI__builtin_ia32_rangeps512_mask:
2179   case X86::BI__builtin_ia32_getmantsd_round_mask:
2180   case X86::BI__builtin_ia32_getmantss_round_mask:
2181     i = 2; l = 0; u = 15;
2182     break;
2183   case X86::BI__builtin_ia32_cmpps:
2184   case X86::BI__builtin_ia32_cmpss:
2185   case X86::BI__builtin_ia32_cmppd:
2186   case X86::BI__builtin_ia32_cmpsd:
2187   case X86::BI__builtin_ia32_cmpps256:
2188   case X86::BI__builtin_ia32_cmppd256:
2189   case X86::BI__builtin_ia32_cmpps128_mask:
2190   case X86::BI__builtin_ia32_cmppd128_mask:
2191   case X86::BI__builtin_ia32_cmpps256_mask:
2192   case X86::BI__builtin_ia32_cmppd256_mask:
2193   case X86::BI__builtin_ia32_cmpps512_mask:
2194   case X86::BI__builtin_ia32_cmppd512_mask:
2195   case X86::BI__builtin_ia32_cmpsd_mask:
2196   case X86::BI__builtin_ia32_cmpss_mask:
2197     i = 2; l = 0; u = 31;
2198     break;
2199   case X86::BI__builtin_ia32_xabort:
2200     i = 0; l = -128; u = 255;
2201     break;
2202   case X86::BI__builtin_ia32_pshufw:
2203   case X86::BI__builtin_ia32_aeskeygenassist128:
2204     i = 1; l = -128; u = 255;
2205     break;
2206   case X86::BI__builtin_ia32_vcvtps2ph:
2207   case X86::BI__builtin_ia32_vcvtps2ph256:
2208   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2209   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2210   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2211   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2212   case X86::BI__builtin_ia32_rndscaleps_mask:
2213   case X86::BI__builtin_ia32_rndscalepd_mask:
2214   case X86::BI__builtin_ia32_reducepd128_mask:
2215   case X86::BI__builtin_ia32_reducepd256_mask:
2216   case X86::BI__builtin_ia32_reducepd512_mask:
2217   case X86::BI__builtin_ia32_reduceps128_mask:
2218   case X86::BI__builtin_ia32_reduceps256_mask:
2219   case X86::BI__builtin_ia32_reduceps512_mask:
2220   case X86::BI__builtin_ia32_prold512_mask:
2221   case X86::BI__builtin_ia32_prolq512_mask:
2222   case X86::BI__builtin_ia32_prold128_mask:
2223   case X86::BI__builtin_ia32_prold256_mask:
2224   case X86::BI__builtin_ia32_prolq128_mask:
2225   case X86::BI__builtin_ia32_prolq256_mask:
2226   case X86::BI__builtin_ia32_prord128_mask:
2227   case X86::BI__builtin_ia32_prord256_mask:
2228   case X86::BI__builtin_ia32_prorq128_mask:
2229   case X86::BI__builtin_ia32_prorq256_mask:
2230   case X86::BI__builtin_ia32_fpclasspd128_mask:
2231   case X86::BI__builtin_ia32_fpclasspd256_mask:
2232   case X86::BI__builtin_ia32_fpclassps128_mask:
2233   case X86::BI__builtin_ia32_fpclassps256_mask:
2234   case X86::BI__builtin_ia32_fpclassps512_mask:
2235   case X86::BI__builtin_ia32_fpclasspd512_mask:
2236   case X86::BI__builtin_ia32_fpclasssd_mask:
2237   case X86::BI__builtin_ia32_fpclassss_mask:
2238     i = 1; l = 0; u = 255;
2239     break;
2240   case X86::BI__builtin_ia32_palignr:
2241   case X86::BI__builtin_ia32_insertps128:
2242   case X86::BI__builtin_ia32_dpps:
2243   case X86::BI__builtin_ia32_dppd:
2244   case X86::BI__builtin_ia32_dpps256:
2245   case X86::BI__builtin_ia32_mpsadbw128:
2246   case X86::BI__builtin_ia32_mpsadbw256:
2247   case X86::BI__builtin_ia32_pcmpistrm128:
2248   case X86::BI__builtin_ia32_pcmpistri128:
2249   case X86::BI__builtin_ia32_pcmpistria128:
2250   case X86::BI__builtin_ia32_pcmpistric128:
2251   case X86::BI__builtin_ia32_pcmpistrio128:
2252   case X86::BI__builtin_ia32_pcmpistris128:
2253   case X86::BI__builtin_ia32_pcmpistriz128:
2254   case X86::BI__builtin_ia32_pclmulqdq128:
2255   case X86::BI__builtin_ia32_vperm2f128_pd256:
2256   case X86::BI__builtin_ia32_vperm2f128_ps256:
2257   case X86::BI__builtin_ia32_vperm2f128_si256:
2258   case X86::BI__builtin_ia32_permti256:
2259     i = 2; l = -128; u = 255;
2260     break;
2261   case X86::BI__builtin_ia32_palignr128:
2262   case X86::BI__builtin_ia32_palignr256:
2263   case X86::BI__builtin_ia32_palignr512_mask:
2264   case X86::BI__builtin_ia32_vcomisd:
2265   case X86::BI__builtin_ia32_vcomiss:
2266   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2267   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2268   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2269   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2270   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2271   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2272   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2273     i = 2; l = 0; u = 255;
2274     break;
2275   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2276   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2277   case X86::BI__builtin_ia32_fixupimmps512_mask:
2278   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2279   case X86::BI__builtin_ia32_fixupimmsd_mask:
2280   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2281   case X86::BI__builtin_ia32_fixupimmss_mask:
2282   case X86::BI__builtin_ia32_fixupimmss_maskz:
2283   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2284   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2285   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2286   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2287   case X86::BI__builtin_ia32_fixupimmps128_mask:
2288   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2289   case X86::BI__builtin_ia32_fixupimmps256_mask:
2290   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2291   case X86::BI__builtin_ia32_pternlogd512_mask:
2292   case X86::BI__builtin_ia32_pternlogd512_maskz:
2293   case X86::BI__builtin_ia32_pternlogq512_mask:
2294   case X86::BI__builtin_ia32_pternlogq512_maskz:
2295   case X86::BI__builtin_ia32_pternlogd128_mask:
2296   case X86::BI__builtin_ia32_pternlogd128_maskz:
2297   case X86::BI__builtin_ia32_pternlogd256_mask:
2298   case X86::BI__builtin_ia32_pternlogd256_maskz:
2299   case X86::BI__builtin_ia32_pternlogq128_mask:
2300   case X86::BI__builtin_ia32_pternlogq128_maskz:
2301   case X86::BI__builtin_ia32_pternlogq256_mask:
2302   case X86::BI__builtin_ia32_pternlogq256_maskz:
2303     i = 3; l = 0; u = 255;
2304     break;
2305   case X86::BI__builtin_ia32_gatherpfdpd:
2306   case X86::BI__builtin_ia32_gatherpfdps:
2307   case X86::BI__builtin_ia32_gatherpfqpd:
2308   case X86::BI__builtin_ia32_gatherpfqps:
2309   case X86::BI__builtin_ia32_scatterpfdpd:
2310   case X86::BI__builtin_ia32_scatterpfdps:
2311   case X86::BI__builtin_ia32_scatterpfqpd:
2312   case X86::BI__builtin_ia32_scatterpfqps:
2313     i = 4; l = 2; u = 3;
2314     break;
2315   case X86::BI__builtin_ia32_pcmpestrm128:
2316   case X86::BI__builtin_ia32_pcmpestri128:
2317   case X86::BI__builtin_ia32_pcmpestria128:
2318   case X86::BI__builtin_ia32_pcmpestric128:
2319   case X86::BI__builtin_ia32_pcmpestrio128:
2320   case X86::BI__builtin_ia32_pcmpestris128:
2321   case X86::BI__builtin_ia32_pcmpestriz128:
2322     i = 4; l = -128; u = 255;
2323     break;
2324   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2325   case X86::BI__builtin_ia32_rndscaless_round_mask:
2326     i = 4; l = 0; u = 255;
2327     break;
2328   }
2329   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2330 }
2331 
2332 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2333 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2334 /// Returns true when the format fits the function and the FormatStringInfo has
2335 /// been populated.
2336 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2337                                FormatStringInfo *FSI) {
2338   FSI->HasVAListArg = Format->getFirstArg() == 0;
2339   FSI->FormatIdx = Format->getFormatIdx() - 1;
2340   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2341 
2342   // The way the format attribute works in GCC, the implicit this argument
2343   // of member functions is counted. However, it doesn't appear in our own
2344   // lists, so decrement format_idx in that case.
2345   if (IsCXXMember) {
2346     if(FSI->FormatIdx == 0)
2347       return false;
2348     --FSI->FormatIdx;
2349     if (FSI->FirstDataArg != 0)
2350       --FSI->FirstDataArg;
2351   }
2352   return true;
2353 }
2354 
2355 /// Checks if a the given expression evaluates to null.
2356 ///
2357 /// \brief Returns true if the value evaluates to null.
2358 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2359   // If the expression has non-null type, it doesn't evaluate to null.
2360   if (auto nullability
2361         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2362     if (*nullability == NullabilityKind::NonNull)
2363       return false;
2364   }
2365 
2366   // As a special case, transparent unions initialized with zero are
2367   // considered null for the purposes of the nonnull attribute.
2368   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2369     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2370       if (const CompoundLiteralExpr *CLE =
2371           dyn_cast<CompoundLiteralExpr>(Expr))
2372         if (const InitListExpr *ILE =
2373             dyn_cast<InitListExpr>(CLE->getInitializer()))
2374           Expr = ILE->getInit(0);
2375   }
2376 
2377   bool Result;
2378   return (!Expr->isValueDependent() &&
2379           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2380           !Result);
2381 }
2382 
2383 static void CheckNonNullArgument(Sema &S,
2384                                  const Expr *ArgExpr,
2385                                  SourceLocation CallSiteLoc) {
2386   if (CheckNonNullExpr(S, ArgExpr))
2387     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2388            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2389 }
2390 
2391 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2392   FormatStringInfo FSI;
2393   if ((GetFormatStringType(Format) == FST_NSString) &&
2394       getFormatStringInfo(Format, false, &FSI)) {
2395     Idx = FSI.FormatIdx;
2396     return true;
2397   }
2398   return false;
2399 }
2400 /// \brief Diagnose use of %s directive in an NSString which is being passed
2401 /// as formatting string to formatting method.
2402 static void
2403 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2404                                         const NamedDecl *FDecl,
2405                                         Expr **Args,
2406                                         unsigned NumArgs) {
2407   unsigned Idx = 0;
2408   bool Format = false;
2409   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2410   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2411     Idx = 2;
2412     Format = true;
2413   }
2414   else
2415     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2416       if (S.GetFormatNSStringIdx(I, Idx)) {
2417         Format = true;
2418         break;
2419       }
2420     }
2421   if (!Format || NumArgs <= Idx)
2422     return;
2423   const Expr *FormatExpr = Args[Idx];
2424   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2425     FormatExpr = CSCE->getSubExpr();
2426   const StringLiteral *FormatString;
2427   if (const ObjCStringLiteral *OSL =
2428       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2429     FormatString = OSL->getString();
2430   else
2431     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2432   if (!FormatString)
2433     return;
2434   if (S.FormatStringHasSArg(FormatString)) {
2435     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2436       << "%s" << 1 << 1;
2437     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2438       << FDecl->getDeclName();
2439   }
2440 }
2441 
2442 /// Determine whether the given type has a non-null nullability annotation.
2443 static bool isNonNullType(ASTContext &ctx, QualType type) {
2444   if (auto nullability = type->getNullability(ctx))
2445     return *nullability == NullabilityKind::NonNull;
2446 
2447   return false;
2448 }
2449 
2450 static void CheckNonNullArguments(Sema &S,
2451                                   const NamedDecl *FDecl,
2452                                   const FunctionProtoType *Proto,
2453                                   ArrayRef<const Expr *> Args,
2454                                   SourceLocation CallSiteLoc) {
2455   assert((FDecl || Proto) && "Need a function declaration or prototype");
2456 
2457   // Check the attributes attached to the method/function itself.
2458   llvm::SmallBitVector NonNullArgs;
2459   if (FDecl) {
2460     // Handle the nonnull attribute on the function/method declaration itself.
2461     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2462       if (!NonNull->args_size()) {
2463         // Easy case: all pointer arguments are nonnull.
2464         for (const auto *Arg : Args)
2465           if (S.isValidPointerAttrType(Arg->getType()))
2466             CheckNonNullArgument(S, Arg, CallSiteLoc);
2467         return;
2468       }
2469 
2470       for (unsigned Val : NonNull->args()) {
2471         if (Val >= Args.size())
2472           continue;
2473         if (NonNullArgs.empty())
2474           NonNullArgs.resize(Args.size());
2475         NonNullArgs.set(Val);
2476       }
2477     }
2478   }
2479 
2480   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2481     // Handle the nonnull attribute on the parameters of the
2482     // function/method.
2483     ArrayRef<ParmVarDecl*> parms;
2484     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2485       parms = FD->parameters();
2486     else
2487       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2488 
2489     unsigned ParamIndex = 0;
2490     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2491          I != E; ++I, ++ParamIndex) {
2492       const ParmVarDecl *PVD = *I;
2493       if (PVD->hasAttr<NonNullAttr>() ||
2494           isNonNullType(S.Context, PVD->getType())) {
2495         if (NonNullArgs.empty())
2496           NonNullArgs.resize(Args.size());
2497 
2498         NonNullArgs.set(ParamIndex);
2499       }
2500     }
2501   } else {
2502     // If we have a non-function, non-method declaration but no
2503     // function prototype, try to dig out the function prototype.
2504     if (!Proto) {
2505       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2506         QualType type = VD->getType().getNonReferenceType();
2507         if (auto pointerType = type->getAs<PointerType>())
2508           type = pointerType->getPointeeType();
2509         else if (auto blockType = type->getAs<BlockPointerType>())
2510           type = blockType->getPointeeType();
2511         // FIXME: data member pointers?
2512 
2513         // Dig out the function prototype, if there is one.
2514         Proto = type->getAs<FunctionProtoType>();
2515       }
2516     }
2517 
2518     // Fill in non-null argument information from the nullability
2519     // information on the parameter types (if we have them).
2520     if (Proto) {
2521       unsigned Index = 0;
2522       for (auto paramType : Proto->getParamTypes()) {
2523         if (isNonNullType(S.Context, paramType)) {
2524           if (NonNullArgs.empty())
2525             NonNullArgs.resize(Args.size());
2526 
2527           NonNullArgs.set(Index);
2528         }
2529 
2530         ++Index;
2531       }
2532     }
2533   }
2534 
2535   // Check for non-null arguments.
2536   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2537        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2538     if (NonNullArgs[ArgIndex])
2539       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2540   }
2541 }
2542 
2543 /// Handles the checks for format strings, non-POD arguments to vararg
2544 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2545 /// attributes.
2546 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2547                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2548                      bool IsMemberFunction, SourceLocation Loc,
2549                      SourceRange Range, VariadicCallType CallType) {
2550   // FIXME: We should check as much as we can in the template definition.
2551   if (CurContext->isDependentContext())
2552     return;
2553 
2554   // Printf and scanf checking.
2555   llvm::SmallBitVector CheckedVarArgs;
2556   if (FDecl) {
2557     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2558       // Only create vector if there are format attributes.
2559       CheckedVarArgs.resize(Args.size());
2560 
2561       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2562                            CheckedVarArgs);
2563     }
2564   }
2565 
2566   // Refuse POD arguments that weren't caught by the format string
2567   // checks above.
2568   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2569   if (CallType != VariadicDoesNotApply &&
2570       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2571     unsigned NumParams = Proto ? Proto->getNumParams()
2572                        : FDecl && isa<FunctionDecl>(FDecl)
2573                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2574                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2575                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2576                        : 0;
2577 
2578     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2579       // Args[ArgIdx] can be null in malformed code.
2580       if (const Expr *Arg = Args[ArgIdx]) {
2581         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2582           checkVariadicArgument(Arg, CallType);
2583       }
2584     }
2585   }
2586 
2587   if (FDecl || Proto) {
2588     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2589 
2590     // Type safety checking.
2591     if (FDecl) {
2592       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2593         CheckArgumentWithTypeTag(I, Args.data());
2594     }
2595   }
2596 
2597   if (FD)
2598     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2599 }
2600 
2601 /// CheckConstructorCall - Check a constructor call for correctness and safety
2602 /// properties not enforced by the C type system.
2603 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2604                                 ArrayRef<const Expr *> Args,
2605                                 const FunctionProtoType *Proto,
2606                                 SourceLocation Loc) {
2607   VariadicCallType CallType =
2608     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2609   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2610             Loc, SourceRange(), CallType);
2611 }
2612 
2613 /// CheckFunctionCall - Check a direct function call for various correctness
2614 /// and safety properties not strictly enforced by the C type system.
2615 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2616                              const FunctionProtoType *Proto) {
2617   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2618                               isa<CXXMethodDecl>(FDecl);
2619   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2620                           IsMemberOperatorCall;
2621   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2622                                                   TheCall->getCallee());
2623   Expr** Args = TheCall->getArgs();
2624   unsigned NumArgs = TheCall->getNumArgs();
2625 
2626   Expr *ImplicitThis = nullptr;
2627   if (IsMemberOperatorCall) {
2628     // If this is a call to a member operator, hide the first argument
2629     // from checkCall.
2630     // FIXME: Our choice of AST representation here is less than ideal.
2631     ImplicitThis = Args[0];
2632     ++Args;
2633     --NumArgs;
2634   } else if (IsMemberFunction)
2635     ImplicitThis =
2636         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2637 
2638   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2639             IsMemberFunction, TheCall->getRParenLoc(),
2640             TheCall->getCallee()->getSourceRange(), CallType);
2641 
2642   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2643   // None of the checks below are needed for functions that don't have
2644   // simple names (e.g., C++ conversion functions).
2645   if (!FnInfo)
2646     return false;
2647 
2648   CheckAbsoluteValueFunction(TheCall, FDecl);
2649   CheckMaxUnsignedZero(TheCall, FDecl);
2650 
2651   if (getLangOpts().ObjC1)
2652     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2653 
2654   unsigned CMId = FDecl->getMemoryFunctionKind();
2655   if (CMId == 0)
2656     return false;
2657 
2658   // Handle memory setting and copying functions.
2659   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2660     CheckStrlcpycatArguments(TheCall, FnInfo);
2661   else if (CMId == Builtin::BIstrncat)
2662     CheckStrncatArguments(TheCall, FnInfo);
2663   else
2664     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2665 
2666   return false;
2667 }
2668 
2669 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2670                                ArrayRef<const Expr *> Args) {
2671   VariadicCallType CallType =
2672       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2673 
2674   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2675             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2676             CallType);
2677 
2678   return false;
2679 }
2680 
2681 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2682                             const FunctionProtoType *Proto) {
2683   QualType Ty;
2684   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2685     Ty = V->getType().getNonReferenceType();
2686   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2687     Ty = F->getType().getNonReferenceType();
2688   else
2689     return false;
2690 
2691   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2692       !Ty->isFunctionProtoType())
2693     return false;
2694 
2695   VariadicCallType CallType;
2696   if (!Proto || !Proto->isVariadic()) {
2697     CallType = VariadicDoesNotApply;
2698   } else if (Ty->isBlockPointerType()) {
2699     CallType = VariadicBlock;
2700   } else { // Ty->isFunctionPointerType()
2701     CallType = VariadicFunction;
2702   }
2703 
2704   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2705             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2706             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2707             TheCall->getCallee()->getSourceRange(), CallType);
2708 
2709   return false;
2710 }
2711 
2712 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2713 /// such as function pointers returned from functions.
2714 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2715   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2716                                                   TheCall->getCallee());
2717   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2718             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2719             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2720             TheCall->getCallee()->getSourceRange(), CallType);
2721 
2722   return false;
2723 }
2724 
2725 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2726   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2727     return false;
2728 
2729   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2730   switch (Op) {
2731   case AtomicExpr::AO__c11_atomic_init:
2732     llvm_unreachable("There is no ordering argument for an init");
2733 
2734   case AtomicExpr::AO__c11_atomic_load:
2735   case AtomicExpr::AO__atomic_load_n:
2736   case AtomicExpr::AO__atomic_load:
2737     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2738            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2739 
2740   case AtomicExpr::AO__c11_atomic_store:
2741   case AtomicExpr::AO__atomic_store:
2742   case AtomicExpr::AO__atomic_store_n:
2743     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2744            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2745            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2746 
2747   default:
2748     return true;
2749   }
2750 }
2751 
2752 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2753                                          AtomicExpr::AtomicOp Op) {
2754   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2755   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2756 
2757   // All these operations take one of the following forms:
2758   enum {
2759     // C    __c11_atomic_init(A *, C)
2760     Init,
2761     // C    __c11_atomic_load(A *, int)
2762     Load,
2763     // void __atomic_load(A *, CP, int)
2764     LoadCopy,
2765     // void __atomic_store(A *, CP, int)
2766     Copy,
2767     // C    __c11_atomic_add(A *, M, int)
2768     Arithmetic,
2769     // C    __atomic_exchange_n(A *, CP, int)
2770     Xchg,
2771     // void __atomic_exchange(A *, C *, CP, int)
2772     GNUXchg,
2773     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2774     C11CmpXchg,
2775     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2776     GNUCmpXchg
2777   } Form = Init;
2778   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2779   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2780   // where:
2781   //   C is an appropriate type,
2782   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2783   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2784   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2785   //   the int parameters are for orderings.
2786 
2787   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2788                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2789                         AtomicExpr::AO__atomic_load,
2790                 "need to update code for modified C11 atomics");
2791   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2792                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2793   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2794              Op == AtomicExpr::AO__atomic_store_n ||
2795              Op == AtomicExpr::AO__atomic_exchange_n ||
2796              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2797   bool IsAddSub = false;
2798 
2799   switch (Op) {
2800   case AtomicExpr::AO__c11_atomic_init:
2801     Form = Init;
2802     break;
2803 
2804   case AtomicExpr::AO__c11_atomic_load:
2805   case AtomicExpr::AO__atomic_load_n:
2806     Form = Load;
2807     break;
2808 
2809   case AtomicExpr::AO__atomic_load:
2810     Form = LoadCopy;
2811     break;
2812 
2813   case AtomicExpr::AO__c11_atomic_store:
2814   case AtomicExpr::AO__atomic_store:
2815   case AtomicExpr::AO__atomic_store_n:
2816     Form = Copy;
2817     break;
2818 
2819   case AtomicExpr::AO__c11_atomic_fetch_add:
2820   case AtomicExpr::AO__c11_atomic_fetch_sub:
2821   case AtomicExpr::AO__atomic_fetch_add:
2822   case AtomicExpr::AO__atomic_fetch_sub:
2823   case AtomicExpr::AO__atomic_add_fetch:
2824   case AtomicExpr::AO__atomic_sub_fetch:
2825     IsAddSub = true;
2826     // Fall through.
2827   case AtomicExpr::AO__c11_atomic_fetch_and:
2828   case AtomicExpr::AO__c11_atomic_fetch_or:
2829   case AtomicExpr::AO__c11_atomic_fetch_xor:
2830   case AtomicExpr::AO__atomic_fetch_and:
2831   case AtomicExpr::AO__atomic_fetch_or:
2832   case AtomicExpr::AO__atomic_fetch_xor:
2833   case AtomicExpr::AO__atomic_fetch_nand:
2834   case AtomicExpr::AO__atomic_and_fetch:
2835   case AtomicExpr::AO__atomic_or_fetch:
2836   case AtomicExpr::AO__atomic_xor_fetch:
2837   case AtomicExpr::AO__atomic_nand_fetch:
2838     Form = Arithmetic;
2839     break;
2840 
2841   case AtomicExpr::AO__c11_atomic_exchange:
2842   case AtomicExpr::AO__atomic_exchange_n:
2843     Form = Xchg;
2844     break;
2845 
2846   case AtomicExpr::AO__atomic_exchange:
2847     Form = GNUXchg;
2848     break;
2849 
2850   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2851   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2852     Form = C11CmpXchg;
2853     break;
2854 
2855   case AtomicExpr::AO__atomic_compare_exchange:
2856   case AtomicExpr::AO__atomic_compare_exchange_n:
2857     Form = GNUCmpXchg;
2858     break;
2859   }
2860 
2861   // Check we have the right number of arguments.
2862   if (TheCall->getNumArgs() < NumArgs[Form]) {
2863     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2864       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2865       << TheCall->getCallee()->getSourceRange();
2866     return ExprError();
2867   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2868     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2869          diag::err_typecheck_call_too_many_args)
2870       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2871       << TheCall->getCallee()->getSourceRange();
2872     return ExprError();
2873   }
2874 
2875   // Inspect the first argument of the atomic operation.
2876   Expr *Ptr = TheCall->getArg(0);
2877   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2878   if (ConvertedPtr.isInvalid())
2879     return ExprError();
2880 
2881   Ptr = ConvertedPtr.get();
2882   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2883   if (!pointerType) {
2884     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2885       << Ptr->getType() << Ptr->getSourceRange();
2886     return ExprError();
2887   }
2888 
2889   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2890   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2891   QualType ValType = AtomTy; // 'C'
2892   if (IsC11) {
2893     if (!AtomTy->isAtomicType()) {
2894       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2895         << Ptr->getType() << Ptr->getSourceRange();
2896       return ExprError();
2897     }
2898     if (AtomTy.isConstQualified()) {
2899       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2900         << Ptr->getType() << Ptr->getSourceRange();
2901       return ExprError();
2902     }
2903     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2904   } else if (Form != Load && Form != LoadCopy) {
2905     if (ValType.isConstQualified()) {
2906       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2907         << Ptr->getType() << Ptr->getSourceRange();
2908       return ExprError();
2909     }
2910   }
2911 
2912   // For an arithmetic operation, the implied arithmetic must be well-formed.
2913   if (Form == Arithmetic) {
2914     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2915     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2916       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2917         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2918       return ExprError();
2919     }
2920     if (!IsAddSub && !ValType->isIntegerType()) {
2921       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2922         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2923       return ExprError();
2924     }
2925     if (IsC11 && ValType->isPointerType() &&
2926         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2927                             diag::err_incomplete_type)) {
2928       return ExprError();
2929     }
2930   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2931     // For __atomic_*_n operations, the value type must be a scalar integral or
2932     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2933     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2934       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2935     return ExprError();
2936   }
2937 
2938   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2939       !AtomTy->isScalarType()) {
2940     // For GNU atomics, require a trivially-copyable type. This is not part of
2941     // the GNU atomics specification, but we enforce it for sanity.
2942     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2943       << Ptr->getType() << Ptr->getSourceRange();
2944     return ExprError();
2945   }
2946 
2947   switch (ValType.getObjCLifetime()) {
2948   case Qualifiers::OCL_None:
2949   case Qualifiers::OCL_ExplicitNone:
2950     // okay
2951     break;
2952 
2953   case Qualifiers::OCL_Weak:
2954   case Qualifiers::OCL_Strong:
2955   case Qualifiers::OCL_Autoreleasing:
2956     // FIXME: Can this happen? By this point, ValType should be known
2957     // to be trivially copyable.
2958     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2959       << ValType << Ptr->getSourceRange();
2960     return ExprError();
2961   }
2962 
2963   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2964   // volatile-ness of the pointee-type inject itself into the result or the
2965   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2966   ValType.removeLocalVolatile();
2967   ValType.removeLocalConst();
2968   QualType ResultType = ValType;
2969   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2970     ResultType = Context.VoidTy;
2971   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2972     ResultType = Context.BoolTy;
2973 
2974   // The type of a parameter passed 'by value'. In the GNU atomics, such
2975   // arguments are actually passed as pointers.
2976   QualType ByValType = ValType; // 'CP'
2977   if (!IsC11 && !IsN)
2978     ByValType = Ptr->getType();
2979 
2980   // The first argument --- the pointer --- has a fixed type; we
2981   // deduce the types of the rest of the arguments accordingly.  Walk
2982   // the remaining arguments, converting them to the deduced value type.
2983   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2984     QualType Ty;
2985     if (i < NumVals[Form] + 1) {
2986       switch (i) {
2987       case 1:
2988         // The second argument is the non-atomic operand. For arithmetic, this
2989         // is always passed by value, and for a compare_exchange it is always
2990         // passed by address. For the rest, GNU uses by-address and C11 uses
2991         // by-value.
2992         assert(Form != Load);
2993         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2994           Ty = ValType;
2995         else if (Form == Copy || Form == Xchg)
2996           Ty = ByValType;
2997         else if (Form == Arithmetic)
2998           Ty = Context.getPointerDiffType();
2999         else {
3000           Expr *ValArg = TheCall->getArg(i);
3001           // Treat this argument as _Nonnull as we want to show a warning if
3002           // NULL is passed into it.
3003           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3004           unsigned AS = 0;
3005           // Keep address space of non-atomic pointer type.
3006           if (const PointerType *PtrTy =
3007                   ValArg->getType()->getAs<PointerType>()) {
3008             AS = PtrTy->getPointeeType().getAddressSpace();
3009           }
3010           Ty = Context.getPointerType(
3011               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3012         }
3013         break;
3014       case 2:
3015         // The third argument to compare_exchange / GNU exchange is a
3016         // (pointer to a) desired value.
3017         Ty = ByValType;
3018         break;
3019       case 3:
3020         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3021         Ty = Context.BoolTy;
3022         break;
3023       }
3024     } else {
3025       // The order(s) are always converted to int.
3026       Ty = Context.IntTy;
3027     }
3028 
3029     InitializedEntity Entity =
3030         InitializedEntity::InitializeParameter(Context, Ty, false);
3031     ExprResult Arg = TheCall->getArg(i);
3032     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3033     if (Arg.isInvalid())
3034       return true;
3035     TheCall->setArg(i, Arg.get());
3036   }
3037 
3038   // Permute the arguments into a 'consistent' order.
3039   SmallVector<Expr*, 5> SubExprs;
3040   SubExprs.push_back(Ptr);
3041   switch (Form) {
3042   case Init:
3043     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3044     SubExprs.push_back(TheCall->getArg(1)); // Val1
3045     break;
3046   case Load:
3047     SubExprs.push_back(TheCall->getArg(1)); // Order
3048     break;
3049   case LoadCopy:
3050   case Copy:
3051   case Arithmetic:
3052   case Xchg:
3053     SubExprs.push_back(TheCall->getArg(2)); // Order
3054     SubExprs.push_back(TheCall->getArg(1)); // Val1
3055     break;
3056   case GNUXchg:
3057     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3058     SubExprs.push_back(TheCall->getArg(3)); // Order
3059     SubExprs.push_back(TheCall->getArg(1)); // Val1
3060     SubExprs.push_back(TheCall->getArg(2)); // Val2
3061     break;
3062   case C11CmpXchg:
3063     SubExprs.push_back(TheCall->getArg(3)); // Order
3064     SubExprs.push_back(TheCall->getArg(1)); // Val1
3065     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3066     SubExprs.push_back(TheCall->getArg(2)); // Val2
3067     break;
3068   case GNUCmpXchg:
3069     SubExprs.push_back(TheCall->getArg(4)); // Order
3070     SubExprs.push_back(TheCall->getArg(1)); // Val1
3071     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3072     SubExprs.push_back(TheCall->getArg(2)); // Val2
3073     SubExprs.push_back(TheCall->getArg(3)); // Weak
3074     break;
3075   }
3076 
3077   if (SubExprs.size() >= 2 && Form != Init) {
3078     llvm::APSInt Result(32);
3079     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3080         !isValidOrderingForOp(Result.getSExtValue(), Op))
3081       Diag(SubExprs[1]->getLocStart(),
3082            diag::warn_atomic_op_has_invalid_memory_order)
3083           << SubExprs[1]->getSourceRange();
3084   }
3085 
3086   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3087                                             SubExprs, ResultType, Op,
3088                                             TheCall->getRParenLoc());
3089 
3090   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3091        (Op == AtomicExpr::AO__c11_atomic_store)) &&
3092       Context.AtomicUsesUnsupportedLibcall(AE))
3093     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3094     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
3095 
3096   return AE;
3097 }
3098 
3099 /// checkBuiltinArgument - Given a call to a builtin function, perform
3100 /// normal type-checking on the given argument, updating the call in
3101 /// place.  This is useful when a builtin function requires custom
3102 /// type-checking for some of its arguments but not necessarily all of
3103 /// them.
3104 ///
3105 /// Returns true on error.
3106 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3107   FunctionDecl *Fn = E->getDirectCallee();
3108   assert(Fn && "builtin call without direct callee!");
3109 
3110   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3111   InitializedEntity Entity =
3112     InitializedEntity::InitializeParameter(S.Context, Param);
3113 
3114   ExprResult Arg = E->getArg(0);
3115   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3116   if (Arg.isInvalid())
3117     return true;
3118 
3119   E->setArg(ArgIndex, Arg.get());
3120   return false;
3121 }
3122 
3123 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3124 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3125 /// type of its first argument.  The main ActOnCallExpr routines have already
3126 /// promoted the types of arguments because all of these calls are prototyped as
3127 /// void(...).
3128 ///
3129 /// This function goes through and does final semantic checking for these
3130 /// builtins,
3131 ExprResult
3132 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3133   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3134   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3135   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3136 
3137   // Ensure that we have at least one argument to do type inference from.
3138   if (TheCall->getNumArgs() < 1) {
3139     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3140       << 0 << 1 << TheCall->getNumArgs()
3141       << TheCall->getCallee()->getSourceRange();
3142     return ExprError();
3143   }
3144 
3145   // Inspect the first argument of the atomic builtin.  This should always be
3146   // a pointer type, whose element is an integral scalar or pointer type.
3147   // Because it is a pointer type, we don't have to worry about any implicit
3148   // casts here.
3149   // FIXME: We don't allow floating point scalars as input.
3150   Expr *FirstArg = TheCall->getArg(0);
3151   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3152   if (FirstArgResult.isInvalid())
3153     return ExprError();
3154   FirstArg = FirstArgResult.get();
3155   TheCall->setArg(0, FirstArg);
3156 
3157   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3158   if (!pointerType) {
3159     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3160       << FirstArg->getType() << FirstArg->getSourceRange();
3161     return ExprError();
3162   }
3163 
3164   QualType ValType = pointerType->getPointeeType();
3165   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3166       !ValType->isBlockPointerType()) {
3167     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3168       << FirstArg->getType() << FirstArg->getSourceRange();
3169     return ExprError();
3170   }
3171 
3172   switch (ValType.getObjCLifetime()) {
3173   case Qualifiers::OCL_None:
3174   case Qualifiers::OCL_ExplicitNone:
3175     // okay
3176     break;
3177 
3178   case Qualifiers::OCL_Weak:
3179   case Qualifiers::OCL_Strong:
3180   case Qualifiers::OCL_Autoreleasing:
3181     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3182       << ValType << FirstArg->getSourceRange();
3183     return ExprError();
3184   }
3185 
3186   // Strip any qualifiers off ValType.
3187   ValType = ValType.getUnqualifiedType();
3188 
3189   // The majority of builtins return a value, but a few have special return
3190   // types, so allow them to override appropriately below.
3191   QualType ResultType = ValType;
3192 
3193   // We need to figure out which concrete builtin this maps onto.  For example,
3194   // __sync_fetch_and_add with a 2 byte object turns into
3195   // __sync_fetch_and_add_2.
3196 #define BUILTIN_ROW(x) \
3197   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3198     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3199 
3200   static const unsigned BuiltinIndices[][5] = {
3201     BUILTIN_ROW(__sync_fetch_and_add),
3202     BUILTIN_ROW(__sync_fetch_and_sub),
3203     BUILTIN_ROW(__sync_fetch_and_or),
3204     BUILTIN_ROW(__sync_fetch_and_and),
3205     BUILTIN_ROW(__sync_fetch_and_xor),
3206     BUILTIN_ROW(__sync_fetch_and_nand),
3207 
3208     BUILTIN_ROW(__sync_add_and_fetch),
3209     BUILTIN_ROW(__sync_sub_and_fetch),
3210     BUILTIN_ROW(__sync_and_and_fetch),
3211     BUILTIN_ROW(__sync_or_and_fetch),
3212     BUILTIN_ROW(__sync_xor_and_fetch),
3213     BUILTIN_ROW(__sync_nand_and_fetch),
3214 
3215     BUILTIN_ROW(__sync_val_compare_and_swap),
3216     BUILTIN_ROW(__sync_bool_compare_and_swap),
3217     BUILTIN_ROW(__sync_lock_test_and_set),
3218     BUILTIN_ROW(__sync_lock_release),
3219     BUILTIN_ROW(__sync_swap)
3220   };
3221 #undef BUILTIN_ROW
3222 
3223   // Determine the index of the size.
3224   unsigned SizeIndex;
3225   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3226   case 1: SizeIndex = 0; break;
3227   case 2: SizeIndex = 1; break;
3228   case 4: SizeIndex = 2; break;
3229   case 8: SizeIndex = 3; break;
3230   case 16: SizeIndex = 4; break;
3231   default:
3232     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3233       << FirstArg->getType() << FirstArg->getSourceRange();
3234     return ExprError();
3235   }
3236 
3237   // Each of these builtins has one pointer argument, followed by some number of
3238   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3239   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3240   // as the number of fixed args.
3241   unsigned BuiltinID = FDecl->getBuiltinID();
3242   unsigned BuiltinIndex, NumFixed = 1;
3243   bool WarnAboutSemanticsChange = false;
3244   switch (BuiltinID) {
3245   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3246   case Builtin::BI__sync_fetch_and_add:
3247   case Builtin::BI__sync_fetch_and_add_1:
3248   case Builtin::BI__sync_fetch_and_add_2:
3249   case Builtin::BI__sync_fetch_and_add_4:
3250   case Builtin::BI__sync_fetch_and_add_8:
3251   case Builtin::BI__sync_fetch_and_add_16:
3252     BuiltinIndex = 0;
3253     break;
3254 
3255   case Builtin::BI__sync_fetch_and_sub:
3256   case Builtin::BI__sync_fetch_and_sub_1:
3257   case Builtin::BI__sync_fetch_and_sub_2:
3258   case Builtin::BI__sync_fetch_and_sub_4:
3259   case Builtin::BI__sync_fetch_and_sub_8:
3260   case Builtin::BI__sync_fetch_and_sub_16:
3261     BuiltinIndex = 1;
3262     break;
3263 
3264   case Builtin::BI__sync_fetch_and_or:
3265   case Builtin::BI__sync_fetch_and_or_1:
3266   case Builtin::BI__sync_fetch_and_or_2:
3267   case Builtin::BI__sync_fetch_and_or_4:
3268   case Builtin::BI__sync_fetch_and_or_8:
3269   case Builtin::BI__sync_fetch_and_or_16:
3270     BuiltinIndex = 2;
3271     break;
3272 
3273   case Builtin::BI__sync_fetch_and_and:
3274   case Builtin::BI__sync_fetch_and_and_1:
3275   case Builtin::BI__sync_fetch_and_and_2:
3276   case Builtin::BI__sync_fetch_and_and_4:
3277   case Builtin::BI__sync_fetch_and_and_8:
3278   case Builtin::BI__sync_fetch_and_and_16:
3279     BuiltinIndex = 3;
3280     break;
3281 
3282   case Builtin::BI__sync_fetch_and_xor:
3283   case Builtin::BI__sync_fetch_and_xor_1:
3284   case Builtin::BI__sync_fetch_and_xor_2:
3285   case Builtin::BI__sync_fetch_and_xor_4:
3286   case Builtin::BI__sync_fetch_and_xor_8:
3287   case Builtin::BI__sync_fetch_and_xor_16:
3288     BuiltinIndex = 4;
3289     break;
3290 
3291   case Builtin::BI__sync_fetch_and_nand:
3292   case Builtin::BI__sync_fetch_and_nand_1:
3293   case Builtin::BI__sync_fetch_and_nand_2:
3294   case Builtin::BI__sync_fetch_and_nand_4:
3295   case Builtin::BI__sync_fetch_and_nand_8:
3296   case Builtin::BI__sync_fetch_and_nand_16:
3297     BuiltinIndex = 5;
3298     WarnAboutSemanticsChange = true;
3299     break;
3300 
3301   case Builtin::BI__sync_add_and_fetch:
3302   case Builtin::BI__sync_add_and_fetch_1:
3303   case Builtin::BI__sync_add_and_fetch_2:
3304   case Builtin::BI__sync_add_and_fetch_4:
3305   case Builtin::BI__sync_add_and_fetch_8:
3306   case Builtin::BI__sync_add_and_fetch_16:
3307     BuiltinIndex = 6;
3308     break;
3309 
3310   case Builtin::BI__sync_sub_and_fetch:
3311   case Builtin::BI__sync_sub_and_fetch_1:
3312   case Builtin::BI__sync_sub_and_fetch_2:
3313   case Builtin::BI__sync_sub_and_fetch_4:
3314   case Builtin::BI__sync_sub_and_fetch_8:
3315   case Builtin::BI__sync_sub_and_fetch_16:
3316     BuiltinIndex = 7;
3317     break;
3318 
3319   case Builtin::BI__sync_and_and_fetch:
3320   case Builtin::BI__sync_and_and_fetch_1:
3321   case Builtin::BI__sync_and_and_fetch_2:
3322   case Builtin::BI__sync_and_and_fetch_4:
3323   case Builtin::BI__sync_and_and_fetch_8:
3324   case Builtin::BI__sync_and_and_fetch_16:
3325     BuiltinIndex = 8;
3326     break;
3327 
3328   case Builtin::BI__sync_or_and_fetch:
3329   case Builtin::BI__sync_or_and_fetch_1:
3330   case Builtin::BI__sync_or_and_fetch_2:
3331   case Builtin::BI__sync_or_and_fetch_4:
3332   case Builtin::BI__sync_or_and_fetch_8:
3333   case Builtin::BI__sync_or_and_fetch_16:
3334     BuiltinIndex = 9;
3335     break;
3336 
3337   case Builtin::BI__sync_xor_and_fetch:
3338   case Builtin::BI__sync_xor_and_fetch_1:
3339   case Builtin::BI__sync_xor_and_fetch_2:
3340   case Builtin::BI__sync_xor_and_fetch_4:
3341   case Builtin::BI__sync_xor_and_fetch_8:
3342   case Builtin::BI__sync_xor_and_fetch_16:
3343     BuiltinIndex = 10;
3344     break;
3345 
3346   case Builtin::BI__sync_nand_and_fetch:
3347   case Builtin::BI__sync_nand_and_fetch_1:
3348   case Builtin::BI__sync_nand_and_fetch_2:
3349   case Builtin::BI__sync_nand_and_fetch_4:
3350   case Builtin::BI__sync_nand_and_fetch_8:
3351   case Builtin::BI__sync_nand_and_fetch_16:
3352     BuiltinIndex = 11;
3353     WarnAboutSemanticsChange = true;
3354     break;
3355 
3356   case Builtin::BI__sync_val_compare_and_swap:
3357   case Builtin::BI__sync_val_compare_and_swap_1:
3358   case Builtin::BI__sync_val_compare_and_swap_2:
3359   case Builtin::BI__sync_val_compare_and_swap_4:
3360   case Builtin::BI__sync_val_compare_and_swap_8:
3361   case Builtin::BI__sync_val_compare_and_swap_16:
3362     BuiltinIndex = 12;
3363     NumFixed = 2;
3364     break;
3365 
3366   case Builtin::BI__sync_bool_compare_and_swap:
3367   case Builtin::BI__sync_bool_compare_and_swap_1:
3368   case Builtin::BI__sync_bool_compare_and_swap_2:
3369   case Builtin::BI__sync_bool_compare_and_swap_4:
3370   case Builtin::BI__sync_bool_compare_and_swap_8:
3371   case Builtin::BI__sync_bool_compare_and_swap_16:
3372     BuiltinIndex = 13;
3373     NumFixed = 2;
3374     ResultType = Context.BoolTy;
3375     break;
3376 
3377   case Builtin::BI__sync_lock_test_and_set:
3378   case Builtin::BI__sync_lock_test_and_set_1:
3379   case Builtin::BI__sync_lock_test_and_set_2:
3380   case Builtin::BI__sync_lock_test_and_set_4:
3381   case Builtin::BI__sync_lock_test_and_set_8:
3382   case Builtin::BI__sync_lock_test_and_set_16:
3383     BuiltinIndex = 14;
3384     break;
3385 
3386   case Builtin::BI__sync_lock_release:
3387   case Builtin::BI__sync_lock_release_1:
3388   case Builtin::BI__sync_lock_release_2:
3389   case Builtin::BI__sync_lock_release_4:
3390   case Builtin::BI__sync_lock_release_8:
3391   case Builtin::BI__sync_lock_release_16:
3392     BuiltinIndex = 15;
3393     NumFixed = 0;
3394     ResultType = Context.VoidTy;
3395     break;
3396 
3397   case Builtin::BI__sync_swap:
3398   case Builtin::BI__sync_swap_1:
3399   case Builtin::BI__sync_swap_2:
3400   case Builtin::BI__sync_swap_4:
3401   case Builtin::BI__sync_swap_8:
3402   case Builtin::BI__sync_swap_16:
3403     BuiltinIndex = 16;
3404     break;
3405   }
3406 
3407   // Now that we know how many fixed arguments we expect, first check that we
3408   // have at least that many.
3409   if (TheCall->getNumArgs() < 1+NumFixed) {
3410     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3411       << 0 << 1+NumFixed << TheCall->getNumArgs()
3412       << TheCall->getCallee()->getSourceRange();
3413     return ExprError();
3414   }
3415 
3416   if (WarnAboutSemanticsChange) {
3417     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3418       << TheCall->getCallee()->getSourceRange();
3419   }
3420 
3421   // Get the decl for the concrete builtin from this, we can tell what the
3422   // concrete integer type we should convert to is.
3423   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3424   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3425   FunctionDecl *NewBuiltinDecl;
3426   if (NewBuiltinID == BuiltinID)
3427     NewBuiltinDecl = FDecl;
3428   else {
3429     // Perform builtin lookup to avoid redeclaring it.
3430     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3431     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3432     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3433     assert(Res.getFoundDecl());
3434     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3435     if (!NewBuiltinDecl)
3436       return ExprError();
3437   }
3438 
3439   // The first argument --- the pointer --- has a fixed type; we
3440   // deduce the types of the rest of the arguments accordingly.  Walk
3441   // the remaining arguments, converting them to the deduced value type.
3442   for (unsigned i = 0; i != NumFixed; ++i) {
3443     ExprResult Arg = TheCall->getArg(i+1);
3444 
3445     // GCC does an implicit conversion to the pointer or integer ValType.  This
3446     // can fail in some cases (1i -> int**), check for this error case now.
3447     // Initialize the argument.
3448     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3449                                                    ValType, /*consume*/ false);
3450     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3451     if (Arg.isInvalid())
3452       return ExprError();
3453 
3454     // Okay, we have something that *can* be converted to the right type.  Check
3455     // to see if there is a potentially weird extension going on here.  This can
3456     // happen when you do an atomic operation on something like an char* and
3457     // pass in 42.  The 42 gets converted to char.  This is even more strange
3458     // for things like 45.123 -> char, etc.
3459     // FIXME: Do this check.
3460     TheCall->setArg(i+1, Arg.get());
3461   }
3462 
3463   ASTContext& Context = this->getASTContext();
3464 
3465   // Create a new DeclRefExpr to refer to the new decl.
3466   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3467       Context,
3468       DRE->getQualifierLoc(),
3469       SourceLocation(),
3470       NewBuiltinDecl,
3471       /*enclosing*/ false,
3472       DRE->getLocation(),
3473       Context.BuiltinFnTy,
3474       DRE->getValueKind());
3475 
3476   // Set the callee in the CallExpr.
3477   // FIXME: This loses syntactic information.
3478   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3479   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3480                                               CK_BuiltinFnToFnPtr);
3481   TheCall->setCallee(PromotedCall.get());
3482 
3483   // Change the result type of the call to match the original value type. This
3484   // is arbitrary, but the codegen for these builtins ins design to handle it
3485   // gracefully.
3486   TheCall->setType(ResultType);
3487 
3488   return TheCallResult;
3489 }
3490 
3491 /// SemaBuiltinNontemporalOverloaded - We have a call to
3492 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3493 /// overloaded function based on the pointer type of its last argument.
3494 ///
3495 /// This function goes through and does final semantic checking for these
3496 /// builtins.
3497 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3498   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3499   DeclRefExpr *DRE =
3500       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3501   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3502   unsigned BuiltinID = FDecl->getBuiltinID();
3503   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3504           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3505          "Unexpected nontemporal load/store builtin!");
3506   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3507   unsigned numArgs = isStore ? 2 : 1;
3508 
3509   // Ensure that we have the proper number of arguments.
3510   if (checkArgCount(*this, TheCall, numArgs))
3511     return ExprError();
3512 
3513   // Inspect the last argument of the nontemporal builtin.  This should always
3514   // be a pointer type, from which we imply the type of the memory access.
3515   // Because it is a pointer type, we don't have to worry about any implicit
3516   // casts here.
3517   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3518   ExprResult PointerArgResult =
3519       DefaultFunctionArrayLvalueConversion(PointerArg);
3520 
3521   if (PointerArgResult.isInvalid())
3522     return ExprError();
3523   PointerArg = PointerArgResult.get();
3524   TheCall->setArg(numArgs - 1, PointerArg);
3525 
3526   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3527   if (!pointerType) {
3528     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3529         << PointerArg->getType() << PointerArg->getSourceRange();
3530     return ExprError();
3531   }
3532 
3533   QualType ValType = pointerType->getPointeeType();
3534 
3535   // Strip any qualifiers off ValType.
3536   ValType = ValType.getUnqualifiedType();
3537   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3538       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3539       !ValType->isVectorType()) {
3540     Diag(DRE->getLocStart(),
3541          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3542         << PointerArg->getType() << PointerArg->getSourceRange();
3543     return ExprError();
3544   }
3545 
3546   if (!isStore) {
3547     TheCall->setType(ValType);
3548     return TheCallResult;
3549   }
3550 
3551   ExprResult ValArg = TheCall->getArg(0);
3552   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3553       Context, ValType, /*consume*/ false);
3554   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3555   if (ValArg.isInvalid())
3556     return ExprError();
3557 
3558   TheCall->setArg(0, ValArg.get());
3559   TheCall->setType(Context.VoidTy);
3560   return TheCallResult;
3561 }
3562 
3563 /// CheckObjCString - Checks that the argument to the builtin
3564 /// CFString constructor is correct
3565 /// Note: It might also make sense to do the UTF-16 conversion here (would
3566 /// simplify the backend).
3567 bool Sema::CheckObjCString(Expr *Arg) {
3568   Arg = Arg->IgnoreParenCasts();
3569   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3570 
3571   if (!Literal || !Literal->isAscii()) {
3572     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3573       << Arg->getSourceRange();
3574     return true;
3575   }
3576 
3577   if (Literal->containsNonAsciiOrNull()) {
3578     StringRef String = Literal->getString();
3579     unsigned NumBytes = String.size();
3580     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3581     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3582     llvm::UTF16 *ToPtr = &ToBuf[0];
3583 
3584     llvm::ConversionResult Result =
3585         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3586                                  ToPtr + NumBytes, llvm::strictConversion);
3587     // Check for conversion failure.
3588     if (Result != llvm::conversionOK)
3589       Diag(Arg->getLocStart(),
3590            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3591   }
3592   return false;
3593 }
3594 
3595 /// CheckObjCString - Checks that the format string argument to the os_log()
3596 /// and os_trace() functions is correct, and converts it to const char *.
3597 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3598   Arg = Arg->IgnoreParenCasts();
3599   auto *Literal = dyn_cast<StringLiteral>(Arg);
3600   if (!Literal) {
3601     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3602       Literal = ObjcLiteral->getString();
3603     }
3604   }
3605 
3606   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3607     return ExprError(
3608         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3609         << Arg->getSourceRange());
3610   }
3611 
3612   ExprResult Result(Literal);
3613   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3614   InitializedEntity Entity =
3615       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3616   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3617   return Result;
3618 }
3619 
3620 /// Check that the user is calling the appropriate va_start builtin for the
3621 /// target and calling convention.
3622 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3623   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3624   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3625   bool IsWindows = TT.isOSWindows();
3626   bool IsMSVAStart = BuiltinID == X86::BI__builtin_ms_va_start;
3627   if (IsX64) {
3628     clang::CallingConv CC = CC_C;
3629     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3630       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3631     if (IsMSVAStart) {
3632       // Don't allow this in System V ABI functions.
3633       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_X86_64Win64))
3634         return S.Diag(Fn->getLocStart(),
3635                       diag::err_ms_va_start_used_in_sysv_function);
3636     } else {
3637       // On x86-64 Unix, don't allow this in Win64 ABI functions.
3638       // On x64 Windows, don't allow this in System V ABI functions.
3639       // (Yes, that means there's no corresponding way to support variadic
3640       // System V ABI functions on Windows.)
3641       if ((IsWindows && CC == CC_X86_64SysV) ||
3642           (!IsWindows && CC == CC_X86_64Win64))
3643         return S.Diag(Fn->getLocStart(),
3644                       diag::err_va_start_used_in_wrong_abi_function)
3645                << !IsWindows;
3646     }
3647     return false;
3648   }
3649 
3650   if (IsMSVAStart)
3651     return S.Diag(Fn->getLocStart(), diag::err_x86_builtin_64_only);
3652   return false;
3653 }
3654 
3655 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3656                                              ParmVarDecl **LastParam = nullptr) {
3657   // Determine whether the current function, block, or obj-c method is variadic
3658   // and get its parameter list.
3659   bool IsVariadic = false;
3660   ArrayRef<ParmVarDecl *> Params;
3661   DeclContext *Caller = S.CurContext;
3662   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3663     IsVariadic = Block->isVariadic();
3664     Params = Block->parameters();
3665   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3666     IsVariadic = FD->isVariadic();
3667     Params = FD->parameters();
3668   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3669     IsVariadic = MD->isVariadic();
3670     // FIXME: This isn't correct for methods (results in bogus warning).
3671     Params = MD->parameters();
3672   } else if (isa<CapturedDecl>(Caller)) {
3673     // We don't support va_start in a CapturedDecl.
3674     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3675     return true;
3676   } else {
3677     // This must be some other declcontext that parses exprs.
3678     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3679     return true;
3680   }
3681 
3682   if (!IsVariadic) {
3683     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3684     return true;
3685   }
3686 
3687   if (LastParam)
3688     *LastParam = Params.empty() ? nullptr : Params.back();
3689 
3690   return false;
3691 }
3692 
3693 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3694 /// for validity.  Emit an error and return true on failure; return false
3695 /// on success.
3696 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3697   Expr *Fn = TheCall->getCallee();
3698 
3699   if (checkVAStartABI(*this, BuiltinID, Fn))
3700     return true;
3701 
3702   if (TheCall->getNumArgs() > 2) {
3703     Diag(TheCall->getArg(2)->getLocStart(),
3704          diag::err_typecheck_call_too_many_args)
3705       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3706       << Fn->getSourceRange()
3707       << SourceRange(TheCall->getArg(2)->getLocStart(),
3708                      (*(TheCall->arg_end()-1))->getLocEnd());
3709     return true;
3710   }
3711 
3712   if (TheCall->getNumArgs() < 2) {
3713     return Diag(TheCall->getLocEnd(),
3714       diag::err_typecheck_call_too_few_args_at_least)
3715       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3716   }
3717 
3718   // Type-check the first argument normally.
3719   if (checkBuiltinArgument(*this, TheCall, 0))
3720     return true;
3721 
3722   // Check that the current function is variadic, and get its last parameter.
3723   ParmVarDecl *LastParam;
3724   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3725     return true;
3726 
3727   // Verify that the second argument to the builtin is the last argument of the
3728   // current function or method.
3729   bool SecondArgIsLastNamedArgument = false;
3730   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3731 
3732   // These are valid if SecondArgIsLastNamedArgument is false after the next
3733   // block.
3734   QualType Type;
3735   SourceLocation ParamLoc;
3736   bool IsCRegister = false;
3737 
3738   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3739     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3740       SecondArgIsLastNamedArgument = PV == LastParam;
3741 
3742       Type = PV->getType();
3743       ParamLoc = PV->getLocation();
3744       IsCRegister =
3745           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3746     }
3747   }
3748 
3749   if (!SecondArgIsLastNamedArgument)
3750     Diag(TheCall->getArg(1)->getLocStart(),
3751          diag::warn_second_arg_of_va_start_not_last_named_param);
3752   else if (IsCRegister || Type->isReferenceType() ||
3753            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3754              // Promotable integers are UB, but enumerations need a bit of
3755              // extra checking to see what their promotable type actually is.
3756              if (!Type->isPromotableIntegerType())
3757                return false;
3758              if (!Type->isEnumeralType())
3759                return true;
3760              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3761              return !(ED &&
3762                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3763            }()) {
3764     unsigned Reason = 0;
3765     if (Type->isReferenceType())  Reason = 1;
3766     else if (IsCRegister)         Reason = 2;
3767     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3768     Diag(ParamLoc, diag::note_parameter_type) << Type;
3769   }
3770 
3771   TheCall->setType(Context.VoidTy);
3772   return false;
3773 }
3774 
3775 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3776   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3777   //                 const char *named_addr);
3778 
3779   Expr *Func = Call->getCallee();
3780 
3781   if (Call->getNumArgs() < 3)
3782     return Diag(Call->getLocEnd(),
3783                 diag::err_typecheck_call_too_few_args_at_least)
3784            << 0 /*function call*/ << 3 << Call->getNumArgs();
3785 
3786   // Type-check the first argument normally.
3787   if (checkBuiltinArgument(*this, Call, 0))
3788     return true;
3789 
3790   // Check that the current function is variadic.
3791   if (checkVAStartIsInVariadicFunction(*this, Func))
3792     return true;
3793 
3794   const struct {
3795     unsigned ArgNo;
3796     QualType Type;
3797   } ArgumentTypes[] = {
3798     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3799     { 2, Context.getSizeType() },
3800   };
3801 
3802   for (const auto &AT : ArgumentTypes) {
3803     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3804     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3805       continue;
3806     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3807       << Arg->getType() << AT.Type << 1 /* different class */
3808       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3809       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3810   }
3811 
3812   return false;
3813 }
3814 
3815 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3816 /// friends.  This is declared to take (...), so we have to check everything.
3817 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3818   if (TheCall->getNumArgs() < 2)
3819     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3820       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3821   if (TheCall->getNumArgs() > 2)
3822     return Diag(TheCall->getArg(2)->getLocStart(),
3823                 diag::err_typecheck_call_too_many_args)
3824       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3825       << SourceRange(TheCall->getArg(2)->getLocStart(),
3826                      (*(TheCall->arg_end()-1))->getLocEnd());
3827 
3828   ExprResult OrigArg0 = TheCall->getArg(0);
3829   ExprResult OrigArg1 = TheCall->getArg(1);
3830 
3831   // Do standard promotions between the two arguments, returning their common
3832   // type.
3833   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3834   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3835     return true;
3836 
3837   // Make sure any conversions are pushed back into the call; this is
3838   // type safe since unordered compare builtins are declared as "_Bool
3839   // foo(...)".
3840   TheCall->setArg(0, OrigArg0.get());
3841   TheCall->setArg(1, OrigArg1.get());
3842 
3843   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3844     return false;
3845 
3846   // If the common type isn't a real floating type, then the arguments were
3847   // invalid for this operation.
3848   if (Res.isNull() || !Res->isRealFloatingType())
3849     return Diag(OrigArg0.get()->getLocStart(),
3850                 diag::err_typecheck_call_invalid_ordered_compare)
3851       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3852       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3853 
3854   return false;
3855 }
3856 
3857 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3858 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3859 /// to check everything. We expect the last argument to be a floating point
3860 /// value.
3861 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3862   if (TheCall->getNumArgs() < NumArgs)
3863     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3864       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3865   if (TheCall->getNumArgs() > NumArgs)
3866     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3867                 diag::err_typecheck_call_too_many_args)
3868       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3869       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3870                      (*(TheCall->arg_end()-1))->getLocEnd());
3871 
3872   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3873 
3874   if (OrigArg->isTypeDependent())
3875     return false;
3876 
3877   // This operation requires a non-_Complex floating-point number.
3878   if (!OrigArg->getType()->isRealFloatingType())
3879     return Diag(OrigArg->getLocStart(),
3880                 diag::err_typecheck_call_invalid_unary_fp)
3881       << OrigArg->getType() << OrigArg->getSourceRange();
3882 
3883   // If this is an implicit conversion from float -> float or double, remove it.
3884   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3885     // Only remove standard FloatCasts, leaving other casts inplace
3886     if (Cast->getCastKind() == CK_FloatingCast) {
3887       Expr *CastArg = Cast->getSubExpr();
3888       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3889           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3890                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3891                "promotion from float to either float or double is the only expected cast here");
3892         Cast->setSubExpr(nullptr);
3893         TheCall->setArg(NumArgs-1, CastArg);
3894       }
3895     }
3896   }
3897 
3898   return false;
3899 }
3900 
3901 // Customized Sema Checking for VSX builtins that have the following signature:
3902 // vector [...] builtinName(vector [...], vector [...], const int);
3903 // Which takes the same type of vectors (any legal vector type) for the first
3904 // two arguments and takes compile time constant for the third argument.
3905 // Example builtins are :
3906 // vector double vec_xxpermdi(vector double, vector double, int);
3907 // vector short vec_xxsldwi(vector short, vector short, int);
3908 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
3909   unsigned ExpectedNumArgs = 3;
3910   if (TheCall->getNumArgs() < ExpectedNumArgs)
3911     return Diag(TheCall->getLocEnd(),
3912                 diag::err_typecheck_call_too_few_args_at_least)
3913            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
3914            << TheCall->getSourceRange();
3915 
3916   if (TheCall->getNumArgs() > ExpectedNumArgs)
3917     return Diag(TheCall->getLocEnd(),
3918                 diag::err_typecheck_call_too_many_args_at_most)
3919            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3920            << TheCall->getSourceRange();
3921 
3922   // Check the third argument is a compile time constant
3923   llvm::APSInt Value;
3924   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
3925     return Diag(TheCall->getLocStart(),
3926                 diag::err_vsx_builtin_nonconstant_argument)
3927            << 3 /* argument index */ << TheCall->getDirectCallee()
3928            << SourceRange(TheCall->getArg(2)->getLocStart(),
3929                           TheCall->getArg(2)->getLocEnd());
3930 
3931   QualType Arg1Ty = TheCall->getArg(0)->getType();
3932   QualType Arg2Ty = TheCall->getArg(1)->getType();
3933 
3934   // Check the type of argument 1 and argument 2 are vectors.
3935   SourceLocation BuiltinLoc = TheCall->getLocStart();
3936   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
3937       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
3938     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
3939            << TheCall->getDirectCallee()
3940            << SourceRange(TheCall->getArg(0)->getLocStart(),
3941                           TheCall->getArg(1)->getLocEnd());
3942   }
3943 
3944   // Check the first two arguments are the same type.
3945   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
3946     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
3947            << TheCall->getDirectCallee()
3948            << SourceRange(TheCall->getArg(0)->getLocStart(),
3949                           TheCall->getArg(1)->getLocEnd());
3950   }
3951 
3952   // When default clang type checking is turned off and the customized type
3953   // checking is used, the returning type of the function must be explicitly
3954   // set. Otherwise it is _Bool by default.
3955   TheCall->setType(Arg1Ty);
3956 
3957   return false;
3958 }
3959 
3960 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3961 // This is declared to take (...), so we have to check everything.
3962 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3963   if (TheCall->getNumArgs() < 2)
3964     return ExprError(Diag(TheCall->getLocEnd(),
3965                           diag::err_typecheck_call_too_few_args_at_least)
3966                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3967                      << TheCall->getSourceRange());
3968 
3969   // Determine which of the following types of shufflevector we're checking:
3970   // 1) unary, vector mask: (lhs, mask)
3971   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3972   QualType resType = TheCall->getArg(0)->getType();
3973   unsigned numElements = 0;
3974 
3975   if (!TheCall->getArg(0)->isTypeDependent() &&
3976       !TheCall->getArg(1)->isTypeDependent()) {
3977     QualType LHSType = TheCall->getArg(0)->getType();
3978     QualType RHSType = TheCall->getArg(1)->getType();
3979 
3980     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3981       return ExprError(Diag(TheCall->getLocStart(),
3982                             diag::err_vec_builtin_non_vector)
3983                        << TheCall->getDirectCallee()
3984                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3985                                       TheCall->getArg(1)->getLocEnd()));
3986 
3987     numElements = LHSType->getAs<VectorType>()->getNumElements();
3988     unsigned numResElements = TheCall->getNumArgs() - 2;
3989 
3990     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3991     // with mask.  If so, verify that RHS is an integer vector type with the
3992     // same number of elts as lhs.
3993     if (TheCall->getNumArgs() == 2) {
3994       if (!RHSType->hasIntegerRepresentation() ||
3995           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3996         return ExprError(Diag(TheCall->getLocStart(),
3997                               diag::err_vec_builtin_incompatible_vector)
3998                          << TheCall->getDirectCallee()
3999                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4000                                         TheCall->getArg(1)->getLocEnd()));
4001     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4002       return ExprError(Diag(TheCall->getLocStart(),
4003                             diag::err_vec_builtin_incompatible_vector)
4004                        << TheCall->getDirectCallee()
4005                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4006                                       TheCall->getArg(1)->getLocEnd()));
4007     } else if (numElements != numResElements) {
4008       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4009       resType = Context.getVectorType(eltType, numResElements,
4010                                       VectorType::GenericVector);
4011     }
4012   }
4013 
4014   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4015     if (TheCall->getArg(i)->isTypeDependent() ||
4016         TheCall->getArg(i)->isValueDependent())
4017       continue;
4018 
4019     llvm::APSInt Result(32);
4020     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4021       return ExprError(Diag(TheCall->getLocStart(),
4022                             diag::err_shufflevector_nonconstant_argument)
4023                        << TheCall->getArg(i)->getSourceRange());
4024 
4025     // Allow -1 which will be translated to undef in the IR.
4026     if (Result.isSigned() && Result.isAllOnesValue())
4027       continue;
4028 
4029     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4030       return ExprError(Diag(TheCall->getLocStart(),
4031                             diag::err_shufflevector_argument_too_large)
4032                        << TheCall->getArg(i)->getSourceRange());
4033   }
4034 
4035   SmallVector<Expr*, 32> exprs;
4036 
4037   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4038     exprs.push_back(TheCall->getArg(i));
4039     TheCall->setArg(i, nullptr);
4040   }
4041 
4042   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4043                                          TheCall->getCallee()->getLocStart(),
4044                                          TheCall->getRParenLoc());
4045 }
4046 
4047 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4048 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4049                                        SourceLocation BuiltinLoc,
4050                                        SourceLocation RParenLoc) {
4051   ExprValueKind VK = VK_RValue;
4052   ExprObjectKind OK = OK_Ordinary;
4053   QualType DstTy = TInfo->getType();
4054   QualType SrcTy = E->getType();
4055 
4056   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4057     return ExprError(Diag(BuiltinLoc,
4058                           diag::err_convertvector_non_vector)
4059                      << E->getSourceRange());
4060   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4061     return ExprError(Diag(BuiltinLoc,
4062                           diag::err_convertvector_non_vector_type));
4063 
4064   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4065     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4066     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4067     if (SrcElts != DstElts)
4068       return ExprError(Diag(BuiltinLoc,
4069                             diag::err_convertvector_incompatible_vector)
4070                        << E->getSourceRange());
4071   }
4072 
4073   return new (Context)
4074       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4075 }
4076 
4077 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4078 // This is declared to take (const void*, ...) and can take two
4079 // optional constant int args.
4080 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4081   unsigned NumArgs = TheCall->getNumArgs();
4082 
4083   if (NumArgs > 3)
4084     return Diag(TheCall->getLocEnd(),
4085              diag::err_typecheck_call_too_many_args_at_most)
4086              << 0 /*function call*/ << 3 << NumArgs
4087              << TheCall->getSourceRange();
4088 
4089   // Argument 0 is checked for us and the remaining arguments must be
4090   // constant integers.
4091   for (unsigned i = 1; i != NumArgs; ++i)
4092     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4093       return true;
4094 
4095   return false;
4096 }
4097 
4098 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4099 // __assume does not evaluate its arguments, and should warn if its argument
4100 // has side effects.
4101 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4102   Expr *Arg = TheCall->getArg(0);
4103   if (Arg->isInstantiationDependent()) return false;
4104 
4105   if (Arg->HasSideEffects(Context))
4106     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4107       << Arg->getSourceRange()
4108       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4109 
4110   return false;
4111 }
4112 
4113 /// Handle __builtin_alloca_with_align. This is declared
4114 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4115 /// than 8.
4116 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4117   // The alignment must be a constant integer.
4118   Expr *Arg = TheCall->getArg(1);
4119 
4120   // We can't check the value of a dependent argument.
4121   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4122     if (const auto *UE =
4123             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4124       if (UE->getKind() == UETT_AlignOf)
4125         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4126           << Arg->getSourceRange();
4127 
4128     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4129 
4130     if (!Result.isPowerOf2())
4131       return Diag(TheCall->getLocStart(),
4132                   diag::err_alignment_not_power_of_two)
4133            << Arg->getSourceRange();
4134 
4135     if (Result < Context.getCharWidth())
4136       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4137            << (unsigned)Context.getCharWidth()
4138            << Arg->getSourceRange();
4139 
4140     if (Result > INT32_MAX)
4141       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4142            << INT32_MAX
4143            << Arg->getSourceRange();
4144   }
4145 
4146   return false;
4147 }
4148 
4149 /// Handle __builtin_assume_aligned. This is declared
4150 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4151 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4152   unsigned NumArgs = TheCall->getNumArgs();
4153 
4154   if (NumArgs > 3)
4155     return Diag(TheCall->getLocEnd(),
4156              diag::err_typecheck_call_too_many_args_at_most)
4157              << 0 /*function call*/ << 3 << NumArgs
4158              << TheCall->getSourceRange();
4159 
4160   // The alignment must be a constant integer.
4161   Expr *Arg = TheCall->getArg(1);
4162 
4163   // We can't check the value of a dependent argument.
4164   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4165     llvm::APSInt Result;
4166     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4167       return true;
4168 
4169     if (!Result.isPowerOf2())
4170       return Diag(TheCall->getLocStart(),
4171                   diag::err_alignment_not_power_of_two)
4172            << Arg->getSourceRange();
4173   }
4174 
4175   if (NumArgs > 2) {
4176     ExprResult Arg(TheCall->getArg(2));
4177     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4178       Context.getSizeType(), false);
4179     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4180     if (Arg.isInvalid()) return true;
4181     TheCall->setArg(2, Arg.get());
4182   }
4183 
4184   return false;
4185 }
4186 
4187 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4188   unsigned BuiltinID =
4189       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4190   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4191 
4192   unsigned NumArgs = TheCall->getNumArgs();
4193   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4194   if (NumArgs < NumRequiredArgs) {
4195     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4196            << 0 /* function call */ << NumRequiredArgs << NumArgs
4197            << TheCall->getSourceRange();
4198   }
4199   if (NumArgs >= NumRequiredArgs + 0x100) {
4200     return Diag(TheCall->getLocEnd(),
4201                 diag::err_typecheck_call_too_many_args_at_most)
4202            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4203            << TheCall->getSourceRange();
4204   }
4205   unsigned i = 0;
4206 
4207   // For formatting call, check buffer arg.
4208   if (!IsSizeCall) {
4209     ExprResult Arg(TheCall->getArg(i));
4210     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4211         Context, Context.VoidPtrTy, false);
4212     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4213     if (Arg.isInvalid())
4214       return true;
4215     TheCall->setArg(i, Arg.get());
4216     i++;
4217   }
4218 
4219   // Check string literal arg.
4220   unsigned FormatIdx = i;
4221   {
4222     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4223     if (Arg.isInvalid())
4224       return true;
4225     TheCall->setArg(i, Arg.get());
4226     i++;
4227   }
4228 
4229   // Make sure variadic args are scalar.
4230   unsigned FirstDataArg = i;
4231   while (i < NumArgs) {
4232     ExprResult Arg = DefaultVariadicArgumentPromotion(
4233         TheCall->getArg(i), VariadicFunction, nullptr);
4234     if (Arg.isInvalid())
4235       return true;
4236     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4237     if (ArgSize.getQuantity() >= 0x100) {
4238       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4239              << i << (int)ArgSize.getQuantity() << 0xff
4240              << TheCall->getSourceRange();
4241     }
4242     TheCall->setArg(i, Arg.get());
4243     i++;
4244   }
4245 
4246   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4247   // call to avoid duplicate diagnostics.
4248   if (!IsSizeCall) {
4249     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4250     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4251     bool Success = CheckFormatArguments(
4252         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4253         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4254         CheckedVarArgs);
4255     if (!Success)
4256       return true;
4257   }
4258 
4259   if (IsSizeCall) {
4260     TheCall->setType(Context.getSizeType());
4261   } else {
4262     TheCall->setType(Context.VoidPtrTy);
4263   }
4264   return false;
4265 }
4266 
4267 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4268 /// TheCall is a constant expression.
4269 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4270                                   llvm::APSInt &Result) {
4271   Expr *Arg = TheCall->getArg(ArgNum);
4272   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4273   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4274 
4275   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4276 
4277   if (!Arg->isIntegerConstantExpr(Result, Context))
4278     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4279                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4280 
4281   return false;
4282 }
4283 
4284 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4285 /// TheCall is a constant expression in the range [Low, High].
4286 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4287                                        int Low, int High) {
4288   llvm::APSInt Result;
4289 
4290   // We can't check the value of a dependent argument.
4291   Expr *Arg = TheCall->getArg(ArgNum);
4292   if (Arg->isTypeDependent() || Arg->isValueDependent())
4293     return false;
4294 
4295   // Check constant-ness first.
4296   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4297     return true;
4298 
4299   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4300     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4301       << Low << High << Arg->getSourceRange();
4302 
4303   return false;
4304 }
4305 
4306 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4307 /// TheCall is a constant expression is a multiple of Num..
4308 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4309                                           unsigned Num) {
4310   llvm::APSInt Result;
4311 
4312   // We can't check the value of a dependent argument.
4313   Expr *Arg = TheCall->getArg(ArgNum);
4314   if (Arg->isTypeDependent() || Arg->isValueDependent())
4315     return false;
4316 
4317   // Check constant-ness first.
4318   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4319     return true;
4320 
4321   if (Result.getSExtValue() % Num != 0)
4322     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4323       << Num << Arg->getSourceRange();
4324 
4325   return false;
4326 }
4327 
4328 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4329 /// TheCall is an ARM/AArch64 special register string literal.
4330 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4331                                     int ArgNum, unsigned ExpectedFieldNum,
4332                                     bool AllowName) {
4333   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4334                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4335                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4336                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4337                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4338                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4339   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4340                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4341                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4342                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4343                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4344                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4345   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4346 
4347   // We can't check the value of a dependent argument.
4348   Expr *Arg = TheCall->getArg(ArgNum);
4349   if (Arg->isTypeDependent() || Arg->isValueDependent())
4350     return false;
4351 
4352   // Check if the argument is a string literal.
4353   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4354     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4355            << Arg->getSourceRange();
4356 
4357   // Check the type of special register given.
4358   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4359   SmallVector<StringRef, 6> Fields;
4360   Reg.split(Fields, ":");
4361 
4362   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4363     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4364            << Arg->getSourceRange();
4365 
4366   // If the string is the name of a register then we cannot check that it is
4367   // valid here but if the string is of one the forms described in ACLE then we
4368   // can check that the supplied fields are integers and within the valid
4369   // ranges.
4370   if (Fields.size() > 1) {
4371     bool FiveFields = Fields.size() == 5;
4372 
4373     bool ValidString = true;
4374     if (IsARMBuiltin) {
4375       ValidString &= Fields[0].startswith_lower("cp") ||
4376                      Fields[0].startswith_lower("p");
4377       if (ValidString)
4378         Fields[0] =
4379           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4380 
4381       ValidString &= Fields[2].startswith_lower("c");
4382       if (ValidString)
4383         Fields[2] = Fields[2].drop_front(1);
4384 
4385       if (FiveFields) {
4386         ValidString &= Fields[3].startswith_lower("c");
4387         if (ValidString)
4388           Fields[3] = Fields[3].drop_front(1);
4389       }
4390     }
4391 
4392     SmallVector<int, 5> Ranges;
4393     if (FiveFields)
4394       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4395     else
4396       Ranges.append({15, 7, 15});
4397 
4398     for (unsigned i=0; i<Fields.size(); ++i) {
4399       int IntField;
4400       ValidString &= !Fields[i].getAsInteger(10, IntField);
4401       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4402     }
4403 
4404     if (!ValidString)
4405       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4406              << Arg->getSourceRange();
4407 
4408   } else if (IsAArch64Builtin && Fields.size() == 1) {
4409     // If the register name is one of those that appear in the condition below
4410     // and the special register builtin being used is one of the write builtins,
4411     // then we require that the argument provided for writing to the register
4412     // is an integer constant expression. This is because it will be lowered to
4413     // an MSR (immediate) instruction, so we need to know the immediate at
4414     // compile time.
4415     if (TheCall->getNumArgs() != 2)
4416       return false;
4417 
4418     std::string RegLower = Reg.lower();
4419     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4420         RegLower != "pan" && RegLower != "uao")
4421       return false;
4422 
4423     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4424   }
4425 
4426   return false;
4427 }
4428 
4429 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4430 /// This checks that the target supports __builtin_longjmp and
4431 /// that val is a constant 1.
4432 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4433   if (!Context.getTargetInfo().hasSjLjLowering())
4434     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4435              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4436 
4437   Expr *Arg = TheCall->getArg(1);
4438   llvm::APSInt Result;
4439 
4440   // TODO: This is less than ideal. Overload this to take a value.
4441   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4442     return true;
4443 
4444   if (Result != 1)
4445     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4446              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4447 
4448   return false;
4449 }
4450 
4451 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4452 /// This checks that the target supports __builtin_setjmp.
4453 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4454   if (!Context.getTargetInfo().hasSjLjLowering())
4455     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4456              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4457   return false;
4458 }
4459 
4460 namespace {
4461 class UncoveredArgHandler {
4462   enum { Unknown = -1, AllCovered = -2 };
4463   signed FirstUncoveredArg;
4464   SmallVector<const Expr *, 4> DiagnosticExprs;
4465 
4466 public:
4467   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4468 
4469   bool hasUncoveredArg() const {
4470     return (FirstUncoveredArg >= 0);
4471   }
4472 
4473   unsigned getUncoveredArg() const {
4474     assert(hasUncoveredArg() && "no uncovered argument");
4475     return FirstUncoveredArg;
4476   }
4477 
4478   void setAllCovered() {
4479     // A string has been found with all arguments covered, so clear out
4480     // the diagnostics.
4481     DiagnosticExprs.clear();
4482     FirstUncoveredArg = AllCovered;
4483   }
4484 
4485   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4486     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4487 
4488     // Don't update if a previous string covers all arguments.
4489     if (FirstUncoveredArg == AllCovered)
4490       return;
4491 
4492     // UncoveredArgHandler tracks the highest uncovered argument index
4493     // and with it all the strings that match this index.
4494     if (NewFirstUncoveredArg == FirstUncoveredArg)
4495       DiagnosticExprs.push_back(StrExpr);
4496     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4497       DiagnosticExprs.clear();
4498       DiagnosticExprs.push_back(StrExpr);
4499       FirstUncoveredArg = NewFirstUncoveredArg;
4500     }
4501   }
4502 
4503   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4504 };
4505 
4506 enum StringLiteralCheckType {
4507   SLCT_NotALiteral,
4508   SLCT_UncheckedLiteral,
4509   SLCT_CheckedLiteral
4510 };
4511 } // end anonymous namespace
4512 
4513 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4514                                      BinaryOperatorKind BinOpKind,
4515                                      bool AddendIsRight) {
4516   unsigned BitWidth = Offset.getBitWidth();
4517   unsigned AddendBitWidth = Addend.getBitWidth();
4518   // There might be negative interim results.
4519   if (Addend.isUnsigned()) {
4520     Addend = Addend.zext(++AddendBitWidth);
4521     Addend.setIsSigned(true);
4522   }
4523   // Adjust the bit width of the APSInts.
4524   if (AddendBitWidth > BitWidth) {
4525     Offset = Offset.sext(AddendBitWidth);
4526     BitWidth = AddendBitWidth;
4527   } else if (BitWidth > AddendBitWidth) {
4528     Addend = Addend.sext(BitWidth);
4529   }
4530 
4531   bool Ov = false;
4532   llvm::APSInt ResOffset = Offset;
4533   if (BinOpKind == BO_Add)
4534     ResOffset = Offset.sadd_ov(Addend, Ov);
4535   else {
4536     assert(AddendIsRight && BinOpKind == BO_Sub &&
4537            "operator must be add or sub with addend on the right");
4538     ResOffset = Offset.ssub_ov(Addend, Ov);
4539   }
4540 
4541   // We add an offset to a pointer here so we should support an offset as big as
4542   // possible.
4543   if (Ov) {
4544     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4545     Offset = Offset.sext(2 * BitWidth);
4546     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4547     return;
4548   }
4549 
4550   Offset = ResOffset;
4551 }
4552 
4553 namespace {
4554 // This is a wrapper class around StringLiteral to support offsetted string
4555 // literals as format strings. It takes the offset into account when returning
4556 // the string and its length or the source locations to display notes correctly.
4557 class FormatStringLiteral {
4558   const StringLiteral *FExpr;
4559   int64_t Offset;
4560 
4561  public:
4562   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4563       : FExpr(fexpr), Offset(Offset) {}
4564 
4565   StringRef getString() const {
4566     return FExpr->getString().drop_front(Offset);
4567   }
4568 
4569   unsigned getByteLength() const {
4570     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4571   }
4572   unsigned getLength() const { return FExpr->getLength() - Offset; }
4573   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4574 
4575   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4576 
4577   QualType getType() const { return FExpr->getType(); }
4578 
4579   bool isAscii() const { return FExpr->isAscii(); }
4580   bool isWide() const { return FExpr->isWide(); }
4581   bool isUTF8() const { return FExpr->isUTF8(); }
4582   bool isUTF16() const { return FExpr->isUTF16(); }
4583   bool isUTF32() const { return FExpr->isUTF32(); }
4584   bool isPascal() const { return FExpr->isPascal(); }
4585 
4586   SourceLocation getLocationOfByte(
4587       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4588       const TargetInfo &Target, unsigned *StartToken = nullptr,
4589       unsigned *StartTokenByteOffset = nullptr) const {
4590     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4591                                     StartToken, StartTokenByteOffset);
4592   }
4593 
4594   SourceLocation getLocStart() const LLVM_READONLY {
4595     return FExpr->getLocStart().getLocWithOffset(Offset);
4596   }
4597   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4598 };
4599 }  // end anonymous namespace
4600 
4601 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4602                               const Expr *OrigFormatExpr,
4603                               ArrayRef<const Expr *> Args,
4604                               bool HasVAListArg, unsigned format_idx,
4605                               unsigned firstDataArg,
4606                               Sema::FormatStringType Type,
4607                               bool inFunctionCall,
4608                               Sema::VariadicCallType CallType,
4609                               llvm::SmallBitVector &CheckedVarArgs,
4610                               UncoveredArgHandler &UncoveredArg);
4611 
4612 // Determine if an expression is a string literal or constant string.
4613 // If this function returns false on the arguments to a function expecting a
4614 // format string, we will usually need to emit a warning.
4615 // True string literals are then checked by CheckFormatString.
4616 static StringLiteralCheckType
4617 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4618                       bool HasVAListArg, unsigned format_idx,
4619                       unsigned firstDataArg, Sema::FormatStringType Type,
4620                       Sema::VariadicCallType CallType, bool InFunctionCall,
4621                       llvm::SmallBitVector &CheckedVarArgs,
4622                       UncoveredArgHandler &UncoveredArg,
4623                       llvm::APSInt Offset) {
4624  tryAgain:
4625   assert(Offset.isSigned() && "invalid offset");
4626 
4627   if (E->isTypeDependent() || E->isValueDependent())
4628     return SLCT_NotALiteral;
4629 
4630   E = E->IgnoreParenCasts();
4631 
4632   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4633     // Technically -Wformat-nonliteral does not warn about this case.
4634     // The behavior of printf and friends in this case is implementation
4635     // dependent.  Ideally if the format string cannot be null then
4636     // it should have a 'nonnull' attribute in the function prototype.
4637     return SLCT_UncheckedLiteral;
4638 
4639   switch (E->getStmtClass()) {
4640   case Stmt::BinaryConditionalOperatorClass:
4641   case Stmt::ConditionalOperatorClass: {
4642     // The expression is a literal if both sub-expressions were, and it was
4643     // completely checked only if both sub-expressions were checked.
4644     const AbstractConditionalOperator *C =
4645         cast<AbstractConditionalOperator>(E);
4646 
4647     // Determine whether it is necessary to check both sub-expressions, for
4648     // example, because the condition expression is a constant that can be
4649     // evaluated at compile time.
4650     bool CheckLeft = true, CheckRight = true;
4651 
4652     bool Cond;
4653     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4654       if (Cond)
4655         CheckRight = false;
4656       else
4657         CheckLeft = false;
4658     }
4659 
4660     // We need to maintain the offsets for the right and the left hand side
4661     // separately to check if every possible indexed expression is a valid
4662     // string literal. They might have different offsets for different string
4663     // literals in the end.
4664     StringLiteralCheckType Left;
4665     if (!CheckLeft)
4666       Left = SLCT_UncheckedLiteral;
4667     else {
4668       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4669                                    HasVAListArg, format_idx, firstDataArg,
4670                                    Type, CallType, InFunctionCall,
4671                                    CheckedVarArgs, UncoveredArg, Offset);
4672       if (Left == SLCT_NotALiteral || !CheckRight) {
4673         return Left;
4674       }
4675     }
4676 
4677     StringLiteralCheckType Right =
4678         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4679                               HasVAListArg, format_idx, firstDataArg,
4680                               Type, CallType, InFunctionCall, CheckedVarArgs,
4681                               UncoveredArg, Offset);
4682 
4683     return (CheckLeft && Left < Right) ? Left : Right;
4684   }
4685 
4686   case Stmt::ImplicitCastExprClass: {
4687     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4688     goto tryAgain;
4689   }
4690 
4691   case Stmt::OpaqueValueExprClass:
4692     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4693       E = src;
4694       goto tryAgain;
4695     }
4696     return SLCT_NotALiteral;
4697 
4698   case Stmt::PredefinedExprClass:
4699     // While __func__, etc., are technically not string literals, they
4700     // cannot contain format specifiers and thus are not a security
4701     // liability.
4702     return SLCT_UncheckedLiteral;
4703 
4704   case Stmt::DeclRefExprClass: {
4705     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4706 
4707     // As an exception, do not flag errors for variables binding to
4708     // const string literals.
4709     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4710       bool isConstant = false;
4711       QualType T = DR->getType();
4712 
4713       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4714         isConstant = AT->getElementType().isConstant(S.Context);
4715       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4716         isConstant = T.isConstant(S.Context) &&
4717                      PT->getPointeeType().isConstant(S.Context);
4718       } else if (T->isObjCObjectPointerType()) {
4719         // In ObjC, there is usually no "const ObjectPointer" type,
4720         // so don't check if the pointee type is constant.
4721         isConstant = T.isConstant(S.Context);
4722       }
4723 
4724       if (isConstant) {
4725         if (const Expr *Init = VD->getAnyInitializer()) {
4726           // Look through initializers like const char c[] = { "foo" }
4727           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4728             if (InitList->isStringLiteralInit())
4729               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4730           }
4731           return checkFormatStringExpr(S, Init, Args,
4732                                        HasVAListArg, format_idx,
4733                                        firstDataArg, Type, CallType,
4734                                        /*InFunctionCall*/ false, CheckedVarArgs,
4735                                        UncoveredArg, Offset);
4736         }
4737       }
4738 
4739       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4740       // special check to see if the format string is a function parameter
4741       // of the function calling the printf function.  If the function
4742       // has an attribute indicating it is a printf-like function, then we
4743       // should suppress warnings concerning non-literals being used in a call
4744       // to a vprintf function.  For example:
4745       //
4746       // void
4747       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4748       //      va_list ap;
4749       //      va_start(ap, fmt);
4750       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4751       //      ...
4752       // }
4753       if (HasVAListArg) {
4754         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4755           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4756             int PVIndex = PV->getFunctionScopeIndex() + 1;
4757             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4758               // adjust for implicit parameter
4759               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4760                 if (MD->isInstance())
4761                   ++PVIndex;
4762               // We also check if the formats are compatible.
4763               // We can't pass a 'scanf' string to a 'printf' function.
4764               if (PVIndex == PVFormat->getFormatIdx() &&
4765                   Type == S.GetFormatStringType(PVFormat))
4766                 return SLCT_UncheckedLiteral;
4767             }
4768           }
4769         }
4770       }
4771     }
4772 
4773     return SLCT_NotALiteral;
4774   }
4775 
4776   case Stmt::CallExprClass:
4777   case Stmt::CXXMemberCallExprClass: {
4778     const CallExpr *CE = cast<CallExpr>(E);
4779     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4780       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4781         unsigned ArgIndex = FA->getFormatIdx();
4782         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4783           if (MD->isInstance())
4784             --ArgIndex;
4785         const Expr *Arg = CE->getArg(ArgIndex - 1);
4786 
4787         return checkFormatStringExpr(S, Arg, Args,
4788                                      HasVAListArg, format_idx, firstDataArg,
4789                                      Type, CallType, InFunctionCall,
4790                                      CheckedVarArgs, UncoveredArg, Offset);
4791       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4792         unsigned BuiltinID = FD->getBuiltinID();
4793         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4794             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4795           const Expr *Arg = CE->getArg(0);
4796           return checkFormatStringExpr(S, Arg, Args,
4797                                        HasVAListArg, format_idx,
4798                                        firstDataArg, Type, CallType,
4799                                        InFunctionCall, CheckedVarArgs,
4800                                        UncoveredArg, Offset);
4801         }
4802       }
4803     }
4804 
4805     return SLCT_NotALiteral;
4806   }
4807   case Stmt::ObjCMessageExprClass: {
4808     const auto *ME = cast<ObjCMessageExpr>(E);
4809     if (const auto *ND = ME->getMethodDecl()) {
4810       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4811         unsigned ArgIndex = FA->getFormatIdx();
4812         const Expr *Arg = ME->getArg(ArgIndex - 1);
4813         return checkFormatStringExpr(
4814             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4815             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4816       }
4817     }
4818 
4819     return SLCT_NotALiteral;
4820   }
4821   case Stmt::ObjCStringLiteralClass:
4822   case Stmt::StringLiteralClass: {
4823     const StringLiteral *StrE = nullptr;
4824 
4825     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4826       StrE = ObjCFExpr->getString();
4827     else
4828       StrE = cast<StringLiteral>(E);
4829 
4830     if (StrE) {
4831       if (Offset.isNegative() || Offset > StrE->getLength()) {
4832         // TODO: It would be better to have an explicit warning for out of
4833         // bounds literals.
4834         return SLCT_NotALiteral;
4835       }
4836       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4837       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4838                         firstDataArg, Type, InFunctionCall, CallType,
4839                         CheckedVarArgs, UncoveredArg);
4840       return SLCT_CheckedLiteral;
4841     }
4842 
4843     return SLCT_NotALiteral;
4844   }
4845   case Stmt::BinaryOperatorClass: {
4846     llvm::APSInt LResult;
4847     llvm::APSInt RResult;
4848 
4849     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4850 
4851     // A string literal + an int offset is still a string literal.
4852     if (BinOp->isAdditiveOp()) {
4853       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4854       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4855 
4856       if (LIsInt != RIsInt) {
4857         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4858 
4859         if (LIsInt) {
4860           if (BinOpKind == BO_Add) {
4861             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4862             E = BinOp->getRHS();
4863             goto tryAgain;
4864           }
4865         } else {
4866           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4867           E = BinOp->getLHS();
4868           goto tryAgain;
4869         }
4870       }
4871     }
4872 
4873     return SLCT_NotALiteral;
4874   }
4875   case Stmt::UnaryOperatorClass: {
4876     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4877     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4878     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4879       llvm::APSInt IndexResult;
4880       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4881         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4882         E = ASE->getBase();
4883         goto tryAgain;
4884       }
4885     }
4886 
4887     return SLCT_NotALiteral;
4888   }
4889 
4890   default:
4891     return SLCT_NotALiteral;
4892   }
4893 }
4894 
4895 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4896   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4897       .Case("scanf", FST_Scanf)
4898       .Cases("printf", "printf0", FST_Printf)
4899       .Cases("NSString", "CFString", FST_NSString)
4900       .Case("strftime", FST_Strftime)
4901       .Case("strfmon", FST_Strfmon)
4902       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4903       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4904       .Case("os_trace", FST_OSLog)
4905       .Case("os_log", FST_OSLog)
4906       .Default(FST_Unknown);
4907 }
4908 
4909 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4910 /// functions) for correct use of format strings.
4911 /// Returns true if a format string has been fully checked.
4912 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4913                                 ArrayRef<const Expr *> Args,
4914                                 bool IsCXXMember,
4915                                 VariadicCallType CallType,
4916                                 SourceLocation Loc, SourceRange Range,
4917                                 llvm::SmallBitVector &CheckedVarArgs) {
4918   FormatStringInfo FSI;
4919   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4920     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4921                                 FSI.FirstDataArg, GetFormatStringType(Format),
4922                                 CallType, Loc, Range, CheckedVarArgs);
4923   return false;
4924 }
4925 
4926 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4927                                 bool HasVAListArg, unsigned format_idx,
4928                                 unsigned firstDataArg, FormatStringType Type,
4929                                 VariadicCallType CallType,
4930                                 SourceLocation Loc, SourceRange Range,
4931                                 llvm::SmallBitVector &CheckedVarArgs) {
4932   // CHECK: printf/scanf-like function is called with no format string.
4933   if (format_idx >= Args.size()) {
4934     Diag(Loc, diag::warn_missing_format_string) << Range;
4935     return false;
4936   }
4937 
4938   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4939 
4940   // CHECK: format string is not a string literal.
4941   //
4942   // Dynamically generated format strings are difficult to
4943   // automatically vet at compile time.  Requiring that format strings
4944   // are string literals: (1) permits the checking of format strings by
4945   // the compiler and thereby (2) can practically remove the source of
4946   // many format string exploits.
4947 
4948   // Format string can be either ObjC string (e.g. @"%d") or
4949   // C string (e.g. "%d")
4950   // ObjC string uses the same format specifiers as C string, so we can use
4951   // the same format string checking logic for both ObjC and C strings.
4952   UncoveredArgHandler UncoveredArg;
4953   StringLiteralCheckType CT =
4954       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4955                             format_idx, firstDataArg, Type, CallType,
4956                             /*IsFunctionCall*/ true, CheckedVarArgs,
4957                             UncoveredArg,
4958                             /*no string offset*/ llvm::APSInt(64, false) = 0);
4959 
4960   // Generate a diagnostic where an uncovered argument is detected.
4961   if (UncoveredArg.hasUncoveredArg()) {
4962     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4963     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4964     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4965   }
4966 
4967   if (CT != SLCT_NotALiteral)
4968     // Literal format string found, check done!
4969     return CT == SLCT_CheckedLiteral;
4970 
4971   // Strftime is particular as it always uses a single 'time' argument,
4972   // so it is safe to pass a non-literal string.
4973   if (Type == FST_Strftime)
4974     return false;
4975 
4976   // Do not emit diag when the string param is a macro expansion and the
4977   // format is either NSString or CFString. This is a hack to prevent
4978   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4979   // which are usually used in place of NS and CF string literals.
4980   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4981   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4982     return false;
4983 
4984   // If there are no arguments specified, warn with -Wformat-security, otherwise
4985   // warn only with -Wformat-nonliteral.
4986   if (Args.size() == firstDataArg) {
4987     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4988       << OrigFormatExpr->getSourceRange();
4989     switch (Type) {
4990     default:
4991       break;
4992     case FST_Kprintf:
4993     case FST_FreeBSDKPrintf:
4994     case FST_Printf:
4995       Diag(FormatLoc, diag::note_format_security_fixit)
4996         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4997       break;
4998     case FST_NSString:
4999       Diag(FormatLoc, diag::note_format_security_fixit)
5000         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5001       break;
5002     }
5003   } else {
5004     Diag(FormatLoc, diag::warn_format_nonliteral)
5005       << OrigFormatExpr->getSourceRange();
5006   }
5007   return false;
5008 }
5009 
5010 namespace {
5011 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5012 protected:
5013   Sema &S;
5014   const FormatStringLiteral *FExpr;
5015   const Expr *OrigFormatExpr;
5016   const Sema::FormatStringType FSType;
5017   const unsigned FirstDataArg;
5018   const unsigned NumDataArgs;
5019   const char *Beg; // Start of format string.
5020   const bool HasVAListArg;
5021   ArrayRef<const Expr *> Args;
5022   unsigned FormatIdx;
5023   llvm::SmallBitVector CoveredArgs;
5024   bool usesPositionalArgs;
5025   bool atFirstArg;
5026   bool inFunctionCall;
5027   Sema::VariadicCallType CallType;
5028   llvm::SmallBitVector &CheckedVarArgs;
5029   UncoveredArgHandler &UncoveredArg;
5030 
5031 public:
5032   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5033                      const Expr *origFormatExpr,
5034                      const Sema::FormatStringType type, unsigned firstDataArg,
5035                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5036                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5037                      bool inFunctionCall, Sema::VariadicCallType callType,
5038                      llvm::SmallBitVector &CheckedVarArgs,
5039                      UncoveredArgHandler &UncoveredArg)
5040       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5041         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5042         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5043         usesPositionalArgs(false), atFirstArg(true),
5044         inFunctionCall(inFunctionCall), CallType(callType),
5045         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5046     CoveredArgs.resize(numDataArgs);
5047     CoveredArgs.reset();
5048   }
5049 
5050   void DoneProcessing();
5051 
5052   void HandleIncompleteSpecifier(const char *startSpecifier,
5053                                  unsigned specifierLen) override;
5054 
5055   void HandleInvalidLengthModifier(
5056                            const analyze_format_string::FormatSpecifier &FS,
5057                            const analyze_format_string::ConversionSpecifier &CS,
5058                            const char *startSpecifier, unsigned specifierLen,
5059                            unsigned DiagID);
5060 
5061   void HandleNonStandardLengthModifier(
5062                     const analyze_format_string::FormatSpecifier &FS,
5063                     const char *startSpecifier, unsigned specifierLen);
5064 
5065   void HandleNonStandardConversionSpecifier(
5066                     const analyze_format_string::ConversionSpecifier &CS,
5067                     const char *startSpecifier, unsigned specifierLen);
5068 
5069   void HandlePosition(const char *startPos, unsigned posLen) override;
5070 
5071   void HandleInvalidPosition(const char *startSpecifier,
5072                              unsigned specifierLen,
5073                              analyze_format_string::PositionContext p) override;
5074 
5075   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5076 
5077   void HandleNullChar(const char *nullCharacter) override;
5078 
5079   template <typename Range>
5080   static void
5081   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5082                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5083                        bool IsStringLocation, Range StringRange,
5084                        ArrayRef<FixItHint> Fixit = None);
5085 
5086 protected:
5087   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5088                                         const char *startSpec,
5089                                         unsigned specifierLen,
5090                                         const char *csStart, unsigned csLen);
5091 
5092   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5093                                          const char *startSpec,
5094                                          unsigned specifierLen);
5095 
5096   SourceRange getFormatStringRange();
5097   CharSourceRange getSpecifierRange(const char *startSpecifier,
5098                                     unsigned specifierLen);
5099   SourceLocation getLocationOfByte(const char *x);
5100 
5101   const Expr *getDataArg(unsigned i) const;
5102 
5103   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5104                     const analyze_format_string::ConversionSpecifier &CS,
5105                     const char *startSpecifier, unsigned specifierLen,
5106                     unsigned argIndex);
5107 
5108   template <typename Range>
5109   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5110                             bool IsStringLocation, Range StringRange,
5111                             ArrayRef<FixItHint> Fixit = None);
5112 };
5113 } // end anonymous namespace
5114 
5115 SourceRange CheckFormatHandler::getFormatStringRange() {
5116   return OrigFormatExpr->getSourceRange();
5117 }
5118 
5119 CharSourceRange CheckFormatHandler::
5120 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5121   SourceLocation Start = getLocationOfByte(startSpecifier);
5122   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5123 
5124   // Advance the end SourceLocation by one due to half-open ranges.
5125   End = End.getLocWithOffset(1);
5126 
5127   return CharSourceRange::getCharRange(Start, End);
5128 }
5129 
5130 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5131   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5132                                   S.getLangOpts(), S.Context.getTargetInfo());
5133 }
5134 
5135 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5136                                                    unsigned specifierLen){
5137   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5138                        getLocationOfByte(startSpecifier),
5139                        /*IsStringLocation*/true,
5140                        getSpecifierRange(startSpecifier, specifierLen));
5141 }
5142 
5143 void CheckFormatHandler::HandleInvalidLengthModifier(
5144     const analyze_format_string::FormatSpecifier &FS,
5145     const analyze_format_string::ConversionSpecifier &CS,
5146     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5147   using namespace analyze_format_string;
5148 
5149   const LengthModifier &LM = FS.getLengthModifier();
5150   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5151 
5152   // See if we know how to fix this length modifier.
5153   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5154   if (FixedLM) {
5155     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5156                          getLocationOfByte(LM.getStart()),
5157                          /*IsStringLocation*/true,
5158                          getSpecifierRange(startSpecifier, specifierLen));
5159 
5160     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5161       << FixedLM->toString()
5162       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5163 
5164   } else {
5165     FixItHint Hint;
5166     if (DiagID == diag::warn_format_nonsensical_length)
5167       Hint = FixItHint::CreateRemoval(LMRange);
5168 
5169     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5170                          getLocationOfByte(LM.getStart()),
5171                          /*IsStringLocation*/true,
5172                          getSpecifierRange(startSpecifier, specifierLen),
5173                          Hint);
5174   }
5175 }
5176 
5177 void CheckFormatHandler::HandleNonStandardLengthModifier(
5178     const analyze_format_string::FormatSpecifier &FS,
5179     const char *startSpecifier, unsigned specifierLen) {
5180   using namespace analyze_format_string;
5181 
5182   const LengthModifier &LM = FS.getLengthModifier();
5183   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5184 
5185   // See if we know how to fix this length modifier.
5186   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5187   if (FixedLM) {
5188     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5189                            << LM.toString() << 0,
5190                          getLocationOfByte(LM.getStart()),
5191                          /*IsStringLocation*/true,
5192                          getSpecifierRange(startSpecifier, specifierLen));
5193 
5194     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5195       << FixedLM->toString()
5196       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5197 
5198   } else {
5199     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5200                            << LM.toString() << 0,
5201                          getLocationOfByte(LM.getStart()),
5202                          /*IsStringLocation*/true,
5203                          getSpecifierRange(startSpecifier, specifierLen));
5204   }
5205 }
5206 
5207 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5208     const analyze_format_string::ConversionSpecifier &CS,
5209     const char *startSpecifier, unsigned specifierLen) {
5210   using namespace analyze_format_string;
5211 
5212   // See if we know how to fix this conversion specifier.
5213   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5214   if (FixedCS) {
5215     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5216                           << CS.toString() << /*conversion specifier*/1,
5217                          getLocationOfByte(CS.getStart()),
5218                          /*IsStringLocation*/true,
5219                          getSpecifierRange(startSpecifier, specifierLen));
5220 
5221     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5222     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5223       << FixedCS->toString()
5224       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5225   } else {
5226     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5227                           << CS.toString() << /*conversion specifier*/1,
5228                          getLocationOfByte(CS.getStart()),
5229                          /*IsStringLocation*/true,
5230                          getSpecifierRange(startSpecifier, specifierLen));
5231   }
5232 }
5233 
5234 void CheckFormatHandler::HandlePosition(const char *startPos,
5235                                         unsigned posLen) {
5236   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5237                                getLocationOfByte(startPos),
5238                                /*IsStringLocation*/true,
5239                                getSpecifierRange(startPos, posLen));
5240 }
5241 
5242 void
5243 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5244                                      analyze_format_string::PositionContext p) {
5245   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5246                          << (unsigned) p,
5247                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5248                        getSpecifierRange(startPos, posLen));
5249 }
5250 
5251 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5252                                             unsigned posLen) {
5253   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5254                                getLocationOfByte(startPos),
5255                                /*IsStringLocation*/true,
5256                                getSpecifierRange(startPos, posLen));
5257 }
5258 
5259 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5260   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5261     // The presence of a null character is likely an error.
5262     EmitFormatDiagnostic(
5263       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5264       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5265       getFormatStringRange());
5266   }
5267 }
5268 
5269 // Note that this may return NULL if there was an error parsing or building
5270 // one of the argument expressions.
5271 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5272   return Args[FirstDataArg + i];
5273 }
5274 
5275 void CheckFormatHandler::DoneProcessing() {
5276   // Does the number of data arguments exceed the number of
5277   // format conversions in the format string?
5278   if (!HasVAListArg) {
5279       // Find any arguments that weren't covered.
5280     CoveredArgs.flip();
5281     signed notCoveredArg = CoveredArgs.find_first();
5282     if (notCoveredArg >= 0) {
5283       assert((unsigned)notCoveredArg < NumDataArgs);
5284       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5285     } else {
5286       UncoveredArg.setAllCovered();
5287     }
5288   }
5289 }
5290 
5291 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5292                                    const Expr *ArgExpr) {
5293   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5294          "Invalid state");
5295 
5296   if (!ArgExpr)
5297     return;
5298 
5299   SourceLocation Loc = ArgExpr->getLocStart();
5300 
5301   if (S.getSourceManager().isInSystemMacro(Loc))
5302     return;
5303 
5304   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5305   for (auto E : DiagnosticExprs)
5306     PDiag << E->getSourceRange();
5307 
5308   CheckFormatHandler::EmitFormatDiagnostic(
5309                                   S, IsFunctionCall, DiagnosticExprs[0],
5310                                   PDiag, Loc, /*IsStringLocation*/false,
5311                                   DiagnosticExprs[0]->getSourceRange());
5312 }
5313 
5314 bool
5315 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5316                                                      SourceLocation Loc,
5317                                                      const char *startSpec,
5318                                                      unsigned specifierLen,
5319                                                      const char *csStart,
5320                                                      unsigned csLen) {
5321   bool keepGoing = true;
5322   if (argIndex < NumDataArgs) {
5323     // Consider the argument coverered, even though the specifier doesn't
5324     // make sense.
5325     CoveredArgs.set(argIndex);
5326   }
5327   else {
5328     // If argIndex exceeds the number of data arguments we
5329     // don't issue a warning because that is just a cascade of warnings (and
5330     // they may have intended '%%' anyway). We don't want to continue processing
5331     // the format string after this point, however, as we will like just get
5332     // gibberish when trying to match arguments.
5333     keepGoing = false;
5334   }
5335 
5336   StringRef Specifier(csStart, csLen);
5337 
5338   // If the specifier in non-printable, it could be the first byte of a UTF-8
5339   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5340   // hex value.
5341   std::string CodePointStr;
5342   if (!llvm::sys::locale::isPrint(*csStart)) {
5343     llvm::UTF32 CodePoint;
5344     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5345     const llvm::UTF8 *E =
5346         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5347     llvm::ConversionResult Result =
5348         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5349 
5350     if (Result != llvm::conversionOK) {
5351       unsigned char FirstChar = *csStart;
5352       CodePoint = (llvm::UTF32)FirstChar;
5353     }
5354 
5355     llvm::raw_string_ostream OS(CodePointStr);
5356     if (CodePoint < 256)
5357       OS << "\\x" << llvm::format("%02x", CodePoint);
5358     else if (CodePoint <= 0xFFFF)
5359       OS << "\\u" << llvm::format("%04x", CodePoint);
5360     else
5361       OS << "\\U" << llvm::format("%08x", CodePoint);
5362     OS.flush();
5363     Specifier = CodePointStr;
5364   }
5365 
5366   EmitFormatDiagnostic(
5367       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5368       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5369 
5370   return keepGoing;
5371 }
5372 
5373 void
5374 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5375                                                       const char *startSpec,
5376                                                       unsigned specifierLen) {
5377   EmitFormatDiagnostic(
5378     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5379     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5380 }
5381 
5382 bool
5383 CheckFormatHandler::CheckNumArgs(
5384   const analyze_format_string::FormatSpecifier &FS,
5385   const analyze_format_string::ConversionSpecifier &CS,
5386   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5387 
5388   if (argIndex >= NumDataArgs) {
5389     PartialDiagnostic PDiag = FS.usesPositionalArg()
5390       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5391            << (argIndex+1) << NumDataArgs)
5392       : S.PDiag(diag::warn_printf_insufficient_data_args);
5393     EmitFormatDiagnostic(
5394       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5395       getSpecifierRange(startSpecifier, specifierLen));
5396 
5397     // Since more arguments than conversion tokens are given, by extension
5398     // all arguments are covered, so mark this as so.
5399     UncoveredArg.setAllCovered();
5400     return false;
5401   }
5402   return true;
5403 }
5404 
5405 template<typename Range>
5406 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5407                                               SourceLocation Loc,
5408                                               bool IsStringLocation,
5409                                               Range StringRange,
5410                                               ArrayRef<FixItHint> FixIt) {
5411   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5412                        Loc, IsStringLocation, StringRange, FixIt);
5413 }
5414 
5415 /// \brief If the format string is not within the funcion call, emit a note
5416 /// so that the function call and string are in diagnostic messages.
5417 ///
5418 /// \param InFunctionCall if true, the format string is within the function
5419 /// call and only one diagnostic message will be produced.  Otherwise, an
5420 /// extra note will be emitted pointing to location of the format string.
5421 ///
5422 /// \param ArgumentExpr the expression that is passed as the format string
5423 /// argument in the function call.  Used for getting locations when two
5424 /// diagnostics are emitted.
5425 ///
5426 /// \param PDiag the callee should already have provided any strings for the
5427 /// diagnostic message.  This function only adds locations and fixits
5428 /// to diagnostics.
5429 ///
5430 /// \param Loc primary location for diagnostic.  If two diagnostics are
5431 /// required, one will be at Loc and a new SourceLocation will be created for
5432 /// the other one.
5433 ///
5434 /// \param IsStringLocation if true, Loc points to the format string should be
5435 /// used for the note.  Otherwise, Loc points to the argument list and will
5436 /// be used with PDiag.
5437 ///
5438 /// \param StringRange some or all of the string to highlight.  This is
5439 /// templated so it can accept either a CharSourceRange or a SourceRange.
5440 ///
5441 /// \param FixIt optional fix it hint for the format string.
5442 template <typename Range>
5443 void CheckFormatHandler::EmitFormatDiagnostic(
5444     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5445     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5446     Range StringRange, ArrayRef<FixItHint> FixIt) {
5447   if (InFunctionCall) {
5448     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5449     D << StringRange;
5450     D << FixIt;
5451   } else {
5452     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5453       << ArgumentExpr->getSourceRange();
5454 
5455     const Sema::SemaDiagnosticBuilder &Note =
5456       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5457              diag::note_format_string_defined);
5458 
5459     Note << StringRange;
5460     Note << FixIt;
5461   }
5462 }
5463 
5464 //===--- CHECK: Printf format string checking ------------------------------===//
5465 
5466 namespace {
5467 class CheckPrintfHandler : public CheckFormatHandler {
5468 public:
5469   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5470                      const Expr *origFormatExpr,
5471                      const Sema::FormatStringType type, unsigned firstDataArg,
5472                      unsigned numDataArgs, bool isObjC, const char *beg,
5473                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5474                      unsigned formatIdx, bool inFunctionCall,
5475                      Sema::VariadicCallType CallType,
5476                      llvm::SmallBitVector &CheckedVarArgs,
5477                      UncoveredArgHandler &UncoveredArg)
5478       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5479                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5480                            inFunctionCall, CallType, CheckedVarArgs,
5481                            UncoveredArg) {}
5482 
5483   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5484 
5485   /// Returns true if '%@' specifiers are allowed in the format string.
5486   bool allowsObjCArg() const {
5487     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5488            FSType == Sema::FST_OSTrace;
5489   }
5490 
5491   bool HandleInvalidPrintfConversionSpecifier(
5492                                       const analyze_printf::PrintfSpecifier &FS,
5493                                       const char *startSpecifier,
5494                                       unsigned specifierLen) override;
5495 
5496   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5497                              const char *startSpecifier,
5498                              unsigned specifierLen) override;
5499   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5500                        const char *StartSpecifier,
5501                        unsigned SpecifierLen,
5502                        const Expr *E);
5503 
5504   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5505                     const char *startSpecifier, unsigned specifierLen);
5506   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5507                            const analyze_printf::OptionalAmount &Amt,
5508                            unsigned type,
5509                            const char *startSpecifier, unsigned specifierLen);
5510   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5511                   const analyze_printf::OptionalFlag &flag,
5512                   const char *startSpecifier, unsigned specifierLen);
5513   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5514                          const analyze_printf::OptionalFlag &ignoredFlag,
5515                          const analyze_printf::OptionalFlag &flag,
5516                          const char *startSpecifier, unsigned specifierLen);
5517   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5518                            const Expr *E);
5519 
5520   void HandleEmptyObjCModifierFlag(const char *startFlag,
5521                                    unsigned flagLen) override;
5522 
5523   void HandleInvalidObjCModifierFlag(const char *startFlag,
5524                                             unsigned flagLen) override;
5525 
5526   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5527                                            const char *flagsEnd,
5528                                            const char *conversionPosition)
5529                                              override;
5530 };
5531 } // end anonymous namespace
5532 
5533 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5534                                       const analyze_printf::PrintfSpecifier &FS,
5535                                       const char *startSpecifier,
5536                                       unsigned specifierLen) {
5537   const analyze_printf::PrintfConversionSpecifier &CS =
5538     FS.getConversionSpecifier();
5539 
5540   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5541                                           getLocationOfByte(CS.getStart()),
5542                                           startSpecifier, specifierLen,
5543                                           CS.getStart(), CS.getLength());
5544 }
5545 
5546 bool CheckPrintfHandler::HandleAmount(
5547                                const analyze_format_string::OptionalAmount &Amt,
5548                                unsigned k, const char *startSpecifier,
5549                                unsigned specifierLen) {
5550   if (Amt.hasDataArgument()) {
5551     if (!HasVAListArg) {
5552       unsigned argIndex = Amt.getArgIndex();
5553       if (argIndex >= NumDataArgs) {
5554         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5555                                << k,
5556                              getLocationOfByte(Amt.getStart()),
5557                              /*IsStringLocation*/true,
5558                              getSpecifierRange(startSpecifier, specifierLen));
5559         // Don't do any more checking.  We will just emit
5560         // spurious errors.
5561         return false;
5562       }
5563 
5564       // Type check the data argument.  It should be an 'int'.
5565       // Although not in conformance with C99, we also allow the argument to be
5566       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5567       // doesn't emit a warning for that case.
5568       CoveredArgs.set(argIndex);
5569       const Expr *Arg = getDataArg(argIndex);
5570       if (!Arg)
5571         return false;
5572 
5573       QualType T = Arg->getType();
5574 
5575       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5576       assert(AT.isValid());
5577 
5578       if (!AT.matchesType(S.Context, T)) {
5579         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5580                                << k << AT.getRepresentativeTypeName(S.Context)
5581                                << T << Arg->getSourceRange(),
5582                              getLocationOfByte(Amt.getStart()),
5583                              /*IsStringLocation*/true,
5584                              getSpecifierRange(startSpecifier, specifierLen));
5585         // Don't do any more checking.  We will just emit
5586         // spurious errors.
5587         return false;
5588       }
5589     }
5590   }
5591   return true;
5592 }
5593 
5594 void CheckPrintfHandler::HandleInvalidAmount(
5595                                       const analyze_printf::PrintfSpecifier &FS,
5596                                       const analyze_printf::OptionalAmount &Amt,
5597                                       unsigned type,
5598                                       const char *startSpecifier,
5599                                       unsigned specifierLen) {
5600   const analyze_printf::PrintfConversionSpecifier &CS =
5601     FS.getConversionSpecifier();
5602 
5603   FixItHint fixit =
5604     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5605       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5606                                  Amt.getConstantLength()))
5607       : FixItHint();
5608 
5609   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5610                          << type << CS.toString(),
5611                        getLocationOfByte(Amt.getStart()),
5612                        /*IsStringLocation*/true,
5613                        getSpecifierRange(startSpecifier, specifierLen),
5614                        fixit);
5615 }
5616 
5617 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5618                                     const analyze_printf::OptionalFlag &flag,
5619                                     const char *startSpecifier,
5620                                     unsigned specifierLen) {
5621   // Warn about pointless flag with a fixit removal.
5622   const analyze_printf::PrintfConversionSpecifier &CS =
5623     FS.getConversionSpecifier();
5624   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5625                          << flag.toString() << CS.toString(),
5626                        getLocationOfByte(flag.getPosition()),
5627                        /*IsStringLocation*/true,
5628                        getSpecifierRange(startSpecifier, specifierLen),
5629                        FixItHint::CreateRemoval(
5630                          getSpecifierRange(flag.getPosition(), 1)));
5631 }
5632 
5633 void CheckPrintfHandler::HandleIgnoredFlag(
5634                                 const analyze_printf::PrintfSpecifier &FS,
5635                                 const analyze_printf::OptionalFlag &ignoredFlag,
5636                                 const analyze_printf::OptionalFlag &flag,
5637                                 const char *startSpecifier,
5638                                 unsigned specifierLen) {
5639   // Warn about ignored flag with a fixit removal.
5640   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5641                          << ignoredFlag.toString() << flag.toString(),
5642                        getLocationOfByte(ignoredFlag.getPosition()),
5643                        /*IsStringLocation*/true,
5644                        getSpecifierRange(startSpecifier, specifierLen),
5645                        FixItHint::CreateRemoval(
5646                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5647 }
5648 
5649 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5650 //                            bool IsStringLocation, Range StringRange,
5651 //                            ArrayRef<FixItHint> Fixit = None);
5652 
5653 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5654                                                      unsigned flagLen) {
5655   // Warn about an empty flag.
5656   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5657                        getLocationOfByte(startFlag),
5658                        /*IsStringLocation*/true,
5659                        getSpecifierRange(startFlag, flagLen));
5660 }
5661 
5662 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5663                                                        unsigned flagLen) {
5664   // Warn about an invalid flag.
5665   auto Range = getSpecifierRange(startFlag, flagLen);
5666   StringRef flag(startFlag, flagLen);
5667   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5668                       getLocationOfByte(startFlag),
5669                       /*IsStringLocation*/true,
5670                       Range, FixItHint::CreateRemoval(Range));
5671 }
5672 
5673 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5674     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5675     // Warn about using '[...]' without a '@' conversion.
5676     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5677     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5678     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5679                          getLocationOfByte(conversionPosition),
5680                          /*IsStringLocation*/true,
5681                          Range, FixItHint::CreateRemoval(Range));
5682 }
5683 
5684 // Determines if the specified is a C++ class or struct containing
5685 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5686 // "c_str()").
5687 template<typename MemberKind>
5688 static llvm::SmallPtrSet<MemberKind*, 1>
5689 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5690   const RecordType *RT = Ty->getAs<RecordType>();
5691   llvm::SmallPtrSet<MemberKind*, 1> Results;
5692 
5693   if (!RT)
5694     return Results;
5695   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5696   if (!RD || !RD->getDefinition())
5697     return Results;
5698 
5699   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5700                  Sema::LookupMemberName);
5701   R.suppressDiagnostics();
5702 
5703   // We just need to include all members of the right kind turned up by the
5704   // filter, at this point.
5705   if (S.LookupQualifiedName(R, RT->getDecl()))
5706     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5707       NamedDecl *decl = (*I)->getUnderlyingDecl();
5708       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5709         Results.insert(FK);
5710     }
5711   return Results;
5712 }
5713 
5714 /// Check if we could call '.c_str()' on an object.
5715 ///
5716 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5717 /// allow the call, or if it would be ambiguous).
5718 bool Sema::hasCStrMethod(const Expr *E) {
5719   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5720   MethodSet Results =
5721       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5722   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5723        MI != ME; ++MI)
5724     if ((*MI)->getMinRequiredArguments() == 0)
5725       return true;
5726   return false;
5727 }
5728 
5729 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5730 // better diagnostic if so. AT is assumed to be valid.
5731 // Returns true when a c_str() conversion method is found.
5732 bool CheckPrintfHandler::checkForCStrMembers(
5733     const analyze_printf::ArgType &AT, const Expr *E) {
5734   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5735 
5736   MethodSet Results =
5737       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5738 
5739   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5740        MI != ME; ++MI) {
5741     const CXXMethodDecl *Method = *MI;
5742     if (Method->getMinRequiredArguments() == 0 &&
5743         AT.matchesType(S.Context, Method->getReturnType())) {
5744       // FIXME: Suggest parens if the expression needs them.
5745       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5746       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5747           << "c_str()"
5748           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5749       return true;
5750     }
5751   }
5752 
5753   return false;
5754 }
5755 
5756 bool
5757 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5758                                             &FS,
5759                                           const char *startSpecifier,
5760                                           unsigned specifierLen) {
5761   using namespace analyze_format_string;
5762   using namespace analyze_printf;
5763   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5764 
5765   if (FS.consumesDataArgument()) {
5766     if (atFirstArg) {
5767         atFirstArg = false;
5768         usesPositionalArgs = FS.usesPositionalArg();
5769     }
5770     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5771       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5772                                         startSpecifier, specifierLen);
5773       return false;
5774     }
5775   }
5776 
5777   // First check if the field width, precision, and conversion specifier
5778   // have matching data arguments.
5779   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5780                     startSpecifier, specifierLen)) {
5781     return false;
5782   }
5783 
5784   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5785                     startSpecifier, specifierLen)) {
5786     return false;
5787   }
5788 
5789   if (!CS.consumesDataArgument()) {
5790     // FIXME: Technically specifying a precision or field width here
5791     // makes no sense.  Worth issuing a warning at some point.
5792     return true;
5793   }
5794 
5795   // Consume the argument.
5796   unsigned argIndex = FS.getArgIndex();
5797   if (argIndex < NumDataArgs) {
5798     // The check to see if the argIndex is valid will come later.
5799     // We set the bit here because we may exit early from this
5800     // function if we encounter some other error.
5801     CoveredArgs.set(argIndex);
5802   }
5803 
5804   // FreeBSD kernel extensions.
5805   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5806       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5807     // We need at least two arguments.
5808     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5809       return false;
5810 
5811     // Claim the second argument.
5812     CoveredArgs.set(argIndex + 1);
5813 
5814     // Type check the first argument (int for %b, pointer for %D)
5815     const Expr *Ex = getDataArg(argIndex);
5816     const analyze_printf::ArgType &AT =
5817       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5818         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5819     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5820       EmitFormatDiagnostic(
5821         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5822         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5823         << false << Ex->getSourceRange(),
5824         Ex->getLocStart(), /*IsStringLocation*/false,
5825         getSpecifierRange(startSpecifier, specifierLen));
5826 
5827     // Type check the second argument (char * for both %b and %D)
5828     Ex = getDataArg(argIndex + 1);
5829     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5830     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5831       EmitFormatDiagnostic(
5832         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5833         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5834         << false << Ex->getSourceRange(),
5835         Ex->getLocStart(), /*IsStringLocation*/false,
5836         getSpecifierRange(startSpecifier, specifierLen));
5837 
5838      return true;
5839   }
5840 
5841   // Check for using an Objective-C specific conversion specifier
5842   // in a non-ObjC literal.
5843   if (!allowsObjCArg() && CS.isObjCArg()) {
5844     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5845                                                   specifierLen);
5846   }
5847 
5848   // %P can only be used with os_log.
5849   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5850     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5851                                                   specifierLen);
5852   }
5853 
5854   // %n is not allowed with os_log.
5855   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5856     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5857                          getLocationOfByte(CS.getStart()),
5858                          /*IsStringLocation*/ false,
5859                          getSpecifierRange(startSpecifier, specifierLen));
5860 
5861     return true;
5862   }
5863 
5864   // Only scalars are allowed for os_trace.
5865   if (FSType == Sema::FST_OSTrace &&
5866       (CS.getKind() == ConversionSpecifier::PArg ||
5867        CS.getKind() == ConversionSpecifier::sArg ||
5868        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5869     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5870                                                   specifierLen);
5871   }
5872 
5873   // Check for use of public/private annotation outside of os_log().
5874   if (FSType != Sema::FST_OSLog) {
5875     if (FS.isPublic().isSet()) {
5876       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5877                                << "public",
5878                            getLocationOfByte(FS.isPublic().getPosition()),
5879                            /*IsStringLocation*/ false,
5880                            getSpecifierRange(startSpecifier, specifierLen));
5881     }
5882     if (FS.isPrivate().isSet()) {
5883       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5884                                << "private",
5885                            getLocationOfByte(FS.isPrivate().getPosition()),
5886                            /*IsStringLocation*/ false,
5887                            getSpecifierRange(startSpecifier, specifierLen));
5888     }
5889   }
5890 
5891   // Check for invalid use of field width
5892   if (!FS.hasValidFieldWidth()) {
5893     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5894         startSpecifier, specifierLen);
5895   }
5896 
5897   // Check for invalid use of precision
5898   if (!FS.hasValidPrecision()) {
5899     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5900         startSpecifier, specifierLen);
5901   }
5902 
5903   // Precision is mandatory for %P specifier.
5904   if (CS.getKind() == ConversionSpecifier::PArg &&
5905       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5906     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5907                          getLocationOfByte(startSpecifier),
5908                          /*IsStringLocation*/ false,
5909                          getSpecifierRange(startSpecifier, specifierLen));
5910   }
5911 
5912   // Check each flag does not conflict with any other component.
5913   if (!FS.hasValidThousandsGroupingPrefix())
5914     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5915   if (!FS.hasValidLeadingZeros())
5916     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5917   if (!FS.hasValidPlusPrefix())
5918     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5919   if (!FS.hasValidSpacePrefix())
5920     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5921   if (!FS.hasValidAlternativeForm())
5922     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5923   if (!FS.hasValidLeftJustified())
5924     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5925 
5926   // Check that flags are not ignored by another flag
5927   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5928     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5929         startSpecifier, specifierLen);
5930   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5931     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5932             startSpecifier, specifierLen);
5933 
5934   // Check the length modifier is valid with the given conversion specifier.
5935   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5936     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5937                                 diag::warn_format_nonsensical_length);
5938   else if (!FS.hasStandardLengthModifier())
5939     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5940   else if (!FS.hasStandardLengthConversionCombination())
5941     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5942                                 diag::warn_format_non_standard_conversion_spec);
5943 
5944   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5945     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5946 
5947   // The remaining checks depend on the data arguments.
5948   if (HasVAListArg)
5949     return true;
5950 
5951   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5952     return false;
5953 
5954   const Expr *Arg = getDataArg(argIndex);
5955   if (!Arg)
5956     return true;
5957 
5958   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5959 }
5960 
5961 static bool requiresParensToAddCast(const Expr *E) {
5962   // FIXME: We should have a general way to reason about operator
5963   // precedence and whether parens are actually needed here.
5964   // Take care of a few common cases where they aren't.
5965   const Expr *Inside = E->IgnoreImpCasts();
5966   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5967     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5968 
5969   switch (Inside->getStmtClass()) {
5970   case Stmt::ArraySubscriptExprClass:
5971   case Stmt::CallExprClass:
5972   case Stmt::CharacterLiteralClass:
5973   case Stmt::CXXBoolLiteralExprClass:
5974   case Stmt::DeclRefExprClass:
5975   case Stmt::FloatingLiteralClass:
5976   case Stmt::IntegerLiteralClass:
5977   case Stmt::MemberExprClass:
5978   case Stmt::ObjCArrayLiteralClass:
5979   case Stmt::ObjCBoolLiteralExprClass:
5980   case Stmt::ObjCBoxedExprClass:
5981   case Stmt::ObjCDictionaryLiteralClass:
5982   case Stmt::ObjCEncodeExprClass:
5983   case Stmt::ObjCIvarRefExprClass:
5984   case Stmt::ObjCMessageExprClass:
5985   case Stmt::ObjCPropertyRefExprClass:
5986   case Stmt::ObjCStringLiteralClass:
5987   case Stmt::ObjCSubscriptRefExprClass:
5988   case Stmt::ParenExprClass:
5989   case Stmt::StringLiteralClass:
5990   case Stmt::UnaryOperatorClass:
5991     return false;
5992   default:
5993     return true;
5994   }
5995 }
5996 
5997 static std::pair<QualType, StringRef>
5998 shouldNotPrintDirectly(const ASTContext &Context,
5999                        QualType IntendedTy,
6000                        const Expr *E) {
6001   // Use a 'while' to peel off layers of typedefs.
6002   QualType TyTy = IntendedTy;
6003   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6004     StringRef Name = UserTy->getDecl()->getName();
6005     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6006       .Case("CFIndex", Context.LongTy)
6007       .Case("NSInteger", Context.LongTy)
6008       .Case("NSUInteger", Context.UnsignedLongTy)
6009       .Case("SInt32", Context.IntTy)
6010       .Case("UInt32", Context.UnsignedIntTy)
6011       .Default(QualType());
6012 
6013     if (!CastTy.isNull())
6014       return std::make_pair(CastTy, Name);
6015 
6016     TyTy = UserTy->desugar();
6017   }
6018 
6019   // Strip parens if necessary.
6020   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6021     return shouldNotPrintDirectly(Context,
6022                                   PE->getSubExpr()->getType(),
6023                                   PE->getSubExpr());
6024 
6025   // If this is a conditional expression, then its result type is constructed
6026   // via usual arithmetic conversions and thus there might be no necessary
6027   // typedef sugar there.  Recurse to operands to check for NSInteger &
6028   // Co. usage condition.
6029   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6030     QualType TrueTy, FalseTy;
6031     StringRef TrueName, FalseName;
6032 
6033     std::tie(TrueTy, TrueName) =
6034       shouldNotPrintDirectly(Context,
6035                              CO->getTrueExpr()->getType(),
6036                              CO->getTrueExpr());
6037     std::tie(FalseTy, FalseName) =
6038       shouldNotPrintDirectly(Context,
6039                              CO->getFalseExpr()->getType(),
6040                              CO->getFalseExpr());
6041 
6042     if (TrueTy == FalseTy)
6043       return std::make_pair(TrueTy, TrueName);
6044     else if (TrueTy.isNull())
6045       return std::make_pair(FalseTy, FalseName);
6046     else if (FalseTy.isNull())
6047       return std::make_pair(TrueTy, TrueName);
6048   }
6049 
6050   return std::make_pair(QualType(), StringRef());
6051 }
6052 
6053 bool
6054 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6055                                     const char *StartSpecifier,
6056                                     unsigned SpecifierLen,
6057                                     const Expr *E) {
6058   using namespace analyze_format_string;
6059   using namespace analyze_printf;
6060   // Now type check the data expression that matches the
6061   // format specifier.
6062   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6063   if (!AT.isValid())
6064     return true;
6065 
6066   QualType ExprTy = E->getType();
6067   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6068     ExprTy = TET->getUnderlyingExpr()->getType();
6069   }
6070 
6071   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6072 
6073   if (match == analyze_printf::ArgType::Match) {
6074     return true;
6075   }
6076 
6077   // Look through argument promotions for our error message's reported type.
6078   // This includes the integral and floating promotions, but excludes array
6079   // and function pointer decay; seeing that an argument intended to be a
6080   // string has type 'char [6]' is probably more confusing than 'char *'.
6081   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6082     if (ICE->getCastKind() == CK_IntegralCast ||
6083         ICE->getCastKind() == CK_FloatingCast) {
6084       E = ICE->getSubExpr();
6085       ExprTy = E->getType();
6086 
6087       // Check if we didn't match because of an implicit cast from a 'char'
6088       // or 'short' to an 'int'.  This is done because printf is a varargs
6089       // function.
6090       if (ICE->getType() == S.Context.IntTy ||
6091           ICE->getType() == S.Context.UnsignedIntTy) {
6092         // All further checking is done on the subexpression.
6093         if (AT.matchesType(S.Context, ExprTy))
6094           return true;
6095       }
6096     }
6097   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6098     // Special case for 'a', which has type 'int' in C.
6099     // Note, however, that we do /not/ want to treat multibyte constants like
6100     // 'MooV' as characters! This form is deprecated but still exists.
6101     if (ExprTy == S.Context.IntTy)
6102       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6103         ExprTy = S.Context.CharTy;
6104   }
6105 
6106   // Look through enums to their underlying type.
6107   bool IsEnum = false;
6108   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6109     ExprTy = EnumTy->getDecl()->getIntegerType();
6110     IsEnum = true;
6111   }
6112 
6113   // %C in an Objective-C context prints a unichar, not a wchar_t.
6114   // If the argument is an integer of some kind, believe the %C and suggest
6115   // a cast instead of changing the conversion specifier.
6116   QualType IntendedTy = ExprTy;
6117   if (isObjCContext() &&
6118       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6119     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6120         !ExprTy->isCharType()) {
6121       // 'unichar' is defined as a typedef of unsigned short, but we should
6122       // prefer using the typedef if it is visible.
6123       IntendedTy = S.Context.UnsignedShortTy;
6124 
6125       // While we are here, check if the value is an IntegerLiteral that happens
6126       // to be within the valid range.
6127       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6128         const llvm::APInt &V = IL->getValue();
6129         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6130           return true;
6131       }
6132 
6133       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6134                           Sema::LookupOrdinaryName);
6135       if (S.LookupName(Result, S.getCurScope())) {
6136         NamedDecl *ND = Result.getFoundDecl();
6137         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6138           if (TD->getUnderlyingType() == IntendedTy)
6139             IntendedTy = S.Context.getTypedefType(TD);
6140       }
6141     }
6142   }
6143 
6144   // Special-case some of Darwin's platform-independence types by suggesting
6145   // casts to primitive types that are known to be large enough.
6146   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6147   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6148     QualType CastTy;
6149     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6150     if (!CastTy.isNull()) {
6151       IntendedTy = CastTy;
6152       ShouldNotPrintDirectly = true;
6153     }
6154   }
6155 
6156   // We may be able to offer a FixItHint if it is a supported type.
6157   PrintfSpecifier fixedFS = FS;
6158   bool success =
6159       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6160 
6161   if (success) {
6162     // Get the fix string from the fixed format specifier
6163     SmallString<16> buf;
6164     llvm::raw_svector_ostream os(buf);
6165     fixedFS.toString(os);
6166 
6167     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6168 
6169     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6170       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6171       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6172         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6173       }
6174       // In this case, the specifier is wrong and should be changed to match
6175       // the argument.
6176       EmitFormatDiagnostic(S.PDiag(diag)
6177                                << AT.getRepresentativeTypeName(S.Context)
6178                                << IntendedTy << IsEnum << E->getSourceRange(),
6179                            E->getLocStart(),
6180                            /*IsStringLocation*/ false, SpecRange,
6181                            FixItHint::CreateReplacement(SpecRange, os.str()));
6182     } else {
6183       // The canonical type for formatting this value is different from the
6184       // actual type of the expression. (This occurs, for example, with Darwin's
6185       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6186       // should be printed as 'long' for 64-bit compatibility.)
6187       // Rather than emitting a normal format/argument mismatch, we want to
6188       // add a cast to the recommended type (and correct the format string
6189       // if necessary).
6190       SmallString<16> CastBuf;
6191       llvm::raw_svector_ostream CastFix(CastBuf);
6192       CastFix << "(";
6193       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6194       CastFix << ")";
6195 
6196       SmallVector<FixItHint,4> Hints;
6197       if (!AT.matchesType(S.Context, IntendedTy))
6198         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6199 
6200       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6201         // If there's already a cast present, just replace it.
6202         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6203         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6204 
6205       } else if (!requiresParensToAddCast(E)) {
6206         // If the expression has high enough precedence,
6207         // just write the C-style cast.
6208         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6209                                                    CastFix.str()));
6210       } else {
6211         // Otherwise, add parens around the expression as well as the cast.
6212         CastFix << "(";
6213         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6214                                                    CastFix.str()));
6215 
6216         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6217         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6218       }
6219 
6220       if (ShouldNotPrintDirectly) {
6221         // The expression has a type that should not be printed directly.
6222         // We extract the name from the typedef because we don't want to show
6223         // the underlying type in the diagnostic.
6224         StringRef Name;
6225         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6226           Name = TypedefTy->getDecl()->getName();
6227         else
6228           Name = CastTyName;
6229         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6230                                << Name << IntendedTy << IsEnum
6231                                << E->getSourceRange(),
6232                              E->getLocStart(), /*IsStringLocation=*/false,
6233                              SpecRange, Hints);
6234       } else {
6235         // In this case, the expression could be printed using a different
6236         // specifier, but we've decided that the specifier is probably correct
6237         // and we should cast instead. Just use the normal warning message.
6238         EmitFormatDiagnostic(
6239           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6240             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6241             << E->getSourceRange(),
6242           E->getLocStart(), /*IsStringLocation*/false,
6243           SpecRange, Hints);
6244       }
6245     }
6246   } else {
6247     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6248                                                    SpecifierLen);
6249     // Since the warning for passing non-POD types to variadic functions
6250     // was deferred until now, we emit a warning for non-POD
6251     // arguments here.
6252     switch (S.isValidVarArgType(ExprTy)) {
6253     case Sema::VAK_Valid:
6254     case Sema::VAK_ValidInCXX11: {
6255       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6256       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6257         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6258       }
6259 
6260       EmitFormatDiagnostic(
6261           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6262                         << IsEnum << CSR << E->getSourceRange(),
6263           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6264       break;
6265     }
6266     case Sema::VAK_Undefined:
6267     case Sema::VAK_MSVCUndefined:
6268       EmitFormatDiagnostic(
6269         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6270           << S.getLangOpts().CPlusPlus11
6271           << ExprTy
6272           << CallType
6273           << AT.getRepresentativeTypeName(S.Context)
6274           << CSR
6275           << E->getSourceRange(),
6276         E->getLocStart(), /*IsStringLocation*/false, CSR);
6277       checkForCStrMembers(AT, E);
6278       break;
6279 
6280     case Sema::VAK_Invalid:
6281       if (ExprTy->isObjCObjectType())
6282         EmitFormatDiagnostic(
6283           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6284             << S.getLangOpts().CPlusPlus11
6285             << ExprTy
6286             << CallType
6287             << AT.getRepresentativeTypeName(S.Context)
6288             << CSR
6289             << E->getSourceRange(),
6290           E->getLocStart(), /*IsStringLocation*/false, CSR);
6291       else
6292         // FIXME: If this is an initializer list, suggest removing the braces
6293         // or inserting a cast to the target type.
6294         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6295           << isa<InitListExpr>(E) << ExprTy << CallType
6296           << AT.getRepresentativeTypeName(S.Context)
6297           << E->getSourceRange();
6298       break;
6299     }
6300 
6301     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6302            "format string specifier index out of range");
6303     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6304   }
6305 
6306   return true;
6307 }
6308 
6309 //===--- CHECK: Scanf format string checking ------------------------------===//
6310 
6311 namespace {
6312 class CheckScanfHandler : public CheckFormatHandler {
6313 public:
6314   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6315                     const Expr *origFormatExpr, Sema::FormatStringType type,
6316                     unsigned firstDataArg, unsigned numDataArgs,
6317                     const char *beg, bool hasVAListArg,
6318                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6319                     bool inFunctionCall, Sema::VariadicCallType CallType,
6320                     llvm::SmallBitVector &CheckedVarArgs,
6321                     UncoveredArgHandler &UncoveredArg)
6322       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6323                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6324                            inFunctionCall, CallType, CheckedVarArgs,
6325                            UncoveredArg) {}
6326 
6327   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6328                             const char *startSpecifier,
6329                             unsigned specifierLen) override;
6330 
6331   bool HandleInvalidScanfConversionSpecifier(
6332           const analyze_scanf::ScanfSpecifier &FS,
6333           const char *startSpecifier,
6334           unsigned specifierLen) override;
6335 
6336   void HandleIncompleteScanList(const char *start, const char *end) override;
6337 };
6338 } // end anonymous namespace
6339 
6340 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6341                                                  const char *end) {
6342   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6343                        getLocationOfByte(end), /*IsStringLocation*/true,
6344                        getSpecifierRange(start, end - start));
6345 }
6346 
6347 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6348                                         const analyze_scanf::ScanfSpecifier &FS,
6349                                         const char *startSpecifier,
6350                                         unsigned specifierLen) {
6351 
6352   const analyze_scanf::ScanfConversionSpecifier &CS =
6353     FS.getConversionSpecifier();
6354 
6355   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6356                                           getLocationOfByte(CS.getStart()),
6357                                           startSpecifier, specifierLen,
6358                                           CS.getStart(), CS.getLength());
6359 }
6360 
6361 bool CheckScanfHandler::HandleScanfSpecifier(
6362                                        const analyze_scanf::ScanfSpecifier &FS,
6363                                        const char *startSpecifier,
6364                                        unsigned specifierLen) {
6365   using namespace analyze_scanf;
6366   using namespace analyze_format_string;
6367 
6368   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6369 
6370   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6371   // be used to decide if we are using positional arguments consistently.
6372   if (FS.consumesDataArgument()) {
6373     if (atFirstArg) {
6374       atFirstArg = false;
6375       usesPositionalArgs = FS.usesPositionalArg();
6376     }
6377     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6378       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6379                                         startSpecifier, specifierLen);
6380       return false;
6381     }
6382   }
6383 
6384   // Check if the field with is non-zero.
6385   const OptionalAmount &Amt = FS.getFieldWidth();
6386   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6387     if (Amt.getConstantAmount() == 0) {
6388       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6389                                                    Amt.getConstantLength());
6390       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6391                            getLocationOfByte(Amt.getStart()),
6392                            /*IsStringLocation*/true, R,
6393                            FixItHint::CreateRemoval(R));
6394     }
6395   }
6396 
6397   if (!FS.consumesDataArgument()) {
6398     // FIXME: Technically specifying a precision or field width here
6399     // makes no sense.  Worth issuing a warning at some point.
6400     return true;
6401   }
6402 
6403   // Consume the argument.
6404   unsigned argIndex = FS.getArgIndex();
6405   if (argIndex < NumDataArgs) {
6406       // The check to see if the argIndex is valid will come later.
6407       // We set the bit here because we may exit early from this
6408       // function if we encounter some other error.
6409     CoveredArgs.set(argIndex);
6410   }
6411 
6412   // Check the length modifier is valid with the given conversion specifier.
6413   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6414     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6415                                 diag::warn_format_nonsensical_length);
6416   else if (!FS.hasStandardLengthModifier())
6417     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6418   else if (!FS.hasStandardLengthConversionCombination())
6419     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6420                                 diag::warn_format_non_standard_conversion_spec);
6421 
6422   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6423     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6424 
6425   // The remaining checks depend on the data arguments.
6426   if (HasVAListArg)
6427     return true;
6428 
6429   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6430     return false;
6431 
6432   // Check that the argument type matches the format specifier.
6433   const Expr *Ex = getDataArg(argIndex);
6434   if (!Ex)
6435     return true;
6436 
6437   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6438 
6439   if (!AT.isValid()) {
6440     return true;
6441   }
6442 
6443   analyze_format_string::ArgType::MatchKind match =
6444       AT.matchesType(S.Context, Ex->getType());
6445   if (match == analyze_format_string::ArgType::Match) {
6446     return true;
6447   }
6448 
6449   ScanfSpecifier fixedFS = FS;
6450   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6451                                  S.getLangOpts(), S.Context);
6452 
6453   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6454   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6455     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6456   }
6457 
6458   if (success) {
6459     // Get the fix string from the fixed format specifier.
6460     SmallString<128> buf;
6461     llvm::raw_svector_ostream os(buf);
6462     fixedFS.toString(os);
6463 
6464     EmitFormatDiagnostic(
6465         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6466                       << Ex->getType() << false << Ex->getSourceRange(),
6467         Ex->getLocStart(),
6468         /*IsStringLocation*/ false,
6469         getSpecifierRange(startSpecifier, specifierLen),
6470         FixItHint::CreateReplacement(
6471             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6472   } else {
6473     EmitFormatDiagnostic(S.PDiag(diag)
6474                              << AT.getRepresentativeTypeName(S.Context)
6475                              << Ex->getType() << false << Ex->getSourceRange(),
6476                          Ex->getLocStart(),
6477                          /*IsStringLocation*/ false,
6478                          getSpecifierRange(startSpecifier, specifierLen));
6479   }
6480 
6481   return true;
6482 }
6483 
6484 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6485                               const Expr *OrigFormatExpr,
6486                               ArrayRef<const Expr *> Args,
6487                               bool HasVAListArg, unsigned format_idx,
6488                               unsigned firstDataArg,
6489                               Sema::FormatStringType Type,
6490                               bool inFunctionCall,
6491                               Sema::VariadicCallType CallType,
6492                               llvm::SmallBitVector &CheckedVarArgs,
6493                               UncoveredArgHandler &UncoveredArg) {
6494   // CHECK: is the format string a wide literal?
6495   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6496     CheckFormatHandler::EmitFormatDiagnostic(
6497       S, inFunctionCall, Args[format_idx],
6498       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6499       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6500     return;
6501   }
6502 
6503   // Str - The format string.  NOTE: this is NOT null-terminated!
6504   StringRef StrRef = FExpr->getString();
6505   const char *Str = StrRef.data();
6506   // Account for cases where the string literal is truncated in a declaration.
6507   const ConstantArrayType *T =
6508     S.Context.getAsConstantArrayType(FExpr->getType());
6509   assert(T && "String literal not of constant array type!");
6510   size_t TypeSize = T->getSize().getZExtValue();
6511   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6512   const unsigned numDataArgs = Args.size() - firstDataArg;
6513 
6514   // Emit a warning if the string literal is truncated and does not contain an
6515   // embedded null character.
6516   if (TypeSize <= StrRef.size() &&
6517       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6518     CheckFormatHandler::EmitFormatDiagnostic(
6519         S, inFunctionCall, Args[format_idx],
6520         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6521         FExpr->getLocStart(),
6522         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6523     return;
6524   }
6525 
6526   // CHECK: empty format string?
6527   if (StrLen == 0 && numDataArgs > 0) {
6528     CheckFormatHandler::EmitFormatDiagnostic(
6529       S, inFunctionCall, Args[format_idx],
6530       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6531       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6532     return;
6533   }
6534 
6535   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6536       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6537       Type == Sema::FST_OSTrace) {
6538     CheckPrintfHandler H(
6539         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6540         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6541         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6542         CheckedVarArgs, UncoveredArg);
6543 
6544     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6545                                                   S.getLangOpts(),
6546                                                   S.Context.getTargetInfo(),
6547                                             Type == Sema::FST_FreeBSDKPrintf))
6548       H.DoneProcessing();
6549   } else if (Type == Sema::FST_Scanf) {
6550     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6551                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6552                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6553 
6554     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6555                                                  S.getLangOpts(),
6556                                                  S.Context.getTargetInfo()))
6557       H.DoneProcessing();
6558   } // TODO: handle other formats
6559 }
6560 
6561 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6562   // Str - The format string.  NOTE: this is NOT null-terminated!
6563   StringRef StrRef = FExpr->getString();
6564   const char *Str = StrRef.data();
6565   // Account for cases where the string literal is truncated in a declaration.
6566   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6567   assert(T && "String literal not of constant array type!");
6568   size_t TypeSize = T->getSize().getZExtValue();
6569   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6570   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6571                                                          getLangOpts(),
6572                                                          Context.getTargetInfo());
6573 }
6574 
6575 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6576 
6577 // Returns the related absolute value function that is larger, of 0 if one
6578 // does not exist.
6579 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6580   switch (AbsFunction) {
6581   default:
6582     return 0;
6583 
6584   case Builtin::BI__builtin_abs:
6585     return Builtin::BI__builtin_labs;
6586   case Builtin::BI__builtin_labs:
6587     return Builtin::BI__builtin_llabs;
6588   case Builtin::BI__builtin_llabs:
6589     return 0;
6590 
6591   case Builtin::BI__builtin_fabsf:
6592     return Builtin::BI__builtin_fabs;
6593   case Builtin::BI__builtin_fabs:
6594     return Builtin::BI__builtin_fabsl;
6595   case Builtin::BI__builtin_fabsl:
6596     return 0;
6597 
6598   case Builtin::BI__builtin_cabsf:
6599     return Builtin::BI__builtin_cabs;
6600   case Builtin::BI__builtin_cabs:
6601     return Builtin::BI__builtin_cabsl;
6602   case Builtin::BI__builtin_cabsl:
6603     return 0;
6604 
6605   case Builtin::BIabs:
6606     return Builtin::BIlabs;
6607   case Builtin::BIlabs:
6608     return Builtin::BIllabs;
6609   case Builtin::BIllabs:
6610     return 0;
6611 
6612   case Builtin::BIfabsf:
6613     return Builtin::BIfabs;
6614   case Builtin::BIfabs:
6615     return Builtin::BIfabsl;
6616   case Builtin::BIfabsl:
6617     return 0;
6618 
6619   case Builtin::BIcabsf:
6620    return Builtin::BIcabs;
6621   case Builtin::BIcabs:
6622     return Builtin::BIcabsl;
6623   case Builtin::BIcabsl:
6624     return 0;
6625   }
6626 }
6627 
6628 // Returns the argument type of the absolute value function.
6629 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6630                                              unsigned AbsType) {
6631   if (AbsType == 0)
6632     return QualType();
6633 
6634   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6635   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6636   if (Error != ASTContext::GE_None)
6637     return QualType();
6638 
6639   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6640   if (!FT)
6641     return QualType();
6642 
6643   if (FT->getNumParams() != 1)
6644     return QualType();
6645 
6646   return FT->getParamType(0);
6647 }
6648 
6649 // Returns the best absolute value function, or zero, based on type and
6650 // current absolute value function.
6651 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6652                                    unsigned AbsFunctionKind) {
6653   unsigned BestKind = 0;
6654   uint64_t ArgSize = Context.getTypeSize(ArgType);
6655   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6656        Kind = getLargerAbsoluteValueFunction(Kind)) {
6657     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6658     if (Context.getTypeSize(ParamType) >= ArgSize) {
6659       if (BestKind == 0)
6660         BestKind = Kind;
6661       else if (Context.hasSameType(ParamType, ArgType)) {
6662         BestKind = Kind;
6663         break;
6664       }
6665     }
6666   }
6667   return BestKind;
6668 }
6669 
6670 enum AbsoluteValueKind {
6671   AVK_Integer,
6672   AVK_Floating,
6673   AVK_Complex
6674 };
6675 
6676 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6677   if (T->isIntegralOrEnumerationType())
6678     return AVK_Integer;
6679   if (T->isRealFloatingType())
6680     return AVK_Floating;
6681   if (T->isAnyComplexType())
6682     return AVK_Complex;
6683 
6684   llvm_unreachable("Type not integer, floating, or complex");
6685 }
6686 
6687 // Changes the absolute value function to a different type.  Preserves whether
6688 // the function is a builtin.
6689 static unsigned changeAbsFunction(unsigned AbsKind,
6690                                   AbsoluteValueKind ValueKind) {
6691   switch (ValueKind) {
6692   case AVK_Integer:
6693     switch (AbsKind) {
6694     default:
6695       return 0;
6696     case Builtin::BI__builtin_fabsf:
6697     case Builtin::BI__builtin_fabs:
6698     case Builtin::BI__builtin_fabsl:
6699     case Builtin::BI__builtin_cabsf:
6700     case Builtin::BI__builtin_cabs:
6701     case Builtin::BI__builtin_cabsl:
6702       return Builtin::BI__builtin_abs;
6703     case Builtin::BIfabsf:
6704     case Builtin::BIfabs:
6705     case Builtin::BIfabsl:
6706     case Builtin::BIcabsf:
6707     case Builtin::BIcabs:
6708     case Builtin::BIcabsl:
6709       return Builtin::BIabs;
6710     }
6711   case AVK_Floating:
6712     switch (AbsKind) {
6713     default:
6714       return 0;
6715     case Builtin::BI__builtin_abs:
6716     case Builtin::BI__builtin_labs:
6717     case Builtin::BI__builtin_llabs:
6718     case Builtin::BI__builtin_cabsf:
6719     case Builtin::BI__builtin_cabs:
6720     case Builtin::BI__builtin_cabsl:
6721       return Builtin::BI__builtin_fabsf;
6722     case Builtin::BIabs:
6723     case Builtin::BIlabs:
6724     case Builtin::BIllabs:
6725     case Builtin::BIcabsf:
6726     case Builtin::BIcabs:
6727     case Builtin::BIcabsl:
6728       return Builtin::BIfabsf;
6729     }
6730   case AVK_Complex:
6731     switch (AbsKind) {
6732     default:
6733       return 0;
6734     case Builtin::BI__builtin_abs:
6735     case Builtin::BI__builtin_labs:
6736     case Builtin::BI__builtin_llabs:
6737     case Builtin::BI__builtin_fabsf:
6738     case Builtin::BI__builtin_fabs:
6739     case Builtin::BI__builtin_fabsl:
6740       return Builtin::BI__builtin_cabsf;
6741     case Builtin::BIabs:
6742     case Builtin::BIlabs:
6743     case Builtin::BIllabs:
6744     case Builtin::BIfabsf:
6745     case Builtin::BIfabs:
6746     case Builtin::BIfabsl:
6747       return Builtin::BIcabsf;
6748     }
6749   }
6750   llvm_unreachable("Unable to convert function");
6751 }
6752 
6753 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6754   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6755   if (!FnInfo)
6756     return 0;
6757 
6758   switch (FDecl->getBuiltinID()) {
6759   default:
6760     return 0;
6761   case Builtin::BI__builtin_abs:
6762   case Builtin::BI__builtin_fabs:
6763   case Builtin::BI__builtin_fabsf:
6764   case Builtin::BI__builtin_fabsl:
6765   case Builtin::BI__builtin_labs:
6766   case Builtin::BI__builtin_llabs:
6767   case Builtin::BI__builtin_cabs:
6768   case Builtin::BI__builtin_cabsf:
6769   case Builtin::BI__builtin_cabsl:
6770   case Builtin::BIabs:
6771   case Builtin::BIlabs:
6772   case Builtin::BIllabs:
6773   case Builtin::BIfabs:
6774   case Builtin::BIfabsf:
6775   case Builtin::BIfabsl:
6776   case Builtin::BIcabs:
6777   case Builtin::BIcabsf:
6778   case Builtin::BIcabsl:
6779     return FDecl->getBuiltinID();
6780   }
6781   llvm_unreachable("Unknown Builtin type");
6782 }
6783 
6784 // If the replacement is valid, emit a note with replacement function.
6785 // Additionally, suggest including the proper header if not already included.
6786 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6787                             unsigned AbsKind, QualType ArgType) {
6788   bool EmitHeaderHint = true;
6789   const char *HeaderName = nullptr;
6790   const char *FunctionName = nullptr;
6791   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6792     FunctionName = "std::abs";
6793     if (ArgType->isIntegralOrEnumerationType()) {
6794       HeaderName = "cstdlib";
6795     } else if (ArgType->isRealFloatingType()) {
6796       HeaderName = "cmath";
6797     } else {
6798       llvm_unreachable("Invalid Type");
6799     }
6800 
6801     // Lookup all std::abs
6802     if (NamespaceDecl *Std = S.getStdNamespace()) {
6803       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6804       R.suppressDiagnostics();
6805       S.LookupQualifiedName(R, Std);
6806 
6807       for (const auto *I : R) {
6808         const FunctionDecl *FDecl = nullptr;
6809         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6810           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6811         } else {
6812           FDecl = dyn_cast<FunctionDecl>(I);
6813         }
6814         if (!FDecl)
6815           continue;
6816 
6817         // Found std::abs(), check that they are the right ones.
6818         if (FDecl->getNumParams() != 1)
6819           continue;
6820 
6821         // Check that the parameter type can handle the argument.
6822         QualType ParamType = FDecl->getParamDecl(0)->getType();
6823         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6824             S.Context.getTypeSize(ArgType) <=
6825                 S.Context.getTypeSize(ParamType)) {
6826           // Found a function, don't need the header hint.
6827           EmitHeaderHint = false;
6828           break;
6829         }
6830       }
6831     }
6832   } else {
6833     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6834     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6835 
6836     if (HeaderName) {
6837       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6838       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6839       R.suppressDiagnostics();
6840       S.LookupName(R, S.getCurScope());
6841 
6842       if (R.isSingleResult()) {
6843         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6844         if (FD && FD->getBuiltinID() == AbsKind) {
6845           EmitHeaderHint = false;
6846         } else {
6847           return;
6848         }
6849       } else if (!R.empty()) {
6850         return;
6851       }
6852     }
6853   }
6854 
6855   S.Diag(Loc, diag::note_replace_abs_function)
6856       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6857 
6858   if (!HeaderName)
6859     return;
6860 
6861   if (!EmitHeaderHint)
6862     return;
6863 
6864   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6865                                                     << FunctionName;
6866 }
6867 
6868 template <std::size_t StrLen>
6869 static bool IsStdFunction(const FunctionDecl *FDecl,
6870                           const char (&Str)[StrLen]) {
6871   if (!FDecl)
6872     return false;
6873   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
6874     return false;
6875   if (!FDecl->isInStdNamespace())
6876     return false;
6877 
6878   return true;
6879 }
6880 
6881 // Warn when using the wrong abs() function.
6882 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6883                                       const FunctionDecl *FDecl) {
6884   if (Call->getNumArgs() != 1)
6885     return;
6886 
6887   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6888   bool IsStdAbs = IsStdFunction(FDecl, "abs");
6889   if (AbsKind == 0 && !IsStdAbs)
6890     return;
6891 
6892   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6893   QualType ParamType = Call->getArg(0)->getType();
6894 
6895   // Unsigned types cannot be negative.  Suggest removing the absolute value
6896   // function call.
6897   if (ArgType->isUnsignedIntegerType()) {
6898     const char *FunctionName =
6899         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6900     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6901     Diag(Call->getExprLoc(), diag::note_remove_abs)
6902         << FunctionName
6903         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6904     return;
6905   }
6906 
6907   // Taking the absolute value of a pointer is very suspicious, they probably
6908   // wanted to index into an array, dereference a pointer, call a function, etc.
6909   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6910     unsigned DiagType = 0;
6911     if (ArgType->isFunctionType())
6912       DiagType = 1;
6913     else if (ArgType->isArrayType())
6914       DiagType = 2;
6915 
6916     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6917     return;
6918   }
6919 
6920   // std::abs has overloads which prevent most of the absolute value problems
6921   // from occurring.
6922   if (IsStdAbs)
6923     return;
6924 
6925   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6926   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6927 
6928   // The argument and parameter are the same kind.  Check if they are the right
6929   // size.
6930   if (ArgValueKind == ParamValueKind) {
6931     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6932       return;
6933 
6934     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6935     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6936         << FDecl << ArgType << ParamType;
6937 
6938     if (NewAbsKind == 0)
6939       return;
6940 
6941     emitReplacement(*this, Call->getExprLoc(),
6942                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6943     return;
6944   }
6945 
6946   // ArgValueKind != ParamValueKind
6947   // The wrong type of absolute value function was used.  Attempt to find the
6948   // proper one.
6949   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6950   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6951   if (NewAbsKind == 0)
6952     return;
6953 
6954   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6955       << FDecl << ParamValueKind << ArgValueKind;
6956 
6957   emitReplacement(*this, Call->getExprLoc(),
6958                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6959 }
6960 
6961 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
6962 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6963                                 const FunctionDecl *FDecl) {
6964   if (!Call || !FDecl) return;
6965 
6966   // Ignore template specializations and macros.
6967   if (inTemplateInstantiation()) return;
6968   if (Call->getExprLoc().isMacroID()) return;
6969 
6970   // Only care about the one template argument, two function parameter std::max
6971   if (Call->getNumArgs() != 2) return;
6972   if (!IsStdFunction(FDecl, "max")) return;
6973   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6974   if (!ArgList) return;
6975   if (ArgList->size() != 1) return;
6976 
6977   // Check that template type argument is unsigned integer.
6978   const auto& TA = ArgList->get(0);
6979   if (TA.getKind() != TemplateArgument::Type) return;
6980   QualType ArgType = TA.getAsType();
6981   if (!ArgType->isUnsignedIntegerType()) return;
6982 
6983   // See if either argument is a literal zero.
6984   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6985     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6986     if (!MTE) return false;
6987     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6988     if (!Num) return false;
6989     if (Num->getValue() != 0) return false;
6990     return true;
6991   };
6992 
6993   const Expr *FirstArg = Call->getArg(0);
6994   const Expr *SecondArg = Call->getArg(1);
6995   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6996   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6997 
6998   // Only warn when exactly one argument is zero.
6999   if (IsFirstArgZero == IsSecondArgZero) return;
7000 
7001   SourceRange FirstRange = FirstArg->getSourceRange();
7002   SourceRange SecondRange = SecondArg->getSourceRange();
7003 
7004   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7005 
7006   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7007       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7008 
7009   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7010   SourceRange RemovalRange;
7011   if (IsFirstArgZero) {
7012     RemovalRange = SourceRange(FirstRange.getBegin(),
7013                                SecondRange.getBegin().getLocWithOffset(-1));
7014   } else {
7015     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7016                                SecondRange.getEnd());
7017   }
7018 
7019   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7020         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7021         << FixItHint::CreateRemoval(RemovalRange);
7022 }
7023 
7024 //===--- CHECK: Standard memory functions ---------------------------------===//
7025 
7026 /// \brief Takes the expression passed to the size_t parameter of functions
7027 /// such as memcmp, strncat, etc and warns if it's a comparison.
7028 ///
7029 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7030 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7031                                            IdentifierInfo *FnName,
7032                                            SourceLocation FnLoc,
7033                                            SourceLocation RParenLoc) {
7034   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7035   if (!Size)
7036     return false;
7037 
7038   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7039   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7040     return false;
7041 
7042   SourceRange SizeRange = Size->getSourceRange();
7043   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7044       << SizeRange << FnName;
7045   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7046       << FnName << FixItHint::CreateInsertion(
7047                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7048       << FixItHint::CreateRemoval(RParenLoc);
7049   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7050       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7051       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7052                                     ")");
7053 
7054   return true;
7055 }
7056 
7057 /// \brief Determine whether the given type is or contains a dynamic class type
7058 /// (e.g., whether it has a vtable).
7059 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7060                                                      bool &IsContained) {
7061   // Look through array types while ignoring qualifiers.
7062   const Type *Ty = T->getBaseElementTypeUnsafe();
7063   IsContained = false;
7064 
7065   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7066   RD = RD ? RD->getDefinition() : nullptr;
7067   if (!RD || RD->isInvalidDecl())
7068     return nullptr;
7069 
7070   if (RD->isDynamicClass())
7071     return RD;
7072 
7073   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7074   // It's impossible for a class to transitively contain itself by value, so
7075   // infinite recursion is impossible.
7076   for (auto *FD : RD->fields()) {
7077     bool SubContained;
7078     if (const CXXRecordDecl *ContainedRD =
7079             getContainedDynamicClass(FD->getType(), SubContained)) {
7080       IsContained = true;
7081       return ContainedRD;
7082     }
7083   }
7084 
7085   return nullptr;
7086 }
7087 
7088 /// \brief If E is a sizeof expression, returns its argument expression,
7089 /// otherwise returns NULL.
7090 static const Expr *getSizeOfExprArg(const Expr *E) {
7091   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7092       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7093     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7094       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7095 
7096   return nullptr;
7097 }
7098 
7099 /// \brief If E is a sizeof expression, returns its argument type.
7100 static QualType getSizeOfArgType(const Expr *E) {
7101   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7102       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7103     if (SizeOf->getKind() == clang::UETT_SizeOf)
7104       return SizeOf->getTypeOfArgument();
7105 
7106   return QualType();
7107 }
7108 
7109 /// \brief Check for dangerous or invalid arguments to memset().
7110 ///
7111 /// This issues warnings on known problematic, dangerous or unspecified
7112 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7113 /// function calls.
7114 ///
7115 /// \param Call The call expression to diagnose.
7116 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7117                                    unsigned BId,
7118                                    IdentifierInfo *FnName) {
7119   assert(BId != 0);
7120 
7121   // It is possible to have a non-standard definition of memset.  Validate
7122   // we have enough arguments, and if not, abort further checking.
7123   unsigned ExpectedNumArgs =
7124       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7125   if (Call->getNumArgs() < ExpectedNumArgs)
7126     return;
7127 
7128   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7129                       BId == Builtin::BIstrndup ? 1 : 2);
7130   unsigned LenArg =
7131       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7132   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7133 
7134   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7135                                      Call->getLocStart(), Call->getRParenLoc()))
7136     return;
7137 
7138   // We have special checking when the length is a sizeof expression.
7139   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7140   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7141   llvm::FoldingSetNodeID SizeOfArgID;
7142 
7143   // Although widely used, 'bzero' is not a standard function. Be more strict
7144   // with the argument types before allowing diagnostics and only allow the
7145   // form bzero(ptr, sizeof(...)).
7146   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7147   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7148     return;
7149 
7150   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7151     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7152     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7153 
7154     QualType DestTy = Dest->getType();
7155     QualType PointeeTy;
7156     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7157       PointeeTy = DestPtrTy->getPointeeType();
7158 
7159       // Never warn about void type pointers. This can be used to suppress
7160       // false positives.
7161       if (PointeeTy->isVoidType())
7162         continue;
7163 
7164       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7165       // actually comparing the expressions for equality. Because computing the
7166       // expression IDs can be expensive, we only do this if the diagnostic is
7167       // enabled.
7168       if (SizeOfArg &&
7169           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7170                            SizeOfArg->getExprLoc())) {
7171         // We only compute IDs for expressions if the warning is enabled, and
7172         // cache the sizeof arg's ID.
7173         if (SizeOfArgID == llvm::FoldingSetNodeID())
7174           SizeOfArg->Profile(SizeOfArgID, Context, true);
7175         llvm::FoldingSetNodeID DestID;
7176         Dest->Profile(DestID, Context, true);
7177         if (DestID == SizeOfArgID) {
7178           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7179           //       over sizeof(src) as well.
7180           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7181           StringRef ReadableName = FnName->getName();
7182 
7183           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7184             if (UnaryOp->getOpcode() == UO_AddrOf)
7185               ActionIdx = 1; // If its an address-of operator, just remove it.
7186           if (!PointeeTy->isIncompleteType() &&
7187               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7188             ActionIdx = 2; // If the pointee's size is sizeof(char),
7189                            // suggest an explicit length.
7190 
7191           // If the function is defined as a builtin macro, do not show macro
7192           // expansion.
7193           SourceLocation SL = SizeOfArg->getExprLoc();
7194           SourceRange DSR = Dest->getSourceRange();
7195           SourceRange SSR = SizeOfArg->getSourceRange();
7196           SourceManager &SM = getSourceManager();
7197 
7198           if (SM.isMacroArgExpansion(SL)) {
7199             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7200             SL = SM.getSpellingLoc(SL);
7201             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7202                              SM.getSpellingLoc(DSR.getEnd()));
7203             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7204                              SM.getSpellingLoc(SSR.getEnd()));
7205           }
7206 
7207           DiagRuntimeBehavior(SL, SizeOfArg,
7208                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7209                                 << ReadableName
7210                                 << PointeeTy
7211                                 << DestTy
7212                                 << DSR
7213                                 << SSR);
7214           DiagRuntimeBehavior(SL, SizeOfArg,
7215                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7216                                 << ActionIdx
7217                                 << SSR);
7218 
7219           break;
7220         }
7221       }
7222 
7223       // Also check for cases where the sizeof argument is the exact same
7224       // type as the memory argument, and where it points to a user-defined
7225       // record type.
7226       if (SizeOfArgTy != QualType()) {
7227         if (PointeeTy->isRecordType() &&
7228             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7229           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7230                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7231                                 << FnName << SizeOfArgTy << ArgIdx
7232                                 << PointeeTy << Dest->getSourceRange()
7233                                 << LenExpr->getSourceRange());
7234           break;
7235         }
7236       }
7237     } else if (DestTy->isArrayType()) {
7238       PointeeTy = DestTy;
7239     }
7240 
7241     if (PointeeTy == QualType())
7242       continue;
7243 
7244     // Always complain about dynamic classes.
7245     bool IsContained;
7246     if (const CXXRecordDecl *ContainedRD =
7247             getContainedDynamicClass(PointeeTy, IsContained)) {
7248 
7249       unsigned OperationType = 0;
7250       // "overwritten" if we're warning about the destination for any call
7251       // but memcmp; otherwise a verb appropriate to the call.
7252       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7253         if (BId == Builtin::BImemcpy)
7254           OperationType = 1;
7255         else if(BId == Builtin::BImemmove)
7256           OperationType = 2;
7257         else if (BId == Builtin::BImemcmp)
7258           OperationType = 3;
7259       }
7260 
7261       DiagRuntimeBehavior(
7262         Dest->getExprLoc(), Dest,
7263         PDiag(diag::warn_dyn_class_memaccess)
7264           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7265           << FnName << IsContained << ContainedRD << OperationType
7266           << Call->getCallee()->getSourceRange());
7267     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7268              BId != Builtin::BImemset)
7269       DiagRuntimeBehavior(
7270         Dest->getExprLoc(), Dest,
7271         PDiag(diag::warn_arc_object_memaccess)
7272           << ArgIdx << FnName << PointeeTy
7273           << Call->getCallee()->getSourceRange());
7274     else
7275       continue;
7276 
7277     DiagRuntimeBehavior(
7278       Dest->getExprLoc(), Dest,
7279       PDiag(diag::note_bad_memaccess_silence)
7280         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7281     break;
7282   }
7283 }
7284 
7285 // A little helper routine: ignore addition and subtraction of integer literals.
7286 // This intentionally does not ignore all integer constant expressions because
7287 // we don't want to remove sizeof().
7288 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7289   Ex = Ex->IgnoreParenCasts();
7290 
7291   for (;;) {
7292     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7293     if (!BO || !BO->isAdditiveOp())
7294       break;
7295 
7296     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7297     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7298 
7299     if (isa<IntegerLiteral>(RHS))
7300       Ex = LHS;
7301     else if (isa<IntegerLiteral>(LHS))
7302       Ex = RHS;
7303     else
7304       break;
7305   }
7306 
7307   return Ex;
7308 }
7309 
7310 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7311                                                       ASTContext &Context) {
7312   // Only handle constant-sized or VLAs, but not flexible members.
7313   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7314     // Only issue the FIXIT for arrays of size > 1.
7315     if (CAT->getSize().getSExtValue() <= 1)
7316       return false;
7317   } else if (!Ty->isVariableArrayType()) {
7318     return false;
7319   }
7320   return true;
7321 }
7322 
7323 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7324 // be the size of the source, instead of the destination.
7325 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7326                                     IdentifierInfo *FnName) {
7327 
7328   // Don't crash if the user has the wrong number of arguments
7329   unsigned NumArgs = Call->getNumArgs();
7330   if ((NumArgs != 3) && (NumArgs != 4))
7331     return;
7332 
7333   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7334   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7335   const Expr *CompareWithSrc = nullptr;
7336 
7337   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7338                                      Call->getLocStart(), Call->getRParenLoc()))
7339     return;
7340 
7341   // Look for 'strlcpy(dst, x, sizeof(x))'
7342   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7343     CompareWithSrc = Ex;
7344   else {
7345     // Look for 'strlcpy(dst, x, strlen(x))'
7346     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7347       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7348           SizeCall->getNumArgs() == 1)
7349         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7350     }
7351   }
7352 
7353   if (!CompareWithSrc)
7354     return;
7355 
7356   // Determine if the argument to sizeof/strlen is equal to the source
7357   // argument.  In principle there's all kinds of things you could do
7358   // here, for instance creating an == expression and evaluating it with
7359   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7360   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7361   if (!SrcArgDRE)
7362     return;
7363 
7364   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7365   if (!CompareWithSrcDRE ||
7366       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7367     return;
7368 
7369   const Expr *OriginalSizeArg = Call->getArg(2);
7370   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7371     << OriginalSizeArg->getSourceRange() << FnName;
7372 
7373   // Output a FIXIT hint if the destination is an array (rather than a
7374   // pointer to an array).  This could be enhanced to handle some
7375   // pointers if we know the actual size, like if DstArg is 'array+2'
7376   // we could say 'sizeof(array)-2'.
7377   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7378   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7379     return;
7380 
7381   SmallString<128> sizeString;
7382   llvm::raw_svector_ostream OS(sizeString);
7383   OS << "sizeof(";
7384   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7385   OS << ")";
7386 
7387   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7388     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7389                                     OS.str());
7390 }
7391 
7392 /// Check if two expressions refer to the same declaration.
7393 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7394   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7395     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7396       return D1->getDecl() == D2->getDecl();
7397   return false;
7398 }
7399 
7400 static const Expr *getStrlenExprArg(const Expr *E) {
7401   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7402     const FunctionDecl *FD = CE->getDirectCallee();
7403     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7404       return nullptr;
7405     return CE->getArg(0)->IgnoreParenCasts();
7406   }
7407   return nullptr;
7408 }
7409 
7410 // Warn on anti-patterns as the 'size' argument to strncat.
7411 // The correct size argument should look like following:
7412 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7413 void Sema::CheckStrncatArguments(const CallExpr *CE,
7414                                  IdentifierInfo *FnName) {
7415   // Don't crash if the user has the wrong number of arguments.
7416   if (CE->getNumArgs() < 3)
7417     return;
7418   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7419   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7420   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7421 
7422   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7423                                      CE->getRParenLoc()))
7424     return;
7425 
7426   // Identify common expressions, which are wrongly used as the size argument
7427   // to strncat and may lead to buffer overflows.
7428   unsigned PatternType = 0;
7429   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7430     // - sizeof(dst)
7431     if (referToTheSameDecl(SizeOfArg, DstArg))
7432       PatternType = 1;
7433     // - sizeof(src)
7434     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7435       PatternType = 2;
7436   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7437     if (BE->getOpcode() == BO_Sub) {
7438       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7439       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7440       // - sizeof(dst) - strlen(dst)
7441       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7442           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7443         PatternType = 1;
7444       // - sizeof(src) - (anything)
7445       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7446         PatternType = 2;
7447     }
7448   }
7449 
7450   if (PatternType == 0)
7451     return;
7452 
7453   // Generate the diagnostic.
7454   SourceLocation SL = LenArg->getLocStart();
7455   SourceRange SR = LenArg->getSourceRange();
7456   SourceManager &SM = getSourceManager();
7457 
7458   // If the function is defined as a builtin macro, do not show macro expansion.
7459   if (SM.isMacroArgExpansion(SL)) {
7460     SL = SM.getSpellingLoc(SL);
7461     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7462                      SM.getSpellingLoc(SR.getEnd()));
7463   }
7464 
7465   // Check if the destination is an array (rather than a pointer to an array).
7466   QualType DstTy = DstArg->getType();
7467   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7468                                                                     Context);
7469   if (!isKnownSizeArray) {
7470     if (PatternType == 1)
7471       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7472     else
7473       Diag(SL, diag::warn_strncat_src_size) << SR;
7474     return;
7475   }
7476 
7477   if (PatternType == 1)
7478     Diag(SL, diag::warn_strncat_large_size) << SR;
7479   else
7480     Diag(SL, diag::warn_strncat_src_size) << SR;
7481 
7482   SmallString<128> sizeString;
7483   llvm::raw_svector_ostream OS(sizeString);
7484   OS << "sizeof(";
7485   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7486   OS << ") - ";
7487   OS << "strlen(";
7488   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7489   OS << ") - 1";
7490 
7491   Diag(SL, diag::note_strncat_wrong_size)
7492     << FixItHint::CreateReplacement(SR, OS.str());
7493 }
7494 
7495 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7496 
7497 static const Expr *EvalVal(const Expr *E,
7498                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7499                            const Decl *ParentDecl);
7500 static const Expr *EvalAddr(const Expr *E,
7501                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7502                             const Decl *ParentDecl);
7503 
7504 /// CheckReturnStackAddr - Check if a return statement returns the address
7505 ///   of a stack variable.
7506 static void
7507 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7508                      SourceLocation ReturnLoc) {
7509 
7510   const Expr *stackE = nullptr;
7511   SmallVector<const DeclRefExpr *, 8> refVars;
7512 
7513   // Perform checking for returned stack addresses, local blocks,
7514   // label addresses or references to temporaries.
7515   if (lhsType->isPointerType() ||
7516       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7517     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7518   } else if (lhsType->isReferenceType()) {
7519     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7520   }
7521 
7522   if (!stackE)
7523     return; // Nothing suspicious was found.
7524 
7525   // Parameters are initialized in the calling scope, so taking the address
7526   // of a parameter reference doesn't need a warning.
7527   for (auto *DRE : refVars)
7528     if (isa<ParmVarDecl>(DRE->getDecl()))
7529       return;
7530 
7531   SourceLocation diagLoc;
7532   SourceRange diagRange;
7533   if (refVars.empty()) {
7534     diagLoc = stackE->getLocStart();
7535     diagRange = stackE->getSourceRange();
7536   } else {
7537     // We followed through a reference variable. 'stackE' contains the
7538     // problematic expression but we will warn at the return statement pointing
7539     // at the reference variable. We will later display the "trail" of
7540     // reference variables using notes.
7541     diagLoc = refVars[0]->getLocStart();
7542     diagRange = refVars[0]->getSourceRange();
7543   }
7544 
7545   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7546     // address of local var
7547     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7548      << DR->getDecl()->getDeclName() << diagRange;
7549   } else if (isa<BlockExpr>(stackE)) { // local block.
7550     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7551   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7552     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7553   } else { // local temporary.
7554     // If there is an LValue->RValue conversion, then the value of the
7555     // reference type is used, not the reference.
7556     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7557       if (ICE->getCastKind() == CK_LValueToRValue) {
7558         return;
7559       }
7560     }
7561     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7562      << lhsType->isReferenceType() << diagRange;
7563   }
7564 
7565   // Display the "trail" of reference variables that we followed until we
7566   // found the problematic expression using notes.
7567   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7568     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7569     // If this var binds to another reference var, show the range of the next
7570     // var, otherwise the var binds to the problematic expression, in which case
7571     // show the range of the expression.
7572     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7573                                     : stackE->getSourceRange();
7574     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7575         << VD->getDeclName() << range;
7576   }
7577 }
7578 
7579 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7580 ///  check if the expression in a return statement evaluates to an address
7581 ///  to a location on the stack, a local block, an address of a label, or a
7582 ///  reference to local temporary. The recursion is used to traverse the
7583 ///  AST of the return expression, with recursion backtracking when we
7584 ///  encounter a subexpression that (1) clearly does not lead to one of the
7585 ///  above problematic expressions (2) is something we cannot determine leads to
7586 ///  a problematic expression based on such local checking.
7587 ///
7588 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7589 ///  the expression that they point to. Such variables are added to the
7590 ///  'refVars' vector so that we know what the reference variable "trail" was.
7591 ///
7592 ///  EvalAddr processes expressions that are pointers that are used as
7593 ///  references (and not L-values).  EvalVal handles all other values.
7594 ///  At the base case of the recursion is a check for the above problematic
7595 ///  expressions.
7596 ///
7597 ///  This implementation handles:
7598 ///
7599 ///   * pointer-to-pointer casts
7600 ///   * implicit conversions from array references to pointers
7601 ///   * taking the address of fields
7602 ///   * arbitrary interplay between "&" and "*" operators
7603 ///   * pointer arithmetic from an address of a stack variable
7604 ///   * taking the address of an array element where the array is on the stack
7605 static const Expr *EvalAddr(const Expr *E,
7606                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7607                             const Decl *ParentDecl) {
7608   if (E->isTypeDependent())
7609     return nullptr;
7610 
7611   // We should only be called for evaluating pointer expressions.
7612   assert((E->getType()->isAnyPointerType() ||
7613           E->getType()->isBlockPointerType() ||
7614           E->getType()->isObjCQualifiedIdType()) &&
7615          "EvalAddr only works on pointers");
7616 
7617   E = E->IgnoreParens();
7618 
7619   // Our "symbolic interpreter" is just a dispatch off the currently
7620   // viewed AST node.  We then recursively traverse the AST by calling
7621   // EvalAddr and EvalVal appropriately.
7622   switch (E->getStmtClass()) {
7623   case Stmt::DeclRefExprClass: {
7624     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7625 
7626     // If we leave the immediate function, the lifetime isn't about to end.
7627     if (DR->refersToEnclosingVariableOrCapture())
7628       return nullptr;
7629 
7630     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7631       // If this is a reference variable, follow through to the expression that
7632       // it points to.
7633       if (V->hasLocalStorage() &&
7634           V->getType()->isReferenceType() && V->hasInit()) {
7635         // Add the reference variable to the "trail".
7636         refVars.push_back(DR);
7637         return EvalAddr(V->getInit(), refVars, ParentDecl);
7638       }
7639 
7640     return nullptr;
7641   }
7642 
7643   case Stmt::UnaryOperatorClass: {
7644     // The only unary operator that make sense to handle here
7645     // is AddrOf.  All others don't make sense as pointers.
7646     const UnaryOperator *U = cast<UnaryOperator>(E);
7647 
7648     if (U->getOpcode() == UO_AddrOf)
7649       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7650     return nullptr;
7651   }
7652 
7653   case Stmt::BinaryOperatorClass: {
7654     // Handle pointer arithmetic.  All other binary operators are not valid
7655     // in this context.
7656     const BinaryOperator *B = cast<BinaryOperator>(E);
7657     BinaryOperatorKind op = B->getOpcode();
7658 
7659     if (op != BO_Add && op != BO_Sub)
7660       return nullptr;
7661 
7662     const Expr *Base = B->getLHS();
7663 
7664     // Determine which argument is the real pointer base.  It could be
7665     // the RHS argument instead of the LHS.
7666     if (!Base->getType()->isPointerType())
7667       Base = B->getRHS();
7668 
7669     assert(Base->getType()->isPointerType());
7670     return EvalAddr(Base, refVars, ParentDecl);
7671   }
7672 
7673   // For conditional operators we need to see if either the LHS or RHS are
7674   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7675   case Stmt::ConditionalOperatorClass: {
7676     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7677 
7678     // Handle the GNU extension for missing LHS.
7679     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7680     if (const Expr *LHSExpr = C->getLHS()) {
7681       // In C++, we can have a throw-expression, which has 'void' type.
7682       if (!LHSExpr->getType()->isVoidType())
7683         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7684           return LHS;
7685     }
7686 
7687     // In C++, we can have a throw-expression, which has 'void' type.
7688     if (C->getRHS()->getType()->isVoidType())
7689       return nullptr;
7690 
7691     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7692   }
7693 
7694   case Stmt::BlockExprClass:
7695     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7696       return E; // local block.
7697     return nullptr;
7698 
7699   case Stmt::AddrLabelExprClass:
7700     return E; // address of label.
7701 
7702   case Stmt::ExprWithCleanupsClass:
7703     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7704                     ParentDecl);
7705 
7706   // For casts, we need to handle conversions from arrays to
7707   // pointer values, and pointer-to-pointer conversions.
7708   case Stmt::ImplicitCastExprClass:
7709   case Stmt::CStyleCastExprClass:
7710   case Stmt::CXXFunctionalCastExprClass:
7711   case Stmt::ObjCBridgedCastExprClass:
7712   case Stmt::CXXStaticCastExprClass:
7713   case Stmt::CXXDynamicCastExprClass:
7714   case Stmt::CXXConstCastExprClass:
7715   case Stmt::CXXReinterpretCastExprClass: {
7716     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7717     switch (cast<CastExpr>(E)->getCastKind()) {
7718     case CK_LValueToRValue:
7719     case CK_NoOp:
7720     case CK_BaseToDerived:
7721     case CK_DerivedToBase:
7722     case CK_UncheckedDerivedToBase:
7723     case CK_Dynamic:
7724     case CK_CPointerToObjCPointerCast:
7725     case CK_BlockPointerToObjCPointerCast:
7726     case CK_AnyPointerToBlockPointerCast:
7727       return EvalAddr(SubExpr, refVars, ParentDecl);
7728 
7729     case CK_ArrayToPointerDecay:
7730       return EvalVal(SubExpr, refVars, ParentDecl);
7731 
7732     case CK_BitCast:
7733       if (SubExpr->getType()->isAnyPointerType() ||
7734           SubExpr->getType()->isBlockPointerType() ||
7735           SubExpr->getType()->isObjCQualifiedIdType())
7736         return EvalAddr(SubExpr, refVars, ParentDecl);
7737       else
7738         return nullptr;
7739 
7740     default:
7741       return nullptr;
7742     }
7743   }
7744 
7745   case Stmt::MaterializeTemporaryExprClass:
7746     if (const Expr *Result =
7747             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7748                      refVars, ParentDecl))
7749       return Result;
7750     return E;
7751 
7752   // Everything else: we simply don't reason about them.
7753   default:
7754     return nullptr;
7755   }
7756 }
7757 
7758 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7759 ///   See the comments for EvalAddr for more details.
7760 static const Expr *EvalVal(const Expr *E,
7761                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7762                            const Decl *ParentDecl) {
7763   do {
7764     // We should only be called for evaluating non-pointer expressions, or
7765     // expressions with a pointer type that are not used as references but
7766     // instead
7767     // are l-values (e.g., DeclRefExpr with a pointer type).
7768 
7769     // Our "symbolic interpreter" is just a dispatch off the currently
7770     // viewed AST node.  We then recursively traverse the AST by calling
7771     // EvalAddr and EvalVal appropriately.
7772 
7773     E = E->IgnoreParens();
7774     switch (E->getStmtClass()) {
7775     case Stmt::ImplicitCastExprClass: {
7776       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7777       if (IE->getValueKind() == VK_LValue) {
7778         E = IE->getSubExpr();
7779         continue;
7780       }
7781       return nullptr;
7782     }
7783 
7784     case Stmt::ExprWithCleanupsClass:
7785       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7786                      ParentDecl);
7787 
7788     case Stmt::DeclRefExprClass: {
7789       // When we hit a DeclRefExpr we are looking at code that refers to a
7790       // variable's name. If it's not a reference variable we check if it has
7791       // local storage within the function, and if so, return the expression.
7792       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7793 
7794       // If we leave the immediate function, the lifetime isn't about to end.
7795       if (DR->refersToEnclosingVariableOrCapture())
7796         return nullptr;
7797 
7798       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7799         // Check if it refers to itself, e.g. "int& i = i;".
7800         if (V == ParentDecl)
7801           return DR;
7802 
7803         if (V->hasLocalStorage()) {
7804           if (!V->getType()->isReferenceType())
7805             return DR;
7806 
7807           // Reference variable, follow through to the expression that
7808           // it points to.
7809           if (V->hasInit()) {
7810             // Add the reference variable to the "trail".
7811             refVars.push_back(DR);
7812             return EvalVal(V->getInit(), refVars, V);
7813           }
7814         }
7815       }
7816 
7817       return nullptr;
7818     }
7819 
7820     case Stmt::UnaryOperatorClass: {
7821       // The only unary operator that make sense to handle here
7822       // is Deref.  All others don't resolve to a "name."  This includes
7823       // handling all sorts of rvalues passed to a unary operator.
7824       const UnaryOperator *U = cast<UnaryOperator>(E);
7825 
7826       if (U->getOpcode() == UO_Deref)
7827         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7828 
7829       return nullptr;
7830     }
7831 
7832     case Stmt::ArraySubscriptExprClass: {
7833       // Array subscripts are potential references to data on the stack.  We
7834       // retrieve the DeclRefExpr* for the array variable if it indeed
7835       // has local storage.
7836       const auto *ASE = cast<ArraySubscriptExpr>(E);
7837       if (ASE->isTypeDependent())
7838         return nullptr;
7839       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7840     }
7841 
7842     case Stmt::OMPArraySectionExprClass: {
7843       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7844                       ParentDecl);
7845     }
7846 
7847     case Stmt::ConditionalOperatorClass: {
7848       // For conditional operators we need to see if either the LHS or RHS are
7849       // non-NULL Expr's.  If one is non-NULL, we return it.
7850       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7851 
7852       // Handle the GNU extension for missing LHS.
7853       if (const Expr *LHSExpr = C->getLHS()) {
7854         // In C++, we can have a throw-expression, which has 'void' type.
7855         if (!LHSExpr->getType()->isVoidType())
7856           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7857             return LHS;
7858       }
7859 
7860       // In C++, we can have a throw-expression, which has 'void' type.
7861       if (C->getRHS()->getType()->isVoidType())
7862         return nullptr;
7863 
7864       return EvalVal(C->getRHS(), refVars, ParentDecl);
7865     }
7866 
7867     // Accesses to members are potential references to data on the stack.
7868     case Stmt::MemberExprClass: {
7869       const MemberExpr *M = cast<MemberExpr>(E);
7870 
7871       // Check for indirect access.  We only want direct field accesses.
7872       if (M->isArrow())
7873         return nullptr;
7874 
7875       // Check whether the member type is itself a reference, in which case
7876       // we're not going to refer to the member, but to what the member refers
7877       // to.
7878       if (M->getMemberDecl()->getType()->isReferenceType())
7879         return nullptr;
7880 
7881       return EvalVal(M->getBase(), refVars, ParentDecl);
7882     }
7883 
7884     case Stmt::MaterializeTemporaryExprClass:
7885       if (const Expr *Result =
7886               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7887                       refVars, ParentDecl))
7888         return Result;
7889       return E;
7890 
7891     default:
7892       // Check that we don't return or take the address of a reference to a
7893       // temporary. This is only useful in C++.
7894       if (!E->isTypeDependent() && E->isRValue())
7895         return E;
7896 
7897       // Everything else: we simply don't reason about them.
7898       return nullptr;
7899     }
7900   } while (true);
7901 }
7902 
7903 void
7904 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7905                          SourceLocation ReturnLoc,
7906                          bool isObjCMethod,
7907                          const AttrVec *Attrs,
7908                          const FunctionDecl *FD) {
7909   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7910 
7911   // Check if the return value is null but should not be.
7912   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7913        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7914       CheckNonNullExpr(*this, RetValExp))
7915     Diag(ReturnLoc, diag::warn_null_ret)
7916       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7917 
7918   // C++11 [basic.stc.dynamic.allocation]p4:
7919   //   If an allocation function declared with a non-throwing
7920   //   exception-specification fails to allocate storage, it shall return
7921   //   a null pointer. Any other allocation function that fails to allocate
7922   //   storage shall indicate failure only by throwing an exception [...]
7923   if (FD) {
7924     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7925     if (Op == OO_New || Op == OO_Array_New) {
7926       const FunctionProtoType *Proto
7927         = FD->getType()->castAs<FunctionProtoType>();
7928       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7929           CheckNonNullExpr(*this, RetValExp))
7930         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7931           << FD << getLangOpts().CPlusPlus11;
7932     }
7933   }
7934 }
7935 
7936 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7937 
7938 /// Check for comparisons of floating point operands using != and ==.
7939 /// Issue a warning if these are no self-comparisons, as they are not likely
7940 /// to do what the programmer intended.
7941 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7942   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7943   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7944 
7945   // Special case: check for x == x (which is OK).
7946   // Do not emit warnings for such cases.
7947   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7948     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7949       if (DRL->getDecl() == DRR->getDecl())
7950         return;
7951 
7952   // Special case: check for comparisons against literals that can be exactly
7953   //  represented by APFloat.  In such cases, do not emit a warning.  This
7954   //  is a heuristic: often comparison against such literals are used to
7955   //  detect if a value in a variable has not changed.  This clearly can
7956   //  lead to false negatives.
7957   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7958     if (FLL->isExact())
7959       return;
7960   } else
7961     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7962       if (FLR->isExact())
7963         return;
7964 
7965   // Check for comparisons with builtin types.
7966   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7967     if (CL->getBuiltinCallee())
7968       return;
7969 
7970   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7971     if (CR->getBuiltinCallee())
7972       return;
7973 
7974   // Emit the diagnostic.
7975   Diag(Loc, diag::warn_floatingpoint_eq)
7976     << LHS->getSourceRange() << RHS->getSourceRange();
7977 }
7978 
7979 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7980 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7981 
7982 namespace {
7983 
7984 /// Structure recording the 'active' range of an integer-valued
7985 /// expression.
7986 struct IntRange {
7987   /// The number of bits active in the int.
7988   unsigned Width;
7989 
7990   /// True if the int is known not to have negative values.
7991   bool NonNegative;
7992 
7993   IntRange(unsigned Width, bool NonNegative)
7994     : Width(Width), NonNegative(NonNegative)
7995   {}
7996 
7997   /// Returns the range of the bool type.
7998   static IntRange forBoolType() {
7999     return IntRange(1, true);
8000   }
8001 
8002   /// Returns the range of an opaque value of the given integral type.
8003   static IntRange forValueOfType(ASTContext &C, QualType T) {
8004     return forValueOfCanonicalType(C,
8005                           T->getCanonicalTypeInternal().getTypePtr());
8006   }
8007 
8008   /// Returns the range of an opaque value of a canonical integral type.
8009   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8010     assert(T->isCanonicalUnqualified());
8011 
8012     if (const VectorType *VT = dyn_cast<VectorType>(T))
8013       T = VT->getElementType().getTypePtr();
8014     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8015       T = CT->getElementType().getTypePtr();
8016     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8017       T = AT->getValueType().getTypePtr();
8018 
8019     // For enum types, use the known bit width of the enumerators.
8020     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8021       EnumDecl *Enum = ET->getDecl();
8022       if (!Enum->isCompleteDefinition())
8023         return IntRange(C.getIntWidth(QualType(T, 0)), false);
8024 
8025       unsigned NumPositive = Enum->getNumPositiveBits();
8026       unsigned NumNegative = Enum->getNumNegativeBits();
8027 
8028       if (NumNegative == 0)
8029         return IntRange(NumPositive, true/*NonNegative*/);
8030       else
8031         return IntRange(std::max(NumPositive + 1, NumNegative),
8032                         false/*NonNegative*/);
8033     }
8034 
8035     const BuiltinType *BT = cast<BuiltinType>(T);
8036     assert(BT->isInteger());
8037 
8038     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8039   }
8040 
8041   /// Returns the "target" range of a canonical integral type, i.e.
8042   /// the range of values expressible in the type.
8043   ///
8044   /// This matches forValueOfCanonicalType except that enums have the
8045   /// full range of their type, not the range of their enumerators.
8046   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8047     assert(T->isCanonicalUnqualified());
8048 
8049     if (const VectorType *VT = dyn_cast<VectorType>(T))
8050       T = VT->getElementType().getTypePtr();
8051     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8052       T = CT->getElementType().getTypePtr();
8053     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8054       T = AT->getValueType().getTypePtr();
8055     if (const EnumType *ET = dyn_cast<EnumType>(T))
8056       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8057 
8058     const BuiltinType *BT = cast<BuiltinType>(T);
8059     assert(BT->isInteger());
8060 
8061     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8062   }
8063 
8064   /// Returns the supremum of two ranges: i.e. their conservative merge.
8065   static IntRange join(IntRange L, IntRange R) {
8066     return IntRange(std::max(L.Width, R.Width),
8067                     L.NonNegative && R.NonNegative);
8068   }
8069 
8070   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8071   static IntRange meet(IntRange L, IntRange R) {
8072     return IntRange(std::min(L.Width, R.Width),
8073                     L.NonNegative || R.NonNegative);
8074   }
8075 };
8076 
8077 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
8078   if (value.isSigned() && value.isNegative())
8079     return IntRange(value.getMinSignedBits(), false);
8080 
8081   if (value.getBitWidth() > MaxWidth)
8082     value = value.trunc(MaxWidth);
8083 
8084   // isNonNegative() just checks the sign bit without considering
8085   // signedness.
8086   return IntRange(value.getActiveBits(), true);
8087 }
8088 
8089 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8090                        unsigned MaxWidth) {
8091   if (result.isInt())
8092     return GetValueRange(C, result.getInt(), MaxWidth);
8093 
8094   if (result.isVector()) {
8095     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8096     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8097       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8098       R = IntRange::join(R, El);
8099     }
8100     return R;
8101   }
8102 
8103   if (result.isComplexInt()) {
8104     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8105     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8106     return IntRange::join(R, I);
8107   }
8108 
8109   // This can happen with lossless casts to intptr_t of "based" lvalues.
8110   // Assume it might use arbitrary bits.
8111   // FIXME: The only reason we need to pass the type in here is to get
8112   // the sign right on this one case.  It would be nice if APValue
8113   // preserved this.
8114   assert(result.isLValue() || result.isAddrLabelDiff());
8115   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8116 }
8117 
8118 QualType GetExprType(const Expr *E) {
8119   QualType Ty = E->getType();
8120   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8121     Ty = AtomicRHS->getValueType();
8122   return Ty;
8123 }
8124 
8125 /// Pseudo-evaluate the given integer expression, estimating the
8126 /// range of values it might take.
8127 ///
8128 /// \param MaxWidth - the width to which the value will be truncated
8129 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8130   E = E->IgnoreParens();
8131 
8132   // Try a full evaluation first.
8133   Expr::EvalResult result;
8134   if (E->EvaluateAsRValue(result, C))
8135     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8136 
8137   // I think we only want to look through implicit casts here; if the
8138   // user has an explicit widening cast, we should treat the value as
8139   // being of the new, wider type.
8140   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8141     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8142       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8143 
8144     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8145 
8146     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8147                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8148 
8149     // Assume that non-integer casts can span the full range of the type.
8150     if (!isIntegerCast)
8151       return OutputTypeRange;
8152 
8153     IntRange SubRange
8154       = GetExprRange(C, CE->getSubExpr(),
8155                      std::min(MaxWidth, OutputTypeRange.Width));
8156 
8157     // Bail out if the subexpr's range is as wide as the cast type.
8158     if (SubRange.Width >= OutputTypeRange.Width)
8159       return OutputTypeRange;
8160 
8161     // Otherwise, we take the smaller width, and we're non-negative if
8162     // either the output type or the subexpr is.
8163     return IntRange(SubRange.Width,
8164                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8165   }
8166 
8167   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8168     // If we can fold the condition, just take that operand.
8169     bool CondResult;
8170     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8171       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8172                                         : CO->getFalseExpr(),
8173                           MaxWidth);
8174 
8175     // Otherwise, conservatively merge.
8176     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8177     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8178     return IntRange::join(L, R);
8179   }
8180 
8181   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8182     switch (BO->getOpcode()) {
8183 
8184     // Boolean-valued operations are single-bit and positive.
8185     case BO_LAnd:
8186     case BO_LOr:
8187     case BO_LT:
8188     case BO_GT:
8189     case BO_LE:
8190     case BO_GE:
8191     case BO_EQ:
8192     case BO_NE:
8193       return IntRange::forBoolType();
8194 
8195     // The type of the assignments is the type of the LHS, so the RHS
8196     // is not necessarily the same type.
8197     case BO_MulAssign:
8198     case BO_DivAssign:
8199     case BO_RemAssign:
8200     case BO_AddAssign:
8201     case BO_SubAssign:
8202     case BO_XorAssign:
8203     case BO_OrAssign:
8204       // TODO: bitfields?
8205       return IntRange::forValueOfType(C, GetExprType(E));
8206 
8207     // Simple assignments just pass through the RHS, which will have
8208     // been coerced to the LHS type.
8209     case BO_Assign:
8210       // TODO: bitfields?
8211       return GetExprRange(C, BO->getRHS(), MaxWidth);
8212 
8213     // Operations with opaque sources are black-listed.
8214     case BO_PtrMemD:
8215     case BO_PtrMemI:
8216       return IntRange::forValueOfType(C, GetExprType(E));
8217 
8218     // Bitwise-and uses the *infinum* of the two source ranges.
8219     case BO_And:
8220     case BO_AndAssign:
8221       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8222                             GetExprRange(C, BO->getRHS(), MaxWidth));
8223 
8224     // Left shift gets black-listed based on a judgement call.
8225     case BO_Shl:
8226       // ...except that we want to treat '1 << (blah)' as logically
8227       // positive.  It's an important idiom.
8228       if (IntegerLiteral *I
8229             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8230         if (I->getValue() == 1) {
8231           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8232           return IntRange(R.Width, /*NonNegative*/ true);
8233         }
8234       }
8235       // fallthrough
8236 
8237     case BO_ShlAssign:
8238       return IntRange::forValueOfType(C, GetExprType(E));
8239 
8240     // Right shift by a constant can narrow its left argument.
8241     case BO_Shr:
8242     case BO_ShrAssign: {
8243       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8244 
8245       // If the shift amount is a positive constant, drop the width by
8246       // that much.
8247       llvm::APSInt shift;
8248       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8249           shift.isNonNegative()) {
8250         unsigned zext = shift.getZExtValue();
8251         if (zext >= L.Width)
8252           L.Width = (L.NonNegative ? 0 : 1);
8253         else
8254           L.Width -= zext;
8255       }
8256 
8257       return L;
8258     }
8259 
8260     // Comma acts as its right operand.
8261     case BO_Comma:
8262       return GetExprRange(C, BO->getRHS(), MaxWidth);
8263 
8264     // Black-list pointer subtractions.
8265     case BO_Sub:
8266       if (BO->getLHS()->getType()->isPointerType())
8267         return IntRange::forValueOfType(C, GetExprType(E));
8268       break;
8269 
8270     // The width of a division result is mostly determined by the size
8271     // of the LHS.
8272     case BO_Div: {
8273       // Don't 'pre-truncate' the operands.
8274       unsigned opWidth = C.getIntWidth(GetExprType(E));
8275       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8276 
8277       // If the divisor is constant, use that.
8278       llvm::APSInt divisor;
8279       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8280         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8281         if (log2 >= L.Width)
8282           L.Width = (L.NonNegative ? 0 : 1);
8283         else
8284           L.Width = std::min(L.Width - log2, MaxWidth);
8285         return L;
8286       }
8287 
8288       // Otherwise, just use the LHS's width.
8289       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8290       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8291     }
8292 
8293     // The result of a remainder can't be larger than the result of
8294     // either side.
8295     case BO_Rem: {
8296       // Don't 'pre-truncate' the operands.
8297       unsigned opWidth = C.getIntWidth(GetExprType(E));
8298       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8299       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8300 
8301       IntRange meet = IntRange::meet(L, R);
8302       meet.Width = std::min(meet.Width, MaxWidth);
8303       return meet;
8304     }
8305 
8306     // The default behavior is okay for these.
8307     case BO_Mul:
8308     case BO_Add:
8309     case BO_Xor:
8310     case BO_Or:
8311       break;
8312     }
8313 
8314     // The default case is to treat the operation as if it were closed
8315     // on the narrowest type that encompasses both operands.
8316     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8317     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8318     return IntRange::join(L, R);
8319   }
8320 
8321   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8322     switch (UO->getOpcode()) {
8323     // Boolean-valued operations are white-listed.
8324     case UO_LNot:
8325       return IntRange::forBoolType();
8326 
8327     // Operations with opaque sources are black-listed.
8328     case UO_Deref:
8329     case UO_AddrOf: // should be impossible
8330       return IntRange::forValueOfType(C, GetExprType(E));
8331 
8332     default:
8333       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8334     }
8335   }
8336 
8337   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8338     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8339 
8340   if (const auto *BitField = E->getSourceBitField())
8341     return IntRange(BitField->getBitWidthValue(C),
8342                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8343 
8344   return IntRange::forValueOfType(C, GetExprType(E));
8345 }
8346 
8347 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8348   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8349 }
8350 
8351 /// Checks whether the given value, which currently has the given
8352 /// source semantics, has the same value when coerced through the
8353 /// target semantics.
8354 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8355                           const llvm::fltSemantics &Src,
8356                           const llvm::fltSemantics &Tgt) {
8357   llvm::APFloat truncated = value;
8358 
8359   bool ignored;
8360   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8361   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8362 
8363   return truncated.bitwiseIsEqual(value);
8364 }
8365 
8366 /// Checks whether the given value, which currently has the given
8367 /// source semantics, has the same value when coerced through the
8368 /// target semantics.
8369 ///
8370 /// The value might be a vector of floats (or a complex number).
8371 bool IsSameFloatAfterCast(const APValue &value,
8372                           const llvm::fltSemantics &Src,
8373                           const llvm::fltSemantics &Tgt) {
8374   if (value.isFloat())
8375     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8376 
8377   if (value.isVector()) {
8378     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8379       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8380         return false;
8381     return true;
8382   }
8383 
8384   assert(value.isComplexFloat());
8385   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8386           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8387 }
8388 
8389 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8390 
8391 bool IsZero(Sema &S, Expr *E) {
8392   // Suppress cases where we are comparing against an enum constant.
8393   if (const DeclRefExpr *DR =
8394       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8395     if (isa<EnumConstantDecl>(DR->getDecl()))
8396       return false;
8397 
8398   // Suppress cases where the '0' value is expanded from a macro.
8399   if (E->getLocStart().isMacroID())
8400     return false;
8401 
8402   llvm::APSInt Value;
8403   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8404 }
8405 
8406 bool HasEnumType(Expr *E) {
8407   // Strip off implicit integral promotions.
8408   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8409     if (ICE->getCastKind() != CK_IntegralCast &&
8410         ICE->getCastKind() != CK_NoOp)
8411       break;
8412     E = ICE->getSubExpr();
8413   }
8414 
8415   return E->getType()->isEnumeralType();
8416 }
8417 
8418 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
8419   // Disable warning in template instantiations.
8420   if (S.inTemplateInstantiation())
8421     return;
8422 
8423   BinaryOperatorKind op = E->getOpcode();
8424   if (E->isValueDependent())
8425     return;
8426 
8427   if (op == BO_LT && IsZero(S, E->getRHS())) {
8428     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8429       << "< 0" << "false" << HasEnumType(E->getLHS())
8430       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8431   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
8432     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
8433       << ">= 0" << "true" << HasEnumType(E->getLHS())
8434       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8435   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
8436     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8437       << "0 >" << "false" << HasEnumType(E->getRHS())
8438       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8439   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
8440     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
8441       << "0 <=" << "true" << HasEnumType(E->getRHS())
8442       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8443   }
8444 }
8445 
8446 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8447                                   Expr *Other, const llvm::APSInt &Value,
8448                                   bool RhsConstant) {
8449   // Disable warning in template instantiations.
8450   if (S.inTemplateInstantiation())
8451     return;
8452 
8453   // TODO: Investigate using GetExprRange() to get tighter bounds
8454   // on the bit ranges.
8455   QualType OtherT = Other->getType();
8456   if (const auto *AT = OtherT->getAs<AtomicType>())
8457     OtherT = AT->getValueType();
8458   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8459   unsigned OtherWidth = OtherRange.Width;
8460 
8461   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8462 
8463   // 0 values are handled later by CheckTrivialUnsignedComparison().
8464   if ((Value == 0) && (!OtherIsBooleanType))
8465     return;
8466 
8467   BinaryOperatorKind op = E->getOpcode();
8468   bool IsTrue = true;
8469 
8470   // Used for diagnostic printout.
8471   enum {
8472     LiteralConstant = 0,
8473     CXXBoolLiteralTrue,
8474     CXXBoolLiteralFalse
8475   } LiteralOrBoolConstant = LiteralConstant;
8476 
8477   if (!OtherIsBooleanType) {
8478     QualType ConstantT = Constant->getType();
8479     QualType CommonT = E->getLHS()->getType();
8480 
8481     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8482       return;
8483     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8484            "comparison with non-integer type");
8485 
8486     bool ConstantSigned = ConstantT->isSignedIntegerType();
8487     bool CommonSigned = CommonT->isSignedIntegerType();
8488 
8489     bool EqualityOnly = false;
8490 
8491     if (CommonSigned) {
8492       // The common type is signed, therefore no signed to unsigned conversion.
8493       if (!OtherRange.NonNegative) {
8494         // Check that the constant is representable in type OtherT.
8495         if (ConstantSigned) {
8496           if (OtherWidth >= Value.getMinSignedBits())
8497             return;
8498         } else { // !ConstantSigned
8499           if (OtherWidth >= Value.getActiveBits() + 1)
8500             return;
8501         }
8502       } else { // !OtherSigned
8503                // Check that the constant is representable in type OtherT.
8504         // Negative values are out of range.
8505         if (ConstantSigned) {
8506           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8507             return;
8508         } else { // !ConstantSigned
8509           if (OtherWidth >= Value.getActiveBits())
8510             return;
8511         }
8512       }
8513     } else { // !CommonSigned
8514       if (OtherRange.NonNegative) {
8515         if (OtherWidth >= Value.getActiveBits())
8516           return;
8517       } else { // OtherSigned
8518         assert(!ConstantSigned &&
8519                "Two signed types converted to unsigned types.");
8520         // Check to see if the constant is representable in OtherT.
8521         if (OtherWidth > Value.getActiveBits())
8522           return;
8523         // Check to see if the constant is equivalent to a negative value
8524         // cast to CommonT.
8525         if (S.Context.getIntWidth(ConstantT) ==
8526                 S.Context.getIntWidth(CommonT) &&
8527             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8528           return;
8529         // The constant value rests between values that OtherT can represent
8530         // after conversion.  Relational comparison still works, but equality
8531         // comparisons will be tautological.
8532         EqualityOnly = true;
8533       }
8534     }
8535 
8536     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8537 
8538     if (op == BO_EQ || op == BO_NE) {
8539       IsTrue = op == BO_NE;
8540     } else if (EqualityOnly) {
8541       return;
8542     } else if (RhsConstant) {
8543       if (op == BO_GT || op == BO_GE)
8544         IsTrue = !PositiveConstant;
8545       else // op == BO_LT || op == BO_LE
8546         IsTrue = PositiveConstant;
8547     } else {
8548       if (op == BO_LT || op == BO_LE)
8549         IsTrue = !PositiveConstant;
8550       else // op == BO_GT || op == BO_GE
8551         IsTrue = PositiveConstant;
8552     }
8553   } else {
8554     // Other isKnownToHaveBooleanValue
8555     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8556     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8557     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8558 
8559     static const struct LinkedConditions {
8560       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8561       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8562       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8563       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8564       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8565       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8566 
8567     } TruthTable = {
8568         // Constant on LHS.              | Constant on RHS.              |
8569         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8570         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8571         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8572         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8573         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8574         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8575         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8576       };
8577 
8578     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8579 
8580     enum ConstantValue ConstVal = Zero;
8581     if (Value.isUnsigned() || Value.isNonNegative()) {
8582       if (Value == 0) {
8583         LiteralOrBoolConstant =
8584             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8585         ConstVal = Zero;
8586       } else if (Value == 1) {
8587         LiteralOrBoolConstant =
8588             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8589         ConstVal = One;
8590       } else {
8591         LiteralOrBoolConstant = LiteralConstant;
8592         ConstVal = GT_One;
8593       }
8594     } else {
8595       ConstVal = LT_Zero;
8596     }
8597 
8598     CompareBoolWithConstantResult CmpRes;
8599 
8600     switch (op) {
8601     case BO_LT:
8602       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8603       break;
8604     case BO_GT:
8605       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8606       break;
8607     case BO_LE:
8608       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8609       break;
8610     case BO_GE:
8611       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8612       break;
8613     case BO_EQ:
8614       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8615       break;
8616     case BO_NE:
8617       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8618       break;
8619     default:
8620       CmpRes = Unkwn;
8621       break;
8622     }
8623 
8624     if (CmpRes == AFals) {
8625       IsTrue = false;
8626     } else if (CmpRes == ATrue) {
8627       IsTrue = true;
8628     } else {
8629       return;
8630     }
8631   }
8632 
8633   // If this is a comparison to an enum constant, include that
8634   // constant in the diagnostic.
8635   const EnumConstantDecl *ED = nullptr;
8636   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8637     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8638 
8639   SmallString<64> PrettySourceValue;
8640   llvm::raw_svector_ostream OS(PrettySourceValue);
8641   if (ED)
8642     OS << '\'' << *ED << "' (" << Value << ")";
8643   else
8644     OS << Value;
8645 
8646   S.DiagRuntimeBehavior(
8647     E->getOperatorLoc(), E,
8648     S.PDiag(diag::warn_out_of_range_compare)
8649         << OS.str() << LiteralOrBoolConstant
8650         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8651         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8652 }
8653 
8654 /// Analyze the operands of the given comparison.  Implements the
8655 /// fallback case from AnalyzeComparison.
8656 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8657   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8658   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8659 }
8660 
8661 /// \brief Implements -Wsign-compare.
8662 ///
8663 /// \param E the binary operator to check for warnings
8664 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8665   // The type the comparison is being performed in.
8666   QualType T = E->getLHS()->getType();
8667 
8668   // Only analyze comparison operators where both sides have been converted to
8669   // the same type.
8670   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8671     return AnalyzeImpConvsInComparison(S, E);
8672 
8673   // Don't analyze value-dependent comparisons directly.
8674   if (E->isValueDependent())
8675     return AnalyzeImpConvsInComparison(S, E);
8676 
8677   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8678   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8679 
8680   bool IsComparisonConstant = false;
8681 
8682   // Check whether an integer constant comparison results in a value
8683   // of 'true' or 'false'.
8684   if (T->isIntegralType(S.Context)) {
8685     llvm::APSInt RHSValue;
8686     bool IsRHSIntegralLiteral =
8687       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8688     llvm::APSInt LHSValue;
8689     bool IsLHSIntegralLiteral =
8690       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8691     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8692         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8693     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8694       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8695     else
8696       IsComparisonConstant =
8697         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8698   } else if (!T->hasUnsignedIntegerRepresentation())
8699       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8700 
8701   // We don't do anything special if this isn't an unsigned integral
8702   // comparison:  we're only interested in integral comparisons, and
8703   // signed comparisons only happen in cases we don't care to warn about.
8704   //
8705   // We also don't care about value-dependent expressions or expressions
8706   // whose result is a constant.
8707   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8708     return AnalyzeImpConvsInComparison(S, E);
8709 
8710   // Check to see if one of the (unmodified) operands is of different
8711   // signedness.
8712   Expr *signedOperand, *unsignedOperand;
8713   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8714     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8715            "unsigned comparison between two signed integer expressions?");
8716     signedOperand = LHS;
8717     unsignedOperand = RHS;
8718   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8719     signedOperand = RHS;
8720     unsignedOperand = LHS;
8721   } else {
8722     CheckTrivialUnsignedComparison(S, E);
8723     return AnalyzeImpConvsInComparison(S, E);
8724   }
8725 
8726   // Otherwise, calculate the effective range of the signed operand.
8727   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8728 
8729   // Go ahead and analyze implicit conversions in the operands.  Note
8730   // that we skip the implicit conversions on both sides.
8731   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8732   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8733 
8734   // If the signed range is non-negative, -Wsign-compare won't fire,
8735   // but we should still check for comparisons which are always true
8736   // or false.
8737   if (signedRange.NonNegative)
8738     return CheckTrivialUnsignedComparison(S, E);
8739 
8740   // For (in)equality comparisons, if the unsigned operand is a
8741   // constant which cannot collide with a overflowed signed operand,
8742   // then reinterpreting the signed operand as unsigned will not
8743   // change the result of the comparison.
8744   if (E->isEqualityOp()) {
8745     unsigned comparisonWidth = S.Context.getIntWidth(T);
8746     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8747 
8748     // We should never be unable to prove that the unsigned operand is
8749     // non-negative.
8750     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8751 
8752     if (unsignedRange.Width < comparisonWidth)
8753       return;
8754   }
8755 
8756   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8757     S.PDiag(diag::warn_mixed_sign_comparison)
8758       << LHS->getType() << RHS->getType()
8759       << LHS->getSourceRange() << RHS->getSourceRange());
8760 }
8761 
8762 /// Analyzes an attempt to assign the given value to a bitfield.
8763 ///
8764 /// Returns true if there was something fishy about the attempt.
8765 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8766                                SourceLocation InitLoc) {
8767   assert(Bitfield->isBitField());
8768   if (Bitfield->isInvalidDecl())
8769     return false;
8770 
8771   // White-list bool bitfields.
8772   QualType BitfieldType = Bitfield->getType();
8773   if (BitfieldType->isBooleanType())
8774      return false;
8775 
8776   if (BitfieldType->isEnumeralType()) {
8777     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8778     // If the underlying enum type was not explicitly specified as an unsigned
8779     // type and the enum contain only positive values, MSVC++ will cause an
8780     // inconsistency by storing this as a signed type.
8781     if (S.getLangOpts().CPlusPlus11 &&
8782         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8783         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8784         BitfieldEnumDecl->getNumNegativeBits() == 0) {
8785       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8786         << BitfieldEnumDecl->getNameAsString();
8787     }
8788   }
8789 
8790   if (Bitfield->getType()->isBooleanType())
8791     return false;
8792 
8793   // Ignore value- or type-dependent expressions.
8794   if (Bitfield->getBitWidth()->isValueDependent() ||
8795       Bitfield->getBitWidth()->isTypeDependent() ||
8796       Init->isValueDependent() ||
8797       Init->isTypeDependent())
8798     return false;
8799 
8800   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8801   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8802 
8803   llvm::APSInt Value;
8804   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8805                                    Expr::SE_AllowSideEffects)) {
8806     // The RHS is not constant.  If the RHS has an enum type, make sure the
8807     // bitfield is wide enough to hold all the values of the enum without
8808     // truncation.
8809     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8810       EnumDecl *ED = EnumTy->getDecl();
8811       bool SignedBitfield = BitfieldType->isSignedIntegerType();
8812 
8813       // Enum types are implicitly signed on Windows, so check if there are any
8814       // negative enumerators to see if the enum was intended to be signed or
8815       // not.
8816       bool SignedEnum = ED->getNumNegativeBits() > 0;
8817 
8818       // Check for surprising sign changes when assigning enum values to a
8819       // bitfield of different signedness.  If the bitfield is signed and we
8820       // have exactly the right number of bits to store this unsigned enum,
8821       // suggest changing the enum to an unsigned type. This typically happens
8822       // on Windows where unfixed enums always use an underlying type of 'int'.
8823       unsigned DiagID = 0;
8824       if (SignedEnum && !SignedBitfield) {
8825         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8826       } else if (SignedBitfield && !SignedEnum &&
8827                  ED->getNumPositiveBits() == FieldWidth) {
8828         DiagID = diag::warn_signed_bitfield_enum_conversion;
8829       }
8830 
8831       if (DiagID) {
8832         S.Diag(InitLoc, DiagID) << Bitfield << ED;
8833         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8834         SourceRange TypeRange =
8835             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8836         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8837             << SignedEnum << TypeRange;
8838       }
8839 
8840       // Compute the required bitwidth. If the enum has negative values, we need
8841       // one more bit than the normal number of positive bits to represent the
8842       // sign bit.
8843       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8844                                                   ED->getNumNegativeBits())
8845                                        : ED->getNumPositiveBits();
8846 
8847       // Check the bitwidth.
8848       if (BitsNeeded > FieldWidth) {
8849         Expr *WidthExpr = Bitfield->getBitWidth();
8850         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8851             << Bitfield << ED;
8852         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8853             << BitsNeeded << ED << WidthExpr->getSourceRange();
8854       }
8855     }
8856 
8857     return false;
8858   }
8859 
8860   unsigned OriginalWidth = Value.getBitWidth();
8861 
8862   if (!Value.isSigned() || Value.isNegative())
8863     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8864       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8865         OriginalWidth = Value.getMinSignedBits();
8866 
8867   if (OriginalWidth <= FieldWidth)
8868     return false;
8869 
8870   // Compute the value which the bitfield will contain.
8871   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8872   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
8873 
8874   // Check whether the stored value is equal to the original value.
8875   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8876   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8877     return false;
8878 
8879   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8880   // therefore don't strictly fit into a signed bitfield of width 1.
8881   if (FieldWidth == 1 && Value == 1)
8882     return false;
8883 
8884   std::string PrettyValue = Value.toString(10);
8885   std::string PrettyTrunc = TruncatedValue.toString(10);
8886 
8887   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8888     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8889     << Init->getSourceRange();
8890 
8891   return true;
8892 }
8893 
8894 /// Analyze the given simple or compound assignment for warning-worthy
8895 /// operations.
8896 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8897   // Just recurse on the LHS.
8898   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8899 
8900   // We want to recurse on the RHS as normal unless we're assigning to
8901   // a bitfield.
8902   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8903     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8904                                   E->getOperatorLoc())) {
8905       // Recurse, ignoring any implicit conversions on the RHS.
8906       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8907                                         E->getOperatorLoc());
8908     }
8909   }
8910 
8911   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8912 }
8913 
8914 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8915 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8916                      SourceLocation CContext, unsigned diag,
8917                      bool pruneControlFlow = false) {
8918   if (pruneControlFlow) {
8919     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8920                           S.PDiag(diag)
8921                             << SourceType << T << E->getSourceRange()
8922                             << SourceRange(CContext));
8923     return;
8924   }
8925   S.Diag(E->getExprLoc(), diag)
8926     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8927 }
8928 
8929 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8930 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8931                      unsigned diag, bool pruneControlFlow = false) {
8932   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8933 }
8934 
8935 
8936 /// Diagnose an implicit cast from a floating point value to an integer value.
8937 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8938 
8939                              SourceLocation CContext) {
8940   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8941   const bool PruneWarnings = S.inTemplateInstantiation();
8942 
8943   Expr *InnerE = E->IgnoreParenImpCasts();
8944   // We also want to warn on, e.g., "int i = -1.234"
8945   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8946     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8947       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8948 
8949   const bool IsLiteral =
8950       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8951 
8952   llvm::APFloat Value(0.0);
8953   bool IsConstant =
8954     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8955   if (!IsConstant) {
8956     return DiagnoseImpCast(S, E, T, CContext,
8957                            diag::warn_impcast_float_integer, PruneWarnings);
8958   }
8959 
8960   bool isExact = false;
8961 
8962   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8963                             T->hasUnsignedIntegerRepresentation());
8964   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8965                              &isExact) == llvm::APFloat::opOK &&
8966       isExact) {
8967     if (IsLiteral) return;
8968     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8969                            PruneWarnings);
8970   }
8971 
8972   unsigned DiagID = 0;
8973   if (IsLiteral) {
8974     // Warn on floating point literal to integer.
8975     DiagID = diag::warn_impcast_literal_float_to_integer;
8976   } else if (IntegerValue == 0) {
8977     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8978       return DiagnoseImpCast(S, E, T, CContext,
8979                              diag::warn_impcast_float_integer, PruneWarnings);
8980     }
8981     // Warn on non-zero to zero conversion.
8982     DiagID = diag::warn_impcast_float_to_integer_zero;
8983   } else {
8984     if (IntegerValue.isUnsigned()) {
8985       if (!IntegerValue.isMaxValue()) {
8986         return DiagnoseImpCast(S, E, T, CContext,
8987                                diag::warn_impcast_float_integer, PruneWarnings);
8988       }
8989     } else {  // IntegerValue.isSigned()
8990       if (!IntegerValue.isMaxSignedValue() &&
8991           !IntegerValue.isMinSignedValue()) {
8992         return DiagnoseImpCast(S, E, T, CContext,
8993                                diag::warn_impcast_float_integer, PruneWarnings);
8994       }
8995     }
8996     // Warn on evaluatable floating point expression to integer conversion.
8997     DiagID = diag::warn_impcast_float_to_integer;
8998   }
8999 
9000   // FIXME: Force the precision of the source value down so we don't print
9001   // digits which are usually useless (we don't really care here if we
9002   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9003   // would automatically print the shortest representation, but it's a bit
9004   // tricky to implement.
9005   SmallString<16> PrettySourceValue;
9006   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9007   precision = (precision * 59 + 195) / 196;
9008   Value.toString(PrettySourceValue, precision);
9009 
9010   SmallString<16> PrettyTargetValue;
9011   if (IsBool)
9012     PrettyTargetValue = Value.isZero() ? "false" : "true";
9013   else
9014     IntegerValue.toString(PrettyTargetValue);
9015 
9016   if (PruneWarnings) {
9017     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9018                           S.PDiag(DiagID)
9019                               << E->getType() << T.getUnqualifiedType()
9020                               << PrettySourceValue << PrettyTargetValue
9021                               << E->getSourceRange() << SourceRange(CContext));
9022   } else {
9023     S.Diag(E->getExprLoc(), DiagID)
9024         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9025         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9026   }
9027 }
9028 
9029 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9030   if (!Range.Width) return "0";
9031 
9032   llvm::APSInt ValueInRange = Value;
9033   ValueInRange.setIsSigned(!Range.NonNegative);
9034   ValueInRange = ValueInRange.trunc(Range.Width);
9035   return ValueInRange.toString(10);
9036 }
9037 
9038 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9039   if (!isa<ImplicitCastExpr>(Ex))
9040     return false;
9041 
9042   Expr *InnerE = Ex->IgnoreParenImpCasts();
9043   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9044   const Type *Source =
9045     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9046   if (Target->isDependentType())
9047     return false;
9048 
9049   const BuiltinType *FloatCandidateBT =
9050     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9051   const Type *BoolCandidateType = ToBool ? Target : Source;
9052 
9053   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9054           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9055 }
9056 
9057 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9058                                       SourceLocation CC) {
9059   unsigned NumArgs = TheCall->getNumArgs();
9060   for (unsigned i = 0; i < NumArgs; ++i) {
9061     Expr *CurrA = TheCall->getArg(i);
9062     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9063       continue;
9064 
9065     bool IsSwapped = ((i > 0) &&
9066         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9067     IsSwapped |= ((i < (NumArgs - 1)) &&
9068         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9069     if (IsSwapped) {
9070       // Warn on this floating-point to bool conversion.
9071       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9072                       CurrA->getType(), CC,
9073                       diag::warn_impcast_floating_point_to_bool);
9074     }
9075   }
9076 }
9077 
9078 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
9079   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9080                         E->getExprLoc()))
9081     return;
9082 
9083   // Don't warn on functions which have return type nullptr_t.
9084   if (isa<CallExpr>(E))
9085     return;
9086 
9087   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9088   const Expr::NullPointerConstantKind NullKind =
9089       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9090   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9091     return;
9092 
9093   // Return if target type is a safe conversion.
9094   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9095       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9096     return;
9097 
9098   SourceLocation Loc = E->getSourceRange().getBegin();
9099 
9100   // Venture through the macro stacks to get to the source of macro arguments.
9101   // The new location is a better location than the complete location that was
9102   // passed in.
9103   while (S.SourceMgr.isMacroArgExpansion(Loc))
9104     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9105 
9106   while (S.SourceMgr.isMacroArgExpansion(CC))
9107     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9108 
9109   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9110   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9111     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9112         Loc, S.SourceMgr, S.getLangOpts());
9113     if (MacroName == "NULL")
9114       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9115   }
9116 
9117   // Only warn if the null and context location are in the same macro expansion.
9118   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9119     return;
9120 
9121   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9122       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9123       << FixItHint::CreateReplacement(Loc,
9124                                       S.getFixItZeroLiteralForType(T, Loc));
9125 }
9126 
9127 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9128                            ObjCArrayLiteral *ArrayLiteral);
9129 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9130                                 ObjCDictionaryLiteral *DictionaryLiteral);
9131 
9132 /// Check a single element within a collection literal against the
9133 /// target element type.
9134 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9135                                        Expr *Element, unsigned ElementKind) {
9136   // Skip a bitcast to 'id' or qualified 'id'.
9137   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9138     if (ICE->getCastKind() == CK_BitCast &&
9139         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9140       Element = ICE->getSubExpr();
9141   }
9142 
9143   QualType ElementType = Element->getType();
9144   ExprResult ElementResult(Element);
9145   if (ElementType->getAs<ObjCObjectPointerType>() &&
9146       S.CheckSingleAssignmentConstraints(TargetElementType,
9147                                          ElementResult,
9148                                          false, false)
9149         != Sema::Compatible) {
9150     S.Diag(Element->getLocStart(),
9151            diag::warn_objc_collection_literal_element)
9152       << ElementType << ElementKind << TargetElementType
9153       << Element->getSourceRange();
9154   }
9155 
9156   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9157     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9158   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9159     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9160 }
9161 
9162 /// Check an Objective-C array literal being converted to the given
9163 /// target type.
9164 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9165                            ObjCArrayLiteral *ArrayLiteral) {
9166   if (!S.NSArrayDecl)
9167     return;
9168 
9169   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9170   if (!TargetObjCPtr)
9171     return;
9172 
9173   if (TargetObjCPtr->isUnspecialized() ||
9174       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9175         != S.NSArrayDecl->getCanonicalDecl())
9176     return;
9177 
9178   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9179   if (TypeArgs.size() != 1)
9180     return;
9181 
9182   QualType TargetElementType = TypeArgs[0];
9183   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9184     checkObjCCollectionLiteralElement(S, TargetElementType,
9185                                       ArrayLiteral->getElement(I),
9186                                       0);
9187   }
9188 }
9189 
9190 /// Check an Objective-C dictionary literal being converted to the given
9191 /// target type.
9192 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9193                                 ObjCDictionaryLiteral *DictionaryLiteral) {
9194   if (!S.NSDictionaryDecl)
9195     return;
9196 
9197   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9198   if (!TargetObjCPtr)
9199     return;
9200 
9201   if (TargetObjCPtr->isUnspecialized() ||
9202       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9203         != S.NSDictionaryDecl->getCanonicalDecl())
9204     return;
9205 
9206   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9207   if (TypeArgs.size() != 2)
9208     return;
9209 
9210   QualType TargetKeyType = TypeArgs[0];
9211   QualType TargetObjectType = TypeArgs[1];
9212   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9213     auto Element = DictionaryLiteral->getKeyValueElement(I);
9214     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9215     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9216   }
9217 }
9218 
9219 // Helper function to filter out cases for constant width constant conversion.
9220 // Don't warn on char array initialization or for non-decimal values.
9221 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9222                                    SourceLocation CC) {
9223   // If initializing from a constant, and the constant starts with '0',
9224   // then it is a binary, octal, or hexadecimal.  Allow these constants
9225   // to fill all the bits, even if there is a sign change.
9226   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9227     const char FirstLiteralCharacter =
9228         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9229     if (FirstLiteralCharacter == '0')
9230       return false;
9231   }
9232 
9233   // If the CC location points to a '{', and the type is char, then assume
9234   // assume it is an array initialization.
9235   if (CC.isValid() && T->isCharType()) {
9236     const char FirstContextCharacter =
9237         S.getSourceManager().getCharacterData(CC)[0];
9238     if (FirstContextCharacter == '{')
9239       return false;
9240   }
9241 
9242   return true;
9243 }
9244 
9245 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9246                              SourceLocation CC, bool *ICContext = nullptr) {
9247   if (E->isTypeDependent() || E->isValueDependent()) return;
9248 
9249   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9250   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9251   if (Source == Target) return;
9252   if (Target->isDependentType()) return;
9253 
9254   // If the conversion context location is invalid don't complain. We also
9255   // don't want to emit a warning if the issue occurs from the expansion of
9256   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9257   // delay this check as long as possible. Once we detect we are in that
9258   // scenario, we just return.
9259   if (CC.isInvalid())
9260     return;
9261 
9262   // Diagnose implicit casts to bool.
9263   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9264     if (isa<StringLiteral>(E))
9265       // Warn on string literal to bool.  Checks for string literals in logical
9266       // and expressions, for instance, assert(0 && "error here"), are
9267       // prevented by a check in AnalyzeImplicitConversions().
9268       return DiagnoseImpCast(S, E, T, CC,
9269                              diag::warn_impcast_string_literal_to_bool);
9270     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9271         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9272       // This covers the literal expressions that evaluate to Objective-C
9273       // objects.
9274       return DiagnoseImpCast(S, E, T, CC,
9275                              diag::warn_impcast_objective_c_literal_to_bool);
9276     }
9277     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9278       // Warn on pointer to bool conversion that is always true.
9279       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9280                                      SourceRange(CC));
9281     }
9282   }
9283 
9284   // Check implicit casts from Objective-C collection literals to specialized
9285   // collection types, e.g., NSArray<NSString *> *.
9286   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9287     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9288   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9289     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9290 
9291   // Strip vector types.
9292   if (isa<VectorType>(Source)) {
9293     if (!isa<VectorType>(Target)) {
9294       if (S.SourceMgr.isInSystemMacro(CC))
9295         return;
9296       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9297     }
9298 
9299     // If the vector cast is cast between two vectors of the same size, it is
9300     // a bitcast, not a conversion.
9301     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9302       return;
9303 
9304     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9305     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9306   }
9307   if (auto VecTy = dyn_cast<VectorType>(Target))
9308     Target = VecTy->getElementType().getTypePtr();
9309 
9310   // Strip complex types.
9311   if (isa<ComplexType>(Source)) {
9312     if (!isa<ComplexType>(Target)) {
9313       if (S.SourceMgr.isInSystemMacro(CC))
9314         return;
9315 
9316       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9317     }
9318 
9319     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9320     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9321   }
9322 
9323   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9324   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9325 
9326   // If the source is floating point...
9327   if (SourceBT && SourceBT->isFloatingPoint()) {
9328     // ...and the target is floating point...
9329     if (TargetBT && TargetBT->isFloatingPoint()) {
9330       // ...then warn if we're dropping FP rank.
9331 
9332       // Builtin FP kinds are ordered by increasing FP rank.
9333       if (SourceBT->getKind() > TargetBT->getKind()) {
9334         // Don't warn about float constants that are precisely
9335         // representable in the target type.
9336         Expr::EvalResult result;
9337         if (E->EvaluateAsRValue(result, S.Context)) {
9338           // Value might be a float, a float vector, or a float complex.
9339           if (IsSameFloatAfterCast(result.Val,
9340                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9341                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9342             return;
9343         }
9344 
9345         if (S.SourceMgr.isInSystemMacro(CC))
9346           return;
9347 
9348         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9349       }
9350       // ... or possibly if we're increasing rank, too
9351       else if (TargetBT->getKind() > SourceBT->getKind()) {
9352         if (S.SourceMgr.isInSystemMacro(CC))
9353           return;
9354 
9355         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9356       }
9357       return;
9358     }
9359 
9360     // If the target is integral, always warn.
9361     if (TargetBT && TargetBT->isInteger()) {
9362       if (S.SourceMgr.isInSystemMacro(CC))
9363         return;
9364 
9365       DiagnoseFloatingImpCast(S, E, T, CC);
9366     }
9367 
9368     // Detect the case where a call result is converted from floating-point to
9369     // to bool, and the final argument to the call is converted from bool, to
9370     // discover this typo:
9371     //
9372     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9373     //
9374     // FIXME: This is an incredibly special case; is there some more general
9375     // way to detect this class of misplaced-parentheses bug?
9376     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9377       // Check last argument of function call to see if it is an
9378       // implicit cast from a type matching the type the result
9379       // is being cast to.
9380       CallExpr *CEx = cast<CallExpr>(E);
9381       if (unsigned NumArgs = CEx->getNumArgs()) {
9382         Expr *LastA = CEx->getArg(NumArgs - 1);
9383         Expr *InnerE = LastA->IgnoreParenImpCasts();
9384         if (isa<ImplicitCastExpr>(LastA) &&
9385             InnerE->getType()->isBooleanType()) {
9386           // Warn on this floating-point to bool conversion
9387           DiagnoseImpCast(S, E, T, CC,
9388                           diag::warn_impcast_floating_point_to_bool);
9389         }
9390       }
9391     }
9392     return;
9393   }
9394 
9395   DiagnoseNullConversion(S, E, T, CC);
9396 
9397   S.DiscardMisalignedMemberAddress(Target, E);
9398 
9399   if (!Source->isIntegerType() || !Target->isIntegerType())
9400     return;
9401 
9402   // TODO: remove this early return once the false positives for constant->bool
9403   // in templates, macros, etc, are reduced or removed.
9404   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9405     return;
9406 
9407   IntRange SourceRange = GetExprRange(S.Context, E);
9408   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9409 
9410   if (SourceRange.Width > TargetRange.Width) {
9411     // If the source is a constant, use a default-on diagnostic.
9412     // TODO: this should happen for bitfield stores, too.
9413     llvm::APSInt Value(32);
9414     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9415       if (S.SourceMgr.isInSystemMacro(CC))
9416         return;
9417 
9418       std::string PrettySourceValue = Value.toString(10);
9419       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9420 
9421       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9422         S.PDiag(diag::warn_impcast_integer_precision_constant)
9423             << PrettySourceValue << PrettyTargetValue
9424             << E->getType() << T << E->getSourceRange()
9425             << clang::SourceRange(CC));
9426       return;
9427     }
9428 
9429     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9430     if (S.SourceMgr.isInSystemMacro(CC))
9431       return;
9432 
9433     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9434       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9435                              /* pruneControlFlow */ true);
9436     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9437   }
9438 
9439   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9440       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9441     // Warn when doing a signed to signed conversion, warn if the positive
9442     // source value is exactly the width of the target type, which will
9443     // cause a negative value to be stored.
9444 
9445     llvm::APSInt Value;
9446     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9447         !S.SourceMgr.isInSystemMacro(CC)) {
9448       if (isSameWidthConstantConversion(S, E, T, CC)) {
9449         std::string PrettySourceValue = Value.toString(10);
9450         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9451 
9452         S.DiagRuntimeBehavior(
9453             E->getExprLoc(), E,
9454             S.PDiag(diag::warn_impcast_integer_precision_constant)
9455                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9456                 << E->getSourceRange() << clang::SourceRange(CC));
9457         return;
9458       }
9459     }
9460 
9461     // Fall through for non-constants to give a sign conversion warning.
9462   }
9463 
9464   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9465       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9466        SourceRange.Width == TargetRange.Width)) {
9467     if (S.SourceMgr.isInSystemMacro(CC))
9468       return;
9469 
9470     unsigned DiagID = diag::warn_impcast_integer_sign;
9471 
9472     // Traditionally, gcc has warned about this under -Wsign-compare.
9473     // We also want to warn about it in -Wconversion.
9474     // So if -Wconversion is off, use a completely identical diagnostic
9475     // in the sign-compare group.
9476     // The conditional-checking code will
9477     if (ICContext) {
9478       DiagID = diag::warn_impcast_integer_sign_conditional;
9479       *ICContext = true;
9480     }
9481 
9482     return DiagnoseImpCast(S, E, T, CC, DiagID);
9483   }
9484 
9485   // Diagnose conversions between different enumeration types.
9486   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9487   // type, to give us better diagnostics.
9488   QualType SourceType = E->getType();
9489   if (!S.getLangOpts().CPlusPlus) {
9490     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9491       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9492         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9493         SourceType = S.Context.getTypeDeclType(Enum);
9494         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9495       }
9496   }
9497 
9498   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9499     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9500       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9501           TargetEnum->getDecl()->hasNameForLinkage() &&
9502           SourceEnum != TargetEnum) {
9503         if (S.SourceMgr.isInSystemMacro(CC))
9504           return;
9505 
9506         return DiagnoseImpCast(S, E, SourceType, T, CC,
9507                                diag::warn_impcast_different_enum_types);
9508       }
9509 }
9510 
9511 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9512                               SourceLocation CC, QualType T);
9513 
9514 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9515                              SourceLocation CC, bool &ICContext) {
9516   E = E->IgnoreParenImpCasts();
9517 
9518   if (isa<ConditionalOperator>(E))
9519     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9520 
9521   AnalyzeImplicitConversions(S, E, CC);
9522   if (E->getType() != T)
9523     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9524 }
9525 
9526 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9527                               SourceLocation CC, QualType T) {
9528   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9529 
9530   bool Suspicious = false;
9531   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9532   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9533 
9534   // If -Wconversion would have warned about either of the candidates
9535   // for a signedness conversion to the context type...
9536   if (!Suspicious) return;
9537 
9538   // ...but it's currently ignored...
9539   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9540     return;
9541 
9542   // ...then check whether it would have warned about either of the
9543   // candidates for a signedness conversion to the condition type.
9544   if (E->getType() == T) return;
9545 
9546   Suspicious = false;
9547   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9548                           E->getType(), CC, &Suspicious);
9549   if (!Suspicious)
9550     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9551                             E->getType(), CC, &Suspicious);
9552 }
9553 
9554 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9555 /// Input argument E is a logical expression.
9556 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9557   if (S.getLangOpts().Bool)
9558     return;
9559   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9560 }
9561 
9562 /// AnalyzeImplicitConversions - Find and report any interesting
9563 /// implicit conversions in the given expression.  There are a couple
9564 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9565 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9566   QualType T = OrigE->getType();
9567   Expr *E = OrigE->IgnoreParenImpCasts();
9568 
9569   if (E->isTypeDependent() || E->isValueDependent())
9570     return;
9571 
9572   // For conditional operators, we analyze the arguments as if they
9573   // were being fed directly into the output.
9574   if (isa<ConditionalOperator>(E)) {
9575     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9576     CheckConditionalOperator(S, CO, CC, T);
9577     return;
9578   }
9579 
9580   // Check implicit argument conversions for function calls.
9581   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9582     CheckImplicitArgumentConversions(S, Call, CC);
9583 
9584   // Go ahead and check any implicit conversions we might have skipped.
9585   // The non-canonical typecheck is just an optimization;
9586   // CheckImplicitConversion will filter out dead implicit conversions.
9587   if (E->getType() != T)
9588     CheckImplicitConversion(S, E, T, CC);
9589 
9590   // Now continue drilling into this expression.
9591 
9592   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9593     // The bound subexpressions in a PseudoObjectExpr are not reachable
9594     // as transitive children.
9595     // FIXME: Use a more uniform representation for this.
9596     for (auto *SE : POE->semantics())
9597       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9598         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9599   }
9600 
9601   // Skip past explicit casts.
9602   if (isa<ExplicitCastExpr>(E)) {
9603     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9604     return AnalyzeImplicitConversions(S, E, CC);
9605   }
9606 
9607   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9608     // Do a somewhat different check with comparison operators.
9609     if (BO->isComparisonOp())
9610       return AnalyzeComparison(S, BO);
9611 
9612     // And with simple assignments.
9613     if (BO->getOpcode() == BO_Assign)
9614       return AnalyzeAssignment(S, BO);
9615   }
9616 
9617   // These break the otherwise-useful invariant below.  Fortunately,
9618   // we don't really need to recurse into them, because any internal
9619   // expressions should have been analyzed already when they were
9620   // built into statements.
9621   if (isa<StmtExpr>(E)) return;
9622 
9623   // Don't descend into unevaluated contexts.
9624   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9625 
9626   // Now just recurse over the expression's children.
9627   CC = E->getExprLoc();
9628   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9629   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9630   for (Stmt *SubStmt : E->children()) {
9631     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9632     if (!ChildExpr)
9633       continue;
9634 
9635     if (IsLogicalAndOperator &&
9636         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9637       // Ignore checking string literals that are in logical and operators.
9638       // This is a common pattern for asserts.
9639       continue;
9640     AnalyzeImplicitConversions(S, ChildExpr, CC);
9641   }
9642 
9643   if (BO && BO->isLogicalOp()) {
9644     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9645     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9646       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9647 
9648     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9649     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9650       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9651   }
9652 
9653   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9654     if (U->getOpcode() == UO_LNot)
9655       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9656 }
9657 
9658 } // end anonymous namespace
9659 
9660 /// Diagnose integer type and any valid implicit convertion to it.
9661 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9662   // Taking into account implicit conversions,
9663   // allow any integer.
9664   if (!E->getType()->isIntegerType()) {
9665     S.Diag(E->getLocStart(),
9666            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9667     return true;
9668   }
9669   // Potentially emit standard warnings for implicit conversions if enabled
9670   // using -Wconversion.
9671   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9672   return false;
9673 }
9674 
9675 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9676 // Returns true when emitting a warning about taking the address of a reference.
9677 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9678                               const PartialDiagnostic &PD) {
9679   E = E->IgnoreParenImpCasts();
9680 
9681   const FunctionDecl *FD = nullptr;
9682 
9683   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9684     if (!DRE->getDecl()->getType()->isReferenceType())
9685       return false;
9686   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9687     if (!M->getMemberDecl()->getType()->isReferenceType())
9688       return false;
9689   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9690     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9691       return false;
9692     FD = Call->getDirectCallee();
9693   } else {
9694     return false;
9695   }
9696 
9697   SemaRef.Diag(E->getExprLoc(), PD);
9698 
9699   // If possible, point to location of function.
9700   if (FD) {
9701     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9702   }
9703 
9704   return true;
9705 }
9706 
9707 // Returns true if the SourceLocation is expanded from any macro body.
9708 // Returns false if the SourceLocation is invalid, is from not in a macro
9709 // expansion, or is from expanded from a top-level macro argument.
9710 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9711   if (Loc.isInvalid())
9712     return false;
9713 
9714   while (Loc.isMacroID()) {
9715     if (SM.isMacroBodyExpansion(Loc))
9716       return true;
9717     Loc = SM.getImmediateMacroCallerLoc(Loc);
9718   }
9719 
9720   return false;
9721 }
9722 
9723 /// \brief Diagnose pointers that are always non-null.
9724 /// \param E the expression containing the pointer
9725 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9726 /// compared to a null pointer
9727 /// \param IsEqual True when the comparison is equal to a null pointer
9728 /// \param Range Extra SourceRange to highlight in the diagnostic
9729 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9730                                         Expr::NullPointerConstantKind NullKind,
9731                                         bool IsEqual, SourceRange Range) {
9732   if (!E)
9733     return;
9734 
9735   // Don't warn inside macros.
9736   if (E->getExprLoc().isMacroID()) {
9737     const SourceManager &SM = getSourceManager();
9738     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9739         IsInAnyMacroBody(SM, Range.getBegin()))
9740       return;
9741   }
9742   E = E->IgnoreImpCasts();
9743 
9744   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9745 
9746   if (isa<CXXThisExpr>(E)) {
9747     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9748                                 : diag::warn_this_bool_conversion;
9749     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9750     return;
9751   }
9752 
9753   bool IsAddressOf = false;
9754 
9755   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9756     if (UO->getOpcode() != UO_AddrOf)
9757       return;
9758     IsAddressOf = true;
9759     E = UO->getSubExpr();
9760   }
9761 
9762   if (IsAddressOf) {
9763     unsigned DiagID = IsCompare
9764                           ? diag::warn_address_of_reference_null_compare
9765                           : diag::warn_address_of_reference_bool_conversion;
9766     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9767                                          << IsEqual;
9768     if (CheckForReference(*this, E, PD)) {
9769       return;
9770     }
9771   }
9772 
9773   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9774     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9775     std::string Str;
9776     llvm::raw_string_ostream S(Str);
9777     E->printPretty(S, nullptr, getPrintingPolicy());
9778     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9779                                 : diag::warn_cast_nonnull_to_bool;
9780     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9781       << E->getSourceRange() << Range << IsEqual;
9782     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9783   };
9784 
9785   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9786   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9787     if (auto *Callee = Call->getDirectCallee()) {
9788       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9789         ComplainAboutNonnullParamOrCall(A);
9790         return;
9791       }
9792     }
9793   }
9794 
9795   // Expect to find a single Decl.  Skip anything more complicated.
9796   ValueDecl *D = nullptr;
9797   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9798     D = R->getDecl();
9799   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9800     D = M->getMemberDecl();
9801   }
9802 
9803   // Weak Decls can be null.
9804   if (!D || D->isWeak())
9805     return;
9806 
9807   // Check for parameter decl with nonnull attribute
9808   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9809     if (getCurFunction() &&
9810         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9811       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9812         ComplainAboutNonnullParamOrCall(A);
9813         return;
9814       }
9815 
9816       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9817         auto ParamIter = llvm::find(FD->parameters(), PV);
9818         assert(ParamIter != FD->param_end());
9819         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9820 
9821         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9822           if (!NonNull->args_size()) {
9823               ComplainAboutNonnullParamOrCall(NonNull);
9824               return;
9825           }
9826 
9827           for (unsigned ArgNo : NonNull->args()) {
9828             if (ArgNo == ParamNo) {
9829               ComplainAboutNonnullParamOrCall(NonNull);
9830               return;
9831             }
9832           }
9833         }
9834       }
9835     }
9836   }
9837 
9838   QualType T = D->getType();
9839   const bool IsArray = T->isArrayType();
9840   const bool IsFunction = T->isFunctionType();
9841 
9842   // Address of function is used to silence the function warning.
9843   if (IsAddressOf && IsFunction) {
9844     return;
9845   }
9846 
9847   // Found nothing.
9848   if (!IsAddressOf && !IsFunction && !IsArray)
9849     return;
9850 
9851   // Pretty print the expression for the diagnostic.
9852   std::string Str;
9853   llvm::raw_string_ostream S(Str);
9854   E->printPretty(S, nullptr, getPrintingPolicy());
9855 
9856   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9857                               : diag::warn_impcast_pointer_to_bool;
9858   enum {
9859     AddressOf,
9860     FunctionPointer,
9861     ArrayPointer
9862   } DiagType;
9863   if (IsAddressOf)
9864     DiagType = AddressOf;
9865   else if (IsFunction)
9866     DiagType = FunctionPointer;
9867   else if (IsArray)
9868     DiagType = ArrayPointer;
9869   else
9870     llvm_unreachable("Could not determine diagnostic.");
9871   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9872                                 << Range << IsEqual;
9873 
9874   if (!IsFunction)
9875     return;
9876 
9877   // Suggest '&' to silence the function warning.
9878   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9879       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9880 
9881   // Check to see if '()' fixit should be emitted.
9882   QualType ReturnType;
9883   UnresolvedSet<4> NonTemplateOverloads;
9884   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9885   if (ReturnType.isNull())
9886     return;
9887 
9888   if (IsCompare) {
9889     // There are two cases here.  If there is null constant, the only suggest
9890     // for a pointer return type.  If the null is 0, then suggest if the return
9891     // type is a pointer or an integer type.
9892     if (!ReturnType->isPointerType()) {
9893       if (NullKind == Expr::NPCK_ZeroExpression ||
9894           NullKind == Expr::NPCK_ZeroLiteral) {
9895         if (!ReturnType->isIntegerType())
9896           return;
9897       } else {
9898         return;
9899       }
9900     }
9901   } else { // !IsCompare
9902     // For function to bool, only suggest if the function pointer has bool
9903     // return type.
9904     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9905       return;
9906   }
9907   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9908       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9909 }
9910 
9911 /// Diagnoses "dangerous" implicit conversions within the given
9912 /// expression (which is a full expression).  Implements -Wconversion
9913 /// and -Wsign-compare.
9914 ///
9915 /// \param CC the "context" location of the implicit conversion, i.e.
9916 ///   the most location of the syntactic entity requiring the implicit
9917 ///   conversion
9918 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9919   // Don't diagnose in unevaluated contexts.
9920   if (isUnevaluatedContext())
9921     return;
9922 
9923   // Don't diagnose for value- or type-dependent expressions.
9924   if (E->isTypeDependent() || E->isValueDependent())
9925     return;
9926 
9927   // Check for array bounds violations in cases where the check isn't triggered
9928   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9929   // ArraySubscriptExpr is on the RHS of a variable initialization.
9930   CheckArrayAccess(E);
9931 
9932   // This is not the right CC for (e.g.) a variable initialization.
9933   AnalyzeImplicitConversions(*this, E, CC);
9934 }
9935 
9936 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9937 /// Input argument E is a logical expression.
9938 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9939   ::CheckBoolLikeConversion(*this, E, CC);
9940 }
9941 
9942 /// Diagnose when expression is an integer constant expression and its evaluation
9943 /// results in integer overflow
9944 void Sema::CheckForIntOverflow (Expr *E) {
9945   // Use a work list to deal with nested struct initializers.
9946   SmallVector<Expr *, 2> Exprs(1, E);
9947 
9948   do {
9949     Expr *E = Exprs.pop_back_val();
9950 
9951     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9952       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9953       continue;
9954     }
9955 
9956     if (auto InitList = dyn_cast<InitListExpr>(E))
9957       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9958 
9959     if (isa<ObjCBoxedExpr>(E))
9960       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9961   } while (!Exprs.empty());
9962 }
9963 
9964 namespace {
9965 /// \brief Visitor for expressions which looks for unsequenced operations on the
9966 /// same object.
9967 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9968   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9969 
9970   /// \brief A tree of sequenced regions within an expression. Two regions are
9971   /// unsequenced if one is an ancestor or a descendent of the other. When we
9972   /// finish processing an expression with sequencing, such as a comma
9973   /// expression, we fold its tree nodes into its parent, since they are
9974   /// unsequenced with respect to nodes we will visit later.
9975   class SequenceTree {
9976     struct Value {
9977       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9978       unsigned Parent : 31;
9979       unsigned Merged : 1;
9980     };
9981     SmallVector<Value, 8> Values;
9982 
9983   public:
9984     /// \brief A region within an expression which may be sequenced with respect
9985     /// to some other region.
9986     class Seq {
9987       explicit Seq(unsigned N) : Index(N) {}
9988       unsigned Index;
9989       friend class SequenceTree;
9990     public:
9991       Seq() : Index(0) {}
9992     };
9993 
9994     SequenceTree() { Values.push_back(Value(0)); }
9995     Seq root() const { return Seq(0); }
9996 
9997     /// \brief Create a new sequence of operations, which is an unsequenced
9998     /// subset of \p Parent. This sequence of operations is sequenced with
9999     /// respect to other children of \p Parent.
10000     Seq allocate(Seq Parent) {
10001       Values.push_back(Value(Parent.Index));
10002       return Seq(Values.size() - 1);
10003     }
10004 
10005     /// \brief Merge a sequence of operations into its parent.
10006     void merge(Seq S) {
10007       Values[S.Index].Merged = true;
10008     }
10009 
10010     /// \brief Determine whether two operations are unsequenced. This operation
10011     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10012     /// should have been merged into its parent as appropriate.
10013     bool isUnsequenced(Seq Cur, Seq Old) {
10014       unsigned C = representative(Cur.Index);
10015       unsigned Target = representative(Old.Index);
10016       while (C >= Target) {
10017         if (C == Target)
10018           return true;
10019         C = Values[C].Parent;
10020       }
10021       return false;
10022     }
10023 
10024   private:
10025     /// \brief Pick a representative for a sequence.
10026     unsigned representative(unsigned K) {
10027       if (Values[K].Merged)
10028         // Perform path compression as we go.
10029         return Values[K].Parent = representative(Values[K].Parent);
10030       return K;
10031     }
10032   };
10033 
10034   /// An object for which we can track unsequenced uses.
10035   typedef NamedDecl *Object;
10036 
10037   /// Different flavors of object usage which we track. We only track the
10038   /// least-sequenced usage of each kind.
10039   enum UsageKind {
10040     /// A read of an object. Multiple unsequenced reads are OK.
10041     UK_Use,
10042     /// A modification of an object which is sequenced before the value
10043     /// computation of the expression, such as ++n in C++.
10044     UK_ModAsValue,
10045     /// A modification of an object which is not sequenced before the value
10046     /// computation of the expression, such as n++.
10047     UK_ModAsSideEffect,
10048 
10049     UK_Count = UK_ModAsSideEffect + 1
10050   };
10051 
10052   struct Usage {
10053     Usage() : Use(nullptr), Seq() {}
10054     Expr *Use;
10055     SequenceTree::Seq Seq;
10056   };
10057 
10058   struct UsageInfo {
10059     UsageInfo() : Diagnosed(false) {}
10060     Usage Uses[UK_Count];
10061     /// Have we issued a diagnostic for this variable already?
10062     bool Diagnosed;
10063   };
10064   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10065 
10066   Sema &SemaRef;
10067   /// Sequenced regions within the expression.
10068   SequenceTree Tree;
10069   /// Declaration modifications and references which we have seen.
10070   UsageInfoMap UsageMap;
10071   /// The region we are currently within.
10072   SequenceTree::Seq Region;
10073   /// Filled in with declarations which were modified as a side-effect
10074   /// (that is, post-increment operations).
10075   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
10076   /// Expressions to check later. We defer checking these to reduce
10077   /// stack usage.
10078   SmallVectorImpl<Expr *> &WorkList;
10079 
10080   /// RAII object wrapping the visitation of a sequenced subexpression of an
10081   /// expression. At the end of this process, the side-effects of the evaluation
10082   /// become sequenced with respect to the value computation of the result, so
10083   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10084   /// UK_ModAsValue.
10085   struct SequencedSubexpression {
10086     SequencedSubexpression(SequenceChecker &Self)
10087       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10088       Self.ModAsSideEffect = &ModAsSideEffect;
10089     }
10090     ~SequencedSubexpression() {
10091       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10092         UsageInfo &U = Self.UsageMap[M.first];
10093         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10094         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10095         SideEffectUsage = M.second;
10096       }
10097       Self.ModAsSideEffect = OldModAsSideEffect;
10098     }
10099 
10100     SequenceChecker &Self;
10101     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10102     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
10103   };
10104 
10105   /// RAII object wrapping the visitation of a subexpression which we might
10106   /// choose to evaluate as a constant. If any subexpression is evaluated and
10107   /// found to be non-constant, this allows us to suppress the evaluation of
10108   /// the outer expression.
10109   class EvaluationTracker {
10110   public:
10111     EvaluationTracker(SequenceChecker &Self)
10112         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10113       Self.EvalTracker = this;
10114     }
10115     ~EvaluationTracker() {
10116       Self.EvalTracker = Prev;
10117       if (Prev)
10118         Prev->EvalOK &= EvalOK;
10119     }
10120 
10121     bool evaluate(const Expr *E, bool &Result) {
10122       if (!EvalOK || E->isValueDependent())
10123         return false;
10124       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10125       return EvalOK;
10126     }
10127 
10128   private:
10129     SequenceChecker &Self;
10130     EvaluationTracker *Prev;
10131     bool EvalOK;
10132   } *EvalTracker;
10133 
10134   /// \brief Find the object which is produced by the specified expression,
10135   /// if any.
10136   Object getObject(Expr *E, bool Mod) const {
10137     E = E->IgnoreParenCasts();
10138     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10139       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10140         return getObject(UO->getSubExpr(), Mod);
10141     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10142       if (BO->getOpcode() == BO_Comma)
10143         return getObject(BO->getRHS(), Mod);
10144       if (Mod && BO->isAssignmentOp())
10145         return getObject(BO->getLHS(), Mod);
10146     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10147       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10148       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10149         return ME->getMemberDecl();
10150     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10151       // FIXME: If this is a reference, map through to its value.
10152       return DRE->getDecl();
10153     return nullptr;
10154   }
10155 
10156   /// \brief Note that an object was modified or used by an expression.
10157   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10158     Usage &U = UI.Uses[UK];
10159     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10160       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10161         ModAsSideEffect->push_back(std::make_pair(O, U));
10162       U.Use = Ref;
10163       U.Seq = Region;
10164     }
10165   }
10166   /// \brief Check whether a modification or use conflicts with a prior usage.
10167   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10168                   bool IsModMod) {
10169     if (UI.Diagnosed)
10170       return;
10171 
10172     const Usage &U = UI.Uses[OtherKind];
10173     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10174       return;
10175 
10176     Expr *Mod = U.Use;
10177     Expr *ModOrUse = Ref;
10178     if (OtherKind == UK_Use)
10179       std::swap(Mod, ModOrUse);
10180 
10181     SemaRef.Diag(Mod->getExprLoc(),
10182                  IsModMod ? diag::warn_unsequenced_mod_mod
10183                           : diag::warn_unsequenced_mod_use)
10184       << O << SourceRange(ModOrUse->getExprLoc());
10185     UI.Diagnosed = true;
10186   }
10187 
10188   void notePreUse(Object O, Expr *Use) {
10189     UsageInfo &U = UsageMap[O];
10190     // Uses conflict with other modifications.
10191     checkUsage(O, U, Use, UK_ModAsValue, false);
10192   }
10193   void notePostUse(Object O, Expr *Use) {
10194     UsageInfo &U = UsageMap[O];
10195     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10196     addUsage(U, O, Use, UK_Use);
10197   }
10198 
10199   void notePreMod(Object O, Expr *Mod) {
10200     UsageInfo &U = UsageMap[O];
10201     // Modifications conflict with other modifications and with uses.
10202     checkUsage(O, U, Mod, UK_ModAsValue, true);
10203     checkUsage(O, U, Mod, UK_Use, false);
10204   }
10205   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10206     UsageInfo &U = UsageMap[O];
10207     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10208     addUsage(U, O, Use, UK);
10209   }
10210 
10211 public:
10212   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10213       : Base(S.Context), SemaRef(S), Region(Tree.root()),
10214         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
10215     Visit(E);
10216   }
10217 
10218   void VisitStmt(Stmt *S) {
10219     // Skip all statements which aren't expressions for now.
10220   }
10221 
10222   void VisitExpr(Expr *E) {
10223     // By default, just recurse to evaluated subexpressions.
10224     Base::VisitStmt(E);
10225   }
10226 
10227   void VisitCastExpr(CastExpr *E) {
10228     Object O = Object();
10229     if (E->getCastKind() == CK_LValueToRValue)
10230       O = getObject(E->getSubExpr(), false);
10231 
10232     if (O)
10233       notePreUse(O, E);
10234     VisitExpr(E);
10235     if (O)
10236       notePostUse(O, E);
10237   }
10238 
10239   void VisitBinComma(BinaryOperator *BO) {
10240     // C++11 [expr.comma]p1:
10241     //   Every value computation and side effect associated with the left
10242     //   expression is sequenced before every value computation and side
10243     //   effect associated with the right expression.
10244     SequenceTree::Seq LHS = Tree.allocate(Region);
10245     SequenceTree::Seq RHS = Tree.allocate(Region);
10246     SequenceTree::Seq OldRegion = Region;
10247 
10248     {
10249       SequencedSubexpression SeqLHS(*this);
10250       Region = LHS;
10251       Visit(BO->getLHS());
10252     }
10253 
10254     Region = RHS;
10255     Visit(BO->getRHS());
10256 
10257     Region = OldRegion;
10258 
10259     // Forget that LHS and RHS are sequenced. They are both unsequenced
10260     // with respect to other stuff.
10261     Tree.merge(LHS);
10262     Tree.merge(RHS);
10263   }
10264 
10265   void VisitBinAssign(BinaryOperator *BO) {
10266     // The modification is sequenced after the value computation of the LHS
10267     // and RHS, so check it before inspecting the operands and update the
10268     // map afterwards.
10269     Object O = getObject(BO->getLHS(), true);
10270     if (!O)
10271       return VisitExpr(BO);
10272 
10273     notePreMod(O, BO);
10274 
10275     // C++11 [expr.ass]p7:
10276     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10277     //   only once.
10278     //
10279     // Therefore, for a compound assignment operator, O is considered used
10280     // everywhere except within the evaluation of E1 itself.
10281     if (isa<CompoundAssignOperator>(BO))
10282       notePreUse(O, BO);
10283 
10284     Visit(BO->getLHS());
10285 
10286     if (isa<CompoundAssignOperator>(BO))
10287       notePostUse(O, BO);
10288 
10289     Visit(BO->getRHS());
10290 
10291     // C++11 [expr.ass]p1:
10292     //   the assignment is sequenced [...] before the value computation of the
10293     //   assignment expression.
10294     // C11 6.5.16/3 has no such rule.
10295     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10296                                                        : UK_ModAsSideEffect);
10297   }
10298 
10299   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10300     VisitBinAssign(CAO);
10301   }
10302 
10303   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10304   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10305   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10306     Object O = getObject(UO->getSubExpr(), true);
10307     if (!O)
10308       return VisitExpr(UO);
10309 
10310     notePreMod(O, UO);
10311     Visit(UO->getSubExpr());
10312     // C++11 [expr.pre.incr]p1:
10313     //   the expression ++x is equivalent to x+=1
10314     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10315                                                        : UK_ModAsSideEffect);
10316   }
10317 
10318   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10319   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10320   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10321     Object O = getObject(UO->getSubExpr(), true);
10322     if (!O)
10323       return VisitExpr(UO);
10324 
10325     notePreMod(O, UO);
10326     Visit(UO->getSubExpr());
10327     notePostMod(O, UO, UK_ModAsSideEffect);
10328   }
10329 
10330   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10331   void VisitBinLOr(BinaryOperator *BO) {
10332     // The side-effects of the LHS of an '&&' are sequenced before the
10333     // value computation of the RHS, and hence before the value computation
10334     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10335     // as if they were unconditionally sequenced.
10336     EvaluationTracker Eval(*this);
10337     {
10338       SequencedSubexpression Sequenced(*this);
10339       Visit(BO->getLHS());
10340     }
10341 
10342     bool Result;
10343     if (Eval.evaluate(BO->getLHS(), Result)) {
10344       if (!Result)
10345         Visit(BO->getRHS());
10346     } else {
10347       // Check for unsequenced operations in the RHS, treating it as an
10348       // entirely separate evaluation.
10349       //
10350       // FIXME: If there are operations in the RHS which are unsequenced
10351       // with respect to operations outside the RHS, and those operations
10352       // are unconditionally evaluated, diagnose them.
10353       WorkList.push_back(BO->getRHS());
10354     }
10355   }
10356   void VisitBinLAnd(BinaryOperator *BO) {
10357     EvaluationTracker Eval(*this);
10358     {
10359       SequencedSubexpression Sequenced(*this);
10360       Visit(BO->getLHS());
10361     }
10362 
10363     bool Result;
10364     if (Eval.evaluate(BO->getLHS(), Result)) {
10365       if (Result)
10366         Visit(BO->getRHS());
10367     } else {
10368       WorkList.push_back(BO->getRHS());
10369     }
10370   }
10371 
10372   // Only visit the condition, unless we can be sure which subexpression will
10373   // be chosen.
10374   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10375     EvaluationTracker Eval(*this);
10376     {
10377       SequencedSubexpression Sequenced(*this);
10378       Visit(CO->getCond());
10379     }
10380 
10381     bool Result;
10382     if (Eval.evaluate(CO->getCond(), Result))
10383       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10384     else {
10385       WorkList.push_back(CO->getTrueExpr());
10386       WorkList.push_back(CO->getFalseExpr());
10387     }
10388   }
10389 
10390   void VisitCallExpr(CallExpr *CE) {
10391     // C++11 [intro.execution]p15:
10392     //   When calling a function [...], every value computation and side effect
10393     //   associated with any argument expression, or with the postfix expression
10394     //   designating the called function, is sequenced before execution of every
10395     //   expression or statement in the body of the function [and thus before
10396     //   the value computation of its result].
10397     SequencedSubexpression Sequenced(*this);
10398     Base::VisitCallExpr(CE);
10399 
10400     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10401   }
10402 
10403   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10404     // This is a call, so all subexpressions are sequenced before the result.
10405     SequencedSubexpression Sequenced(*this);
10406 
10407     if (!CCE->isListInitialization())
10408       return VisitExpr(CCE);
10409 
10410     // In C++11, list initializations are sequenced.
10411     SmallVector<SequenceTree::Seq, 32> Elts;
10412     SequenceTree::Seq Parent = Region;
10413     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10414                                         E = CCE->arg_end();
10415          I != E; ++I) {
10416       Region = Tree.allocate(Parent);
10417       Elts.push_back(Region);
10418       Visit(*I);
10419     }
10420 
10421     // Forget that the initializers are sequenced.
10422     Region = Parent;
10423     for (unsigned I = 0; I < Elts.size(); ++I)
10424       Tree.merge(Elts[I]);
10425   }
10426 
10427   void VisitInitListExpr(InitListExpr *ILE) {
10428     if (!SemaRef.getLangOpts().CPlusPlus11)
10429       return VisitExpr(ILE);
10430 
10431     // In C++11, list initializations are sequenced.
10432     SmallVector<SequenceTree::Seq, 32> Elts;
10433     SequenceTree::Seq Parent = Region;
10434     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10435       Expr *E = ILE->getInit(I);
10436       if (!E) continue;
10437       Region = Tree.allocate(Parent);
10438       Elts.push_back(Region);
10439       Visit(E);
10440     }
10441 
10442     // Forget that the initializers are sequenced.
10443     Region = Parent;
10444     for (unsigned I = 0; I < Elts.size(); ++I)
10445       Tree.merge(Elts[I]);
10446   }
10447 };
10448 } // end anonymous namespace
10449 
10450 void Sema::CheckUnsequencedOperations(Expr *E) {
10451   SmallVector<Expr *, 8> WorkList;
10452   WorkList.push_back(E);
10453   while (!WorkList.empty()) {
10454     Expr *Item = WorkList.pop_back_val();
10455     SequenceChecker(*this, Item, WorkList);
10456   }
10457 }
10458 
10459 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10460                               bool IsConstexpr) {
10461   CheckImplicitConversions(E, CheckLoc);
10462   if (!E->isInstantiationDependent())
10463     CheckUnsequencedOperations(E);
10464   if (!IsConstexpr && !E->isValueDependent())
10465     CheckForIntOverflow(E);
10466   DiagnoseMisalignedMembers();
10467 }
10468 
10469 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10470                                        FieldDecl *BitField,
10471                                        Expr *Init) {
10472   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10473 }
10474 
10475 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10476                                          SourceLocation Loc) {
10477   if (!PType->isVariablyModifiedType())
10478     return;
10479   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10480     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10481     return;
10482   }
10483   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10484     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10485     return;
10486   }
10487   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10488     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10489     return;
10490   }
10491 
10492   const ArrayType *AT = S.Context.getAsArrayType(PType);
10493   if (!AT)
10494     return;
10495 
10496   if (AT->getSizeModifier() != ArrayType::Star) {
10497     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10498     return;
10499   }
10500 
10501   S.Diag(Loc, diag::err_array_star_in_function_definition);
10502 }
10503 
10504 /// CheckParmsForFunctionDef - Check that the parameters of the given
10505 /// function are appropriate for the definition of a function. This
10506 /// takes care of any checks that cannot be performed on the
10507 /// declaration itself, e.g., that the types of each of the function
10508 /// parameters are complete.
10509 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10510                                     bool CheckParameterNames) {
10511   bool HasInvalidParm = false;
10512   for (ParmVarDecl *Param : Parameters) {
10513     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10514     // function declarator that is part of a function definition of
10515     // that function shall not have incomplete type.
10516     //
10517     // This is also C++ [dcl.fct]p6.
10518     if (!Param->isInvalidDecl() &&
10519         RequireCompleteType(Param->getLocation(), Param->getType(),
10520                             diag::err_typecheck_decl_incomplete_type)) {
10521       Param->setInvalidDecl();
10522       HasInvalidParm = true;
10523     }
10524 
10525     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10526     // declaration of each parameter shall include an identifier.
10527     if (CheckParameterNames &&
10528         Param->getIdentifier() == nullptr &&
10529         !Param->isImplicit() &&
10530         !getLangOpts().CPlusPlus)
10531       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10532 
10533     // C99 6.7.5.3p12:
10534     //   If the function declarator is not part of a definition of that
10535     //   function, parameters may have incomplete type and may use the [*]
10536     //   notation in their sequences of declarator specifiers to specify
10537     //   variable length array types.
10538     QualType PType = Param->getOriginalType();
10539     // FIXME: This diagnostic should point the '[*]' if source-location
10540     // information is added for it.
10541     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10542 
10543     // MSVC destroys objects passed by value in the callee.  Therefore a
10544     // function definition which takes such a parameter must be able to call the
10545     // object's destructor.  However, we don't perform any direct access check
10546     // on the dtor.
10547     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10548                                        .getCXXABI()
10549                                        .areArgsDestroyedLeftToRightInCallee()) {
10550       if (!Param->isInvalidDecl()) {
10551         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10552           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10553           if (!ClassDecl->isInvalidDecl() &&
10554               !ClassDecl->hasIrrelevantDestructor() &&
10555               !ClassDecl->isDependentContext()) {
10556             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10557             MarkFunctionReferenced(Param->getLocation(), Destructor);
10558             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10559           }
10560         }
10561       }
10562     }
10563 
10564     // Parameters with the pass_object_size attribute only need to be marked
10565     // constant at function definitions. Because we lack information about
10566     // whether we're on a declaration or definition when we're instantiating the
10567     // attribute, we need to check for constness here.
10568     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10569       if (!Param->getType().isConstQualified())
10570         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10571             << Attr->getSpelling() << 1;
10572   }
10573 
10574   return HasInvalidParm;
10575 }
10576 
10577 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10578 /// or MemberExpr.
10579 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10580                               ASTContext &Context) {
10581   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10582     return Context.getDeclAlign(DRE->getDecl());
10583 
10584   if (const auto *ME = dyn_cast<MemberExpr>(E))
10585     return Context.getDeclAlign(ME->getMemberDecl());
10586 
10587   return TypeAlign;
10588 }
10589 
10590 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10591 /// pointer cast increases the alignment requirements.
10592 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10593   // This is actually a lot of work to potentially be doing on every
10594   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10595   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10596     return;
10597 
10598   // Ignore dependent types.
10599   if (T->isDependentType() || Op->getType()->isDependentType())
10600     return;
10601 
10602   // Require that the destination be a pointer type.
10603   const PointerType *DestPtr = T->getAs<PointerType>();
10604   if (!DestPtr) return;
10605 
10606   // If the destination has alignment 1, we're done.
10607   QualType DestPointee = DestPtr->getPointeeType();
10608   if (DestPointee->isIncompleteType()) return;
10609   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10610   if (DestAlign.isOne()) return;
10611 
10612   // Require that the source be a pointer type.
10613   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10614   if (!SrcPtr) return;
10615   QualType SrcPointee = SrcPtr->getPointeeType();
10616 
10617   // Whitelist casts from cv void*.  We already implicitly
10618   // whitelisted casts to cv void*, since they have alignment 1.
10619   // Also whitelist casts involving incomplete types, which implicitly
10620   // includes 'void'.
10621   if (SrcPointee->isIncompleteType()) return;
10622 
10623   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10624 
10625   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10626     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10627       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10628   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10629     if (UO->getOpcode() == UO_AddrOf)
10630       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10631   }
10632 
10633   if (SrcAlign >= DestAlign) return;
10634 
10635   Diag(TRange.getBegin(), diag::warn_cast_align)
10636     << Op->getType() << T
10637     << static_cast<unsigned>(SrcAlign.getQuantity())
10638     << static_cast<unsigned>(DestAlign.getQuantity())
10639     << TRange << Op->getSourceRange();
10640 }
10641 
10642 /// \brief Check whether this array fits the idiom of a size-one tail padded
10643 /// array member of a struct.
10644 ///
10645 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10646 /// commonly used to emulate flexible arrays in C89 code.
10647 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10648                                     const NamedDecl *ND) {
10649   if (Size != 1 || !ND) return false;
10650 
10651   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10652   if (!FD) return false;
10653 
10654   // Don't consider sizes resulting from macro expansions or template argument
10655   // substitution to form C89 tail-padded arrays.
10656 
10657   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10658   while (TInfo) {
10659     TypeLoc TL = TInfo->getTypeLoc();
10660     // Look through typedefs.
10661     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10662       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10663       TInfo = TDL->getTypeSourceInfo();
10664       continue;
10665     }
10666     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10667       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10668       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10669         return false;
10670     }
10671     break;
10672   }
10673 
10674   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10675   if (!RD) return false;
10676   if (RD->isUnion()) return false;
10677   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10678     if (!CRD->isStandardLayout()) return false;
10679   }
10680 
10681   // See if this is the last field decl in the record.
10682   const Decl *D = FD;
10683   while ((D = D->getNextDeclInContext()))
10684     if (isa<FieldDecl>(D))
10685       return false;
10686   return true;
10687 }
10688 
10689 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10690                             const ArraySubscriptExpr *ASE,
10691                             bool AllowOnePastEnd, bool IndexNegated) {
10692   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10693   if (IndexExpr->isValueDependent())
10694     return;
10695 
10696   const Type *EffectiveType =
10697       BaseExpr->getType()->getPointeeOrArrayElementType();
10698   BaseExpr = BaseExpr->IgnoreParenCasts();
10699   const ConstantArrayType *ArrayTy =
10700     Context.getAsConstantArrayType(BaseExpr->getType());
10701   if (!ArrayTy)
10702     return;
10703 
10704   llvm::APSInt index;
10705   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10706     return;
10707   if (IndexNegated)
10708     index = -index;
10709 
10710   const NamedDecl *ND = nullptr;
10711   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10712     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10713   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10714     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10715 
10716   if (index.isUnsigned() || !index.isNegative()) {
10717     llvm::APInt size = ArrayTy->getSize();
10718     if (!size.isStrictlyPositive())
10719       return;
10720 
10721     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10722     if (BaseType != EffectiveType) {
10723       // Make sure we're comparing apples to apples when comparing index to size
10724       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10725       uint64_t array_typesize = Context.getTypeSize(BaseType);
10726       // Handle ptrarith_typesize being zero, such as when casting to void*
10727       if (!ptrarith_typesize) ptrarith_typesize = 1;
10728       if (ptrarith_typesize != array_typesize) {
10729         // There's a cast to a different size type involved
10730         uint64_t ratio = array_typesize / ptrarith_typesize;
10731         // TODO: Be smarter about handling cases where array_typesize is not a
10732         // multiple of ptrarith_typesize
10733         if (ptrarith_typesize * ratio == array_typesize)
10734           size *= llvm::APInt(size.getBitWidth(), ratio);
10735       }
10736     }
10737 
10738     if (size.getBitWidth() > index.getBitWidth())
10739       index = index.zext(size.getBitWidth());
10740     else if (size.getBitWidth() < index.getBitWidth())
10741       size = size.zext(index.getBitWidth());
10742 
10743     // For array subscripting the index must be less than size, but for pointer
10744     // arithmetic also allow the index (offset) to be equal to size since
10745     // computing the next address after the end of the array is legal and
10746     // commonly done e.g. in C++ iterators and range-based for loops.
10747     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10748       return;
10749 
10750     // Also don't warn for arrays of size 1 which are members of some
10751     // structure. These are often used to approximate flexible arrays in C89
10752     // code.
10753     if (IsTailPaddedMemberArray(*this, size, ND))
10754       return;
10755 
10756     // Suppress the warning if the subscript expression (as identified by the
10757     // ']' location) and the index expression are both from macro expansions
10758     // within a system header.
10759     if (ASE) {
10760       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10761           ASE->getRBracketLoc());
10762       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10763         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10764             IndexExpr->getLocStart());
10765         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10766           return;
10767       }
10768     }
10769 
10770     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10771     if (ASE)
10772       DiagID = diag::warn_array_index_exceeds_bounds;
10773 
10774     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10775                         PDiag(DiagID) << index.toString(10, true)
10776                           << size.toString(10, true)
10777                           << (unsigned)size.getLimitedValue(~0U)
10778                           << IndexExpr->getSourceRange());
10779   } else {
10780     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10781     if (!ASE) {
10782       DiagID = diag::warn_ptr_arith_precedes_bounds;
10783       if (index.isNegative()) index = -index;
10784     }
10785 
10786     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10787                         PDiag(DiagID) << index.toString(10, true)
10788                           << IndexExpr->getSourceRange());
10789   }
10790 
10791   if (!ND) {
10792     // Try harder to find a NamedDecl to point at in the note.
10793     while (const ArraySubscriptExpr *ASE =
10794            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10795       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10796     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10797       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10798     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10799       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10800   }
10801 
10802   if (ND)
10803     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10804                         PDiag(diag::note_array_index_out_of_bounds)
10805                           << ND->getDeclName());
10806 }
10807 
10808 void Sema::CheckArrayAccess(const Expr *expr) {
10809   int AllowOnePastEnd = 0;
10810   while (expr) {
10811     expr = expr->IgnoreParenImpCasts();
10812     switch (expr->getStmtClass()) {
10813       case Stmt::ArraySubscriptExprClass: {
10814         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10815         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10816                          AllowOnePastEnd > 0);
10817         return;
10818       }
10819       case Stmt::OMPArraySectionExprClass: {
10820         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10821         if (ASE->getLowerBound())
10822           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10823                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
10824         return;
10825       }
10826       case Stmt::UnaryOperatorClass: {
10827         // Only unwrap the * and & unary operators
10828         const UnaryOperator *UO = cast<UnaryOperator>(expr);
10829         expr = UO->getSubExpr();
10830         switch (UO->getOpcode()) {
10831           case UO_AddrOf:
10832             AllowOnePastEnd++;
10833             break;
10834           case UO_Deref:
10835             AllowOnePastEnd--;
10836             break;
10837           default:
10838             return;
10839         }
10840         break;
10841       }
10842       case Stmt::ConditionalOperatorClass: {
10843         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10844         if (const Expr *lhs = cond->getLHS())
10845           CheckArrayAccess(lhs);
10846         if (const Expr *rhs = cond->getRHS())
10847           CheckArrayAccess(rhs);
10848         return;
10849       }
10850       case Stmt::CXXOperatorCallExprClass: {
10851         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10852         for (const auto *Arg : OCE->arguments())
10853           CheckArrayAccess(Arg);
10854         return;
10855       }
10856       default:
10857         return;
10858     }
10859   }
10860 }
10861 
10862 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10863 
10864 namespace {
10865   struct RetainCycleOwner {
10866     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10867     VarDecl *Variable;
10868     SourceRange Range;
10869     SourceLocation Loc;
10870     bool Indirect;
10871 
10872     void setLocsFrom(Expr *e) {
10873       Loc = e->getExprLoc();
10874       Range = e->getSourceRange();
10875     }
10876   };
10877 } // end anonymous namespace
10878 
10879 /// Consider whether capturing the given variable can possibly lead to
10880 /// a retain cycle.
10881 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10882   // In ARC, it's captured strongly iff the variable has __strong
10883   // lifetime.  In MRR, it's captured strongly if the variable is
10884   // __block and has an appropriate type.
10885   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10886     return false;
10887 
10888   owner.Variable = var;
10889   if (ref)
10890     owner.setLocsFrom(ref);
10891   return true;
10892 }
10893 
10894 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10895   while (true) {
10896     e = e->IgnoreParens();
10897     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10898       switch (cast->getCastKind()) {
10899       case CK_BitCast:
10900       case CK_LValueBitCast:
10901       case CK_LValueToRValue:
10902       case CK_ARCReclaimReturnedObject:
10903         e = cast->getSubExpr();
10904         continue;
10905 
10906       default:
10907         return false;
10908       }
10909     }
10910 
10911     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10912       ObjCIvarDecl *ivar = ref->getDecl();
10913       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10914         return false;
10915 
10916       // Try to find a retain cycle in the base.
10917       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10918         return false;
10919 
10920       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10921       owner.Indirect = true;
10922       return true;
10923     }
10924 
10925     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10926       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10927       if (!var) return false;
10928       return considerVariable(var, ref, owner);
10929     }
10930 
10931     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10932       if (member->isArrow()) return false;
10933 
10934       // Don't count this as an indirect ownership.
10935       e = member->getBase();
10936       continue;
10937     }
10938 
10939     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10940       // Only pay attention to pseudo-objects on property references.
10941       ObjCPropertyRefExpr *pre
10942         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10943                                               ->IgnoreParens());
10944       if (!pre) return false;
10945       if (pre->isImplicitProperty()) return false;
10946       ObjCPropertyDecl *property = pre->getExplicitProperty();
10947       if (!property->isRetaining() &&
10948           !(property->getPropertyIvarDecl() &&
10949             property->getPropertyIvarDecl()->getType()
10950               .getObjCLifetime() == Qualifiers::OCL_Strong))
10951           return false;
10952 
10953       owner.Indirect = true;
10954       if (pre->isSuperReceiver()) {
10955         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10956         if (!owner.Variable)
10957           return false;
10958         owner.Loc = pre->getLocation();
10959         owner.Range = pre->getSourceRange();
10960         return true;
10961       }
10962       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10963                               ->getSourceExpr());
10964       continue;
10965     }
10966 
10967     // Array ivars?
10968 
10969     return false;
10970   }
10971 }
10972 
10973 namespace {
10974   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10975     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10976       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10977         Context(Context), Variable(variable), Capturer(nullptr),
10978         VarWillBeReased(false) {}
10979     ASTContext &Context;
10980     VarDecl *Variable;
10981     Expr *Capturer;
10982     bool VarWillBeReased;
10983 
10984     void VisitDeclRefExpr(DeclRefExpr *ref) {
10985       if (ref->getDecl() == Variable && !Capturer)
10986         Capturer = ref;
10987     }
10988 
10989     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10990       if (Capturer) return;
10991       Visit(ref->getBase());
10992       if (Capturer && ref->isFreeIvar())
10993         Capturer = ref;
10994     }
10995 
10996     void VisitBlockExpr(BlockExpr *block) {
10997       // Look inside nested blocks
10998       if (block->getBlockDecl()->capturesVariable(Variable))
10999         Visit(block->getBlockDecl()->getBody());
11000     }
11001 
11002     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11003       if (Capturer) return;
11004       if (OVE->getSourceExpr())
11005         Visit(OVE->getSourceExpr());
11006     }
11007     void VisitBinaryOperator(BinaryOperator *BinOp) {
11008       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11009         return;
11010       Expr *LHS = BinOp->getLHS();
11011       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11012         if (DRE->getDecl() != Variable)
11013           return;
11014         if (Expr *RHS = BinOp->getRHS()) {
11015           RHS = RHS->IgnoreParenCasts();
11016           llvm::APSInt Value;
11017           VarWillBeReased =
11018             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11019         }
11020       }
11021     }
11022   };
11023 } // end anonymous namespace
11024 
11025 /// Check whether the given argument is a block which captures a
11026 /// variable.
11027 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11028   assert(owner.Variable && owner.Loc.isValid());
11029 
11030   e = e->IgnoreParenCasts();
11031 
11032   // Look through [^{...} copy] and Block_copy(^{...}).
11033   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11034     Selector Cmd = ME->getSelector();
11035     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11036       e = ME->getInstanceReceiver();
11037       if (!e)
11038         return nullptr;
11039       e = e->IgnoreParenCasts();
11040     }
11041   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11042     if (CE->getNumArgs() == 1) {
11043       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11044       if (Fn) {
11045         const IdentifierInfo *FnI = Fn->getIdentifier();
11046         if (FnI && FnI->isStr("_Block_copy")) {
11047           e = CE->getArg(0)->IgnoreParenCasts();
11048         }
11049       }
11050     }
11051   }
11052 
11053   BlockExpr *block = dyn_cast<BlockExpr>(e);
11054   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11055     return nullptr;
11056 
11057   FindCaptureVisitor visitor(S.Context, owner.Variable);
11058   visitor.Visit(block->getBlockDecl()->getBody());
11059   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11060 }
11061 
11062 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11063                                 RetainCycleOwner &owner) {
11064   assert(capturer);
11065   assert(owner.Variable && owner.Loc.isValid());
11066 
11067   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11068     << owner.Variable << capturer->getSourceRange();
11069   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11070     << owner.Indirect << owner.Range;
11071 }
11072 
11073 /// Check for a keyword selector that starts with the word 'add' or
11074 /// 'set'.
11075 static bool isSetterLikeSelector(Selector sel) {
11076   if (sel.isUnarySelector()) return false;
11077 
11078   StringRef str = sel.getNameForSlot(0);
11079   while (!str.empty() && str.front() == '_') str = str.substr(1);
11080   if (str.startswith("set"))
11081     str = str.substr(3);
11082   else if (str.startswith("add")) {
11083     // Specially whitelist 'addOperationWithBlock:'.
11084     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11085       return false;
11086     str = str.substr(3);
11087   }
11088   else
11089     return false;
11090 
11091   if (str.empty()) return true;
11092   return !isLowercase(str.front());
11093 }
11094 
11095 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11096                                                     ObjCMessageExpr *Message) {
11097   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11098                                                 Message->getReceiverInterface(),
11099                                                 NSAPI::ClassId_NSMutableArray);
11100   if (!IsMutableArray) {
11101     return None;
11102   }
11103 
11104   Selector Sel = Message->getSelector();
11105 
11106   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11107     S.NSAPIObj->getNSArrayMethodKind(Sel);
11108   if (!MKOpt) {
11109     return None;
11110   }
11111 
11112   NSAPI::NSArrayMethodKind MK = *MKOpt;
11113 
11114   switch (MK) {
11115     case NSAPI::NSMutableArr_addObject:
11116     case NSAPI::NSMutableArr_insertObjectAtIndex:
11117     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11118       return 0;
11119     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11120       return 1;
11121 
11122     default:
11123       return None;
11124   }
11125 
11126   return None;
11127 }
11128 
11129 static
11130 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11131                                                   ObjCMessageExpr *Message) {
11132   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11133                                             Message->getReceiverInterface(),
11134                                             NSAPI::ClassId_NSMutableDictionary);
11135   if (!IsMutableDictionary) {
11136     return None;
11137   }
11138 
11139   Selector Sel = Message->getSelector();
11140 
11141   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11142     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11143   if (!MKOpt) {
11144     return None;
11145   }
11146 
11147   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11148 
11149   switch (MK) {
11150     case NSAPI::NSMutableDict_setObjectForKey:
11151     case NSAPI::NSMutableDict_setValueForKey:
11152     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11153       return 0;
11154 
11155     default:
11156       return None;
11157   }
11158 
11159   return None;
11160 }
11161 
11162 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11163   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11164                                                 Message->getReceiverInterface(),
11165                                                 NSAPI::ClassId_NSMutableSet);
11166 
11167   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11168                                             Message->getReceiverInterface(),
11169                                             NSAPI::ClassId_NSMutableOrderedSet);
11170   if (!IsMutableSet && !IsMutableOrderedSet) {
11171     return None;
11172   }
11173 
11174   Selector Sel = Message->getSelector();
11175 
11176   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11177   if (!MKOpt) {
11178     return None;
11179   }
11180 
11181   NSAPI::NSSetMethodKind MK = *MKOpt;
11182 
11183   switch (MK) {
11184     case NSAPI::NSMutableSet_addObject:
11185     case NSAPI::NSOrderedSet_setObjectAtIndex:
11186     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11187     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11188       return 0;
11189     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11190       return 1;
11191   }
11192 
11193   return None;
11194 }
11195 
11196 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11197   if (!Message->isInstanceMessage()) {
11198     return;
11199   }
11200 
11201   Optional<int> ArgOpt;
11202 
11203   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11204       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11205       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11206     return;
11207   }
11208 
11209   int ArgIndex = *ArgOpt;
11210 
11211   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11212   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11213     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11214   }
11215 
11216   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11217     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11218       if (ArgRE->isObjCSelfExpr()) {
11219         Diag(Message->getSourceRange().getBegin(),
11220              diag::warn_objc_circular_container)
11221           << ArgRE->getDecl()->getName() << StringRef("super");
11222       }
11223     }
11224   } else {
11225     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11226 
11227     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11228       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11229     }
11230 
11231     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11232       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11233         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11234           ValueDecl *Decl = ReceiverRE->getDecl();
11235           Diag(Message->getSourceRange().getBegin(),
11236                diag::warn_objc_circular_container)
11237             << Decl->getName() << Decl->getName();
11238           if (!ArgRE->isObjCSelfExpr()) {
11239             Diag(Decl->getLocation(),
11240                  diag::note_objc_circular_container_declared_here)
11241               << Decl->getName();
11242           }
11243         }
11244       }
11245     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11246       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11247         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11248           ObjCIvarDecl *Decl = IvarRE->getDecl();
11249           Diag(Message->getSourceRange().getBegin(),
11250                diag::warn_objc_circular_container)
11251             << Decl->getName() << Decl->getName();
11252           Diag(Decl->getLocation(),
11253                diag::note_objc_circular_container_declared_here)
11254             << Decl->getName();
11255         }
11256       }
11257     }
11258   }
11259 }
11260 
11261 /// Check a message send to see if it's likely to cause a retain cycle.
11262 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11263   // Only check instance methods whose selector looks like a setter.
11264   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11265     return;
11266 
11267   // Try to find a variable that the receiver is strongly owned by.
11268   RetainCycleOwner owner;
11269   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11270     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11271       return;
11272   } else {
11273     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11274     owner.Variable = getCurMethodDecl()->getSelfDecl();
11275     owner.Loc = msg->getSuperLoc();
11276     owner.Range = msg->getSuperLoc();
11277   }
11278 
11279   // Check whether the receiver is captured by any of the arguments.
11280   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11281     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11282       return diagnoseRetainCycle(*this, capturer, owner);
11283 }
11284 
11285 /// Check a property assign to see if it's likely to cause a retain cycle.
11286 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11287   RetainCycleOwner owner;
11288   if (!findRetainCycleOwner(*this, receiver, owner))
11289     return;
11290 
11291   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11292     diagnoseRetainCycle(*this, capturer, owner);
11293 }
11294 
11295 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11296   RetainCycleOwner Owner;
11297   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11298     return;
11299 
11300   // Because we don't have an expression for the variable, we have to set the
11301   // location explicitly here.
11302   Owner.Loc = Var->getLocation();
11303   Owner.Range = Var->getSourceRange();
11304 
11305   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11306     diagnoseRetainCycle(*this, Capturer, Owner);
11307 }
11308 
11309 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11310                                      Expr *RHS, bool isProperty) {
11311   // Check if RHS is an Objective-C object literal, which also can get
11312   // immediately zapped in a weak reference.  Note that we explicitly
11313   // allow ObjCStringLiterals, since those are designed to never really die.
11314   RHS = RHS->IgnoreParenImpCasts();
11315 
11316   // This enum needs to match with the 'select' in
11317   // warn_objc_arc_literal_assign (off-by-1).
11318   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11319   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11320     return false;
11321 
11322   S.Diag(Loc, diag::warn_arc_literal_assign)
11323     << (unsigned) Kind
11324     << (isProperty ? 0 : 1)
11325     << RHS->getSourceRange();
11326 
11327   return true;
11328 }
11329 
11330 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11331                                     Qualifiers::ObjCLifetime LT,
11332                                     Expr *RHS, bool isProperty) {
11333   // Strip off any implicit cast added to get to the one ARC-specific.
11334   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11335     if (cast->getCastKind() == CK_ARCConsumeObject) {
11336       S.Diag(Loc, diag::warn_arc_retained_assign)
11337         << (LT == Qualifiers::OCL_ExplicitNone)
11338         << (isProperty ? 0 : 1)
11339         << RHS->getSourceRange();
11340       return true;
11341     }
11342     RHS = cast->getSubExpr();
11343   }
11344 
11345   if (LT == Qualifiers::OCL_Weak &&
11346       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11347     return true;
11348 
11349   return false;
11350 }
11351 
11352 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11353                               QualType LHS, Expr *RHS) {
11354   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11355 
11356   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11357     return false;
11358 
11359   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11360     return true;
11361 
11362   return false;
11363 }
11364 
11365 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11366                               Expr *LHS, Expr *RHS) {
11367   QualType LHSType;
11368   // PropertyRef on LHS type need be directly obtained from
11369   // its declaration as it has a PseudoType.
11370   ObjCPropertyRefExpr *PRE
11371     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11372   if (PRE && !PRE->isImplicitProperty()) {
11373     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11374     if (PD)
11375       LHSType = PD->getType();
11376   }
11377 
11378   if (LHSType.isNull())
11379     LHSType = LHS->getType();
11380 
11381   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11382 
11383   if (LT == Qualifiers::OCL_Weak) {
11384     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11385       getCurFunction()->markSafeWeakUse(LHS);
11386   }
11387 
11388   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11389     return;
11390 
11391   // FIXME. Check for other life times.
11392   if (LT != Qualifiers::OCL_None)
11393     return;
11394 
11395   if (PRE) {
11396     if (PRE->isImplicitProperty())
11397       return;
11398     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11399     if (!PD)
11400       return;
11401 
11402     unsigned Attributes = PD->getPropertyAttributes();
11403     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11404       // when 'assign' attribute was not explicitly specified
11405       // by user, ignore it and rely on property type itself
11406       // for lifetime info.
11407       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11408       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11409           LHSType->isObjCRetainableType())
11410         return;
11411 
11412       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11413         if (cast->getCastKind() == CK_ARCConsumeObject) {
11414           Diag(Loc, diag::warn_arc_retained_property_assign)
11415           << RHS->getSourceRange();
11416           return;
11417         }
11418         RHS = cast->getSubExpr();
11419       }
11420     }
11421     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11422       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11423         return;
11424     }
11425   }
11426 }
11427 
11428 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11429 
11430 namespace {
11431 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11432                                  SourceLocation StmtLoc,
11433                                  const NullStmt *Body) {
11434   // Do not warn if the body is a macro that expands to nothing, e.g:
11435   //
11436   // #define CALL(x)
11437   // if (condition)
11438   //   CALL(0);
11439   //
11440   if (Body->hasLeadingEmptyMacro())
11441     return false;
11442 
11443   // Get line numbers of statement and body.
11444   bool StmtLineInvalid;
11445   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11446                                                       &StmtLineInvalid);
11447   if (StmtLineInvalid)
11448     return false;
11449 
11450   bool BodyLineInvalid;
11451   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11452                                                       &BodyLineInvalid);
11453   if (BodyLineInvalid)
11454     return false;
11455 
11456   // Warn if null statement and body are on the same line.
11457   if (StmtLine != BodyLine)
11458     return false;
11459 
11460   return true;
11461 }
11462 } // end anonymous namespace
11463 
11464 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11465                                  const Stmt *Body,
11466                                  unsigned DiagID) {
11467   // Since this is a syntactic check, don't emit diagnostic for template
11468   // instantiations, this just adds noise.
11469   if (CurrentInstantiationScope)
11470     return;
11471 
11472   // The body should be a null statement.
11473   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11474   if (!NBody)
11475     return;
11476 
11477   // Do the usual checks.
11478   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11479     return;
11480 
11481   Diag(NBody->getSemiLoc(), DiagID);
11482   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11483 }
11484 
11485 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11486                                  const Stmt *PossibleBody) {
11487   assert(!CurrentInstantiationScope); // Ensured by caller
11488 
11489   SourceLocation StmtLoc;
11490   const Stmt *Body;
11491   unsigned DiagID;
11492   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11493     StmtLoc = FS->getRParenLoc();
11494     Body = FS->getBody();
11495     DiagID = diag::warn_empty_for_body;
11496   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11497     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11498     Body = WS->getBody();
11499     DiagID = diag::warn_empty_while_body;
11500   } else
11501     return; // Neither `for' nor `while'.
11502 
11503   // The body should be a null statement.
11504   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11505   if (!NBody)
11506     return;
11507 
11508   // Skip expensive checks if diagnostic is disabled.
11509   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11510     return;
11511 
11512   // Do the usual checks.
11513   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11514     return;
11515 
11516   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11517   // noise level low, emit diagnostics only if for/while is followed by a
11518   // CompoundStmt, e.g.:
11519   //    for (int i = 0; i < n; i++);
11520   //    {
11521   //      a(i);
11522   //    }
11523   // or if for/while is followed by a statement with more indentation
11524   // than for/while itself:
11525   //    for (int i = 0; i < n; i++);
11526   //      a(i);
11527   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11528   if (!ProbableTypo) {
11529     bool BodyColInvalid;
11530     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11531                              PossibleBody->getLocStart(),
11532                              &BodyColInvalid);
11533     if (BodyColInvalid)
11534       return;
11535 
11536     bool StmtColInvalid;
11537     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11538                              S->getLocStart(),
11539                              &StmtColInvalid);
11540     if (StmtColInvalid)
11541       return;
11542 
11543     if (BodyCol > StmtCol)
11544       ProbableTypo = true;
11545   }
11546 
11547   if (ProbableTypo) {
11548     Diag(NBody->getSemiLoc(), DiagID);
11549     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11550   }
11551 }
11552 
11553 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11554 
11555 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11556 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11557                              SourceLocation OpLoc) {
11558   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11559     return;
11560 
11561   if (inTemplateInstantiation())
11562     return;
11563 
11564   // Strip parens and casts away.
11565   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11566   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11567 
11568   // Check for a call expression
11569   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11570   if (!CE || CE->getNumArgs() != 1)
11571     return;
11572 
11573   // Check for a call to std::move
11574   const FunctionDecl *FD = CE->getDirectCallee();
11575   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11576       !FD->getIdentifier()->isStr("move"))
11577     return;
11578 
11579   // Get argument from std::move
11580   RHSExpr = CE->getArg(0);
11581 
11582   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11583   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11584 
11585   // Two DeclRefExpr's, check that the decls are the same.
11586   if (LHSDeclRef && RHSDeclRef) {
11587     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11588       return;
11589     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11590         RHSDeclRef->getDecl()->getCanonicalDecl())
11591       return;
11592 
11593     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11594                                         << LHSExpr->getSourceRange()
11595                                         << RHSExpr->getSourceRange();
11596     return;
11597   }
11598 
11599   // Member variables require a different approach to check for self moves.
11600   // MemberExpr's are the same if every nested MemberExpr refers to the same
11601   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11602   // the base Expr's are CXXThisExpr's.
11603   const Expr *LHSBase = LHSExpr;
11604   const Expr *RHSBase = RHSExpr;
11605   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11606   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11607   if (!LHSME || !RHSME)
11608     return;
11609 
11610   while (LHSME && RHSME) {
11611     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11612         RHSME->getMemberDecl()->getCanonicalDecl())
11613       return;
11614 
11615     LHSBase = LHSME->getBase();
11616     RHSBase = RHSME->getBase();
11617     LHSME = dyn_cast<MemberExpr>(LHSBase);
11618     RHSME = dyn_cast<MemberExpr>(RHSBase);
11619   }
11620 
11621   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11622   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11623   if (LHSDeclRef && RHSDeclRef) {
11624     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11625       return;
11626     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11627         RHSDeclRef->getDecl()->getCanonicalDecl())
11628       return;
11629 
11630     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11631                                         << LHSExpr->getSourceRange()
11632                                         << RHSExpr->getSourceRange();
11633     return;
11634   }
11635 
11636   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11637     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11638                                         << LHSExpr->getSourceRange()
11639                                         << RHSExpr->getSourceRange();
11640 }
11641 
11642 //===--- Layout compatibility ----------------------------------------------//
11643 
11644 namespace {
11645 
11646 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11647 
11648 /// \brief Check if two enumeration types are layout-compatible.
11649 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11650   // C++11 [dcl.enum] p8:
11651   // Two enumeration types are layout-compatible if they have the same
11652   // underlying type.
11653   return ED1->isComplete() && ED2->isComplete() &&
11654          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11655 }
11656 
11657 /// \brief Check if two fields are layout-compatible.
11658 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11659   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11660     return false;
11661 
11662   if (Field1->isBitField() != Field2->isBitField())
11663     return false;
11664 
11665   if (Field1->isBitField()) {
11666     // Make sure that the bit-fields are the same length.
11667     unsigned Bits1 = Field1->getBitWidthValue(C);
11668     unsigned Bits2 = Field2->getBitWidthValue(C);
11669 
11670     if (Bits1 != Bits2)
11671       return false;
11672   }
11673 
11674   return true;
11675 }
11676 
11677 /// \brief Check if two standard-layout structs are layout-compatible.
11678 /// (C++11 [class.mem] p17)
11679 bool isLayoutCompatibleStruct(ASTContext &C,
11680                               RecordDecl *RD1,
11681                               RecordDecl *RD2) {
11682   // If both records are C++ classes, check that base classes match.
11683   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11684     // If one of records is a CXXRecordDecl we are in C++ mode,
11685     // thus the other one is a CXXRecordDecl, too.
11686     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11687     // Check number of base classes.
11688     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11689       return false;
11690 
11691     // Check the base classes.
11692     for (CXXRecordDecl::base_class_const_iterator
11693                Base1 = D1CXX->bases_begin(),
11694            BaseEnd1 = D1CXX->bases_end(),
11695               Base2 = D2CXX->bases_begin();
11696          Base1 != BaseEnd1;
11697          ++Base1, ++Base2) {
11698       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11699         return false;
11700     }
11701   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11702     // If only RD2 is a C++ class, it should have zero base classes.
11703     if (D2CXX->getNumBases() > 0)
11704       return false;
11705   }
11706 
11707   // Check the fields.
11708   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11709                              Field2End = RD2->field_end(),
11710                              Field1 = RD1->field_begin(),
11711                              Field1End = RD1->field_end();
11712   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11713     if (!isLayoutCompatible(C, *Field1, *Field2))
11714       return false;
11715   }
11716   if (Field1 != Field1End || Field2 != Field2End)
11717     return false;
11718 
11719   return true;
11720 }
11721 
11722 /// \brief Check if two standard-layout unions are layout-compatible.
11723 /// (C++11 [class.mem] p18)
11724 bool isLayoutCompatibleUnion(ASTContext &C,
11725                              RecordDecl *RD1,
11726                              RecordDecl *RD2) {
11727   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11728   for (auto *Field2 : RD2->fields())
11729     UnmatchedFields.insert(Field2);
11730 
11731   for (auto *Field1 : RD1->fields()) {
11732     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11733         I = UnmatchedFields.begin(),
11734         E = UnmatchedFields.end();
11735 
11736     for ( ; I != E; ++I) {
11737       if (isLayoutCompatible(C, Field1, *I)) {
11738         bool Result = UnmatchedFields.erase(*I);
11739         (void) Result;
11740         assert(Result);
11741         break;
11742       }
11743     }
11744     if (I == E)
11745       return false;
11746   }
11747 
11748   return UnmatchedFields.empty();
11749 }
11750 
11751 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11752   if (RD1->isUnion() != RD2->isUnion())
11753     return false;
11754 
11755   if (RD1->isUnion())
11756     return isLayoutCompatibleUnion(C, RD1, RD2);
11757   else
11758     return isLayoutCompatibleStruct(C, RD1, RD2);
11759 }
11760 
11761 /// \brief Check if two types are layout-compatible in C++11 sense.
11762 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11763   if (T1.isNull() || T2.isNull())
11764     return false;
11765 
11766   // C++11 [basic.types] p11:
11767   // If two types T1 and T2 are the same type, then T1 and T2 are
11768   // layout-compatible types.
11769   if (C.hasSameType(T1, T2))
11770     return true;
11771 
11772   T1 = T1.getCanonicalType().getUnqualifiedType();
11773   T2 = T2.getCanonicalType().getUnqualifiedType();
11774 
11775   const Type::TypeClass TC1 = T1->getTypeClass();
11776   const Type::TypeClass TC2 = T2->getTypeClass();
11777 
11778   if (TC1 != TC2)
11779     return false;
11780 
11781   if (TC1 == Type::Enum) {
11782     return isLayoutCompatible(C,
11783                               cast<EnumType>(T1)->getDecl(),
11784                               cast<EnumType>(T2)->getDecl());
11785   } else if (TC1 == Type::Record) {
11786     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11787       return false;
11788 
11789     return isLayoutCompatible(C,
11790                               cast<RecordType>(T1)->getDecl(),
11791                               cast<RecordType>(T2)->getDecl());
11792   }
11793 
11794   return false;
11795 }
11796 } // end anonymous namespace
11797 
11798 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11799 
11800 namespace {
11801 /// \brief Given a type tag expression find the type tag itself.
11802 ///
11803 /// \param TypeExpr Type tag expression, as it appears in user's code.
11804 ///
11805 /// \param VD Declaration of an identifier that appears in a type tag.
11806 ///
11807 /// \param MagicValue Type tag magic value.
11808 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11809                      const ValueDecl **VD, uint64_t *MagicValue) {
11810   while(true) {
11811     if (!TypeExpr)
11812       return false;
11813 
11814     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11815 
11816     switch (TypeExpr->getStmtClass()) {
11817     case Stmt::UnaryOperatorClass: {
11818       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11819       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11820         TypeExpr = UO->getSubExpr();
11821         continue;
11822       }
11823       return false;
11824     }
11825 
11826     case Stmt::DeclRefExprClass: {
11827       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11828       *VD = DRE->getDecl();
11829       return true;
11830     }
11831 
11832     case Stmt::IntegerLiteralClass: {
11833       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11834       llvm::APInt MagicValueAPInt = IL->getValue();
11835       if (MagicValueAPInt.getActiveBits() <= 64) {
11836         *MagicValue = MagicValueAPInt.getZExtValue();
11837         return true;
11838       } else
11839         return false;
11840     }
11841 
11842     case Stmt::BinaryConditionalOperatorClass:
11843     case Stmt::ConditionalOperatorClass: {
11844       const AbstractConditionalOperator *ACO =
11845           cast<AbstractConditionalOperator>(TypeExpr);
11846       bool Result;
11847       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11848         if (Result)
11849           TypeExpr = ACO->getTrueExpr();
11850         else
11851           TypeExpr = ACO->getFalseExpr();
11852         continue;
11853       }
11854       return false;
11855     }
11856 
11857     case Stmt::BinaryOperatorClass: {
11858       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11859       if (BO->getOpcode() == BO_Comma) {
11860         TypeExpr = BO->getRHS();
11861         continue;
11862       }
11863       return false;
11864     }
11865 
11866     default:
11867       return false;
11868     }
11869   }
11870 }
11871 
11872 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11873 ///
11874 /// \param TypeExpr Expression that specifies a type tag.
11875 ///
11876 /// \param MagicValues Registered magic values.
11877 ///
11878 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11879 ///        kind.
11880 ///
11881 /// \param TypeInfo Information about the corresponding C type.
11882 ///
11883 /// \returns true if the corresponding C type was found.
11884 bool GetMatchingCType(
11885         const IdentifierInfo *ArgumentKind,
11886         const Expr *TypeExpr, const ASTContext &Ctx,
11887         const llvm::DenseMap<Sema::TypeTagMagicValue,
11888                              Sema::TypeTagData> *MagicValues,
11889         bool &FoundWrongKind,
11890         Sema::TypeTagData &TypeInfo) {
11891   FoundWrongKind = false;
11892 
11893   // Variable declaration that has type_tag_for_datatype attribute.
11894   const ValueDecl *VD = nullptr;
11895 
11896   uint64_t MagicValue;
11897 
11898   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11899     return false;
11900 
11901   if (VD) {
11902     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11903       if (I->getArgumentKind() != ArgumentKind) {
11904         FoundWrongKind = true;
11905         return false;
11906       }
11907       TypeInfo.Type = I->getMatchingCType();
11908       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11909       TypeInfo.MustBeNull = I->getMustBeNull();
11910       return true;
11911     }
11912     return false;
11913   }
11914 
11915   if (!MagicValues)
11916     return false;
11917 
11918   llvm::DenseMap<Sema::TypeTagMagicValue,
11919                  Sema::TypeTagData>::const_iterator I =
11920       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11921   if (I == MagicValues->end())
11922     return false;
11923 
11924   TypeInfo = I->second;
11925   return true;
11926 }
11927 } // end anonymous namespace
11928 
11929 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11930                                       uint64_t MagicValue, QualType Type,
11931                                       bool LayoutCompatible,
11932                                       bool MustBeNull) {
11933   if (!TypeTagForDatatypeMagicValues)
11934     TypeTagForDatatypeMagicValues.reset(
11935         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11936 
11937   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11938   (*TypeTagForDatatypeMagicValues)[Magic] =
11939       TypeTagData(Type, LayoutCompatible, MustBeNull);
11940 }
11941 
11942 namespace {
11943 bool IsSameCharType(QualType T1, QualType T2) {
11944   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11945   if (!BT1)
11946     return false;
11947 
11948   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11949   if (!BT2)
11950     return false;
11951 
11952   BuiltinType::Kind T1Kind = BT1->getKind();
11953   BuiltinType::Kind T2Kind = BT2->getKind();
11954 
11955   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11956          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11957          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11958          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11959 }
11960 } // end anonymous namespace
11961 
11962 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11963                                     const Expr * const *ExprArgs) {
11964   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11965   bool IsPointerAttr = Attr->getIsPointer();
11966 
11967   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11968   bool FoundWrongKind;
11969   TypeTagData TypeInfo;
11970   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11971                         TypeTagForDatatypeMagicValues.get(),
11972                         FoundWrongKind, TypeInfo)) {
11973     if (FoundWrongKind)
11974       Diag(TypeTagExpr->getExprLoc(),
11975            diag::warn_type_tag_for_datatype_wrong_kind)
11976         << TypeTagExpr->getSourceRange();
11977     return;
11978   }
11979 
11980   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11981   if (IsPointerAttr) {
11982     // Skip implicit cast of pointer to `void *' (as a function argument).
11983     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11984       if (ICE->getType()->isVoidPointerType() &&
11985           ICE->getCastKind() == CK_BitCast)
11986         ArgumentExpr = ICE->getSubExpr();
11987   }
11988   QualType ArgumentType = ArgumentExpr->getType();
11989 
11990   // Passing a `void*' pointer shouldn't trigger a warning.
11991   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11992     return;
11993 
11994   if (TypeInfo.MustBeNull) {
11995     // Type tag with matching void type requires a null pointer.
11996     if (!ArgumentExpr->isNullPointerConstant(Context,
11997                                              Expr::NPC_ValueDependentIsNotNull)) {
11998       Diag(ArgumentExpr->getExprLoc(),
11999            diag::warn_type_safety_null_pointer_required)
12000           << ArgumentKind->getName()
12001           << ArgumentExpr->getSourceRange()
12002           << TypeTagExpr->getSourceRange();
12003     }
12004     return;
12005   }
12006 
12007   QualType RequiredType = TypeInfo.Type;
12008   if (IsPointerAttr)
12009     RequiredType = Context.getPointerType(RequiredType);
12010 
12011   bool mismatch = false;
12012   if (!TypeInfo.LayoutCompatible) {
12013     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12014 
12015     // C++11 [basic.fundamental] p1:
12016     // Plain char, signed char, and unsigned char are three distinct types.
12017     //
12018     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12019     // char' depending on the current char signedness mode.
12020     if (mismatch)
12021       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12022                                            RequiredType->getPointeeType())) ||
12023           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12024         mismatch = false;
12025   } else
12026     if (IsPointerAttr)
12027       mismatch = !isLayoutCompatible(Context,
12028                                      ArgumentType->getPointeeType(),
12029                                      RequiredType->getPointeeType());
12030     else
12031       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12032 
12033   if (mismatch)
12034     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12035         << ArgumentType << ArgumentKind
12036         << TypeInfo.LayoutCompatible << RequiredType
12037         << ArgumentExpr->getSourceRange()
12038         << TypeTagExpr->getSourceRange();
12039 }
12040 
12041 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12042                                          CharUnits Alignment) {
12043   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12044 }
12045 
12046 void Sema::DiagnoseMisalignedMembers() {
12047   for (MisalignedMember &m : MisalignedMembers) {
12048     const NamedDecl *ND = m.RD;
12049     if (ND->getName().empty()) {
12050       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12051         ND = TD;
12052     }
12053     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12054         << m.MD << ND << m.E->getSourceRange();
12055   }
12056   MisalignedMembers.clear();
12057 }
12058 
12059 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12060   E = E->IgnoreParens();
12061   if (!T->isPointerType() && !T->isIntegerType())
12062     return;
12063   if (isa<UnaryOperator>(E) &&
12064       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12065     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12066     if (isa<MemberExpr>(Op)) {
12067       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12068                           MisalignedMember(Op));
12069       if (MA != MisalignedMembers.end() &&
12070           (T->isIntegerType() ||
12071            (T->isPointerType() &&
12072             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
12073         MisalignedMembers.erase(MA);
12074     }
12075   }
12076 }
12077 
12078 void Sema::RefersToMemberWithReducedAlignment(
12079     Expr *E,
12080     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12081         Action) {
12082   const auto *ME = dyn_cast<MemberExpr>(E);
12083   if (!ME)
12084     return;
12085 
12086   // No need to check expressions with an __unaligned-qualified type.
12087   if (E->getType().getQualifiers().hasUnaligned())
12088     return;
12089 
12090   // For a chain of MemberExpr like "a.b.c.d" this list
12091   // will keep FieldDecl's like [d, c, b].
12092   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12093   const MemberExpr *TopME = nullptr;
12094   bool AnyIsPacked = false;
12095   do {
12096     QualType BaseType = ME->getBase()->getType();
12097     if (ME->isArrow())
12098       BaseType = BaseType->getPointeeType();
12099     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12100     if (RD->isInvalidDecl())
12101       return;
12102 
12103     ValueDecl *MD = ME->getMemberDecl();
12104     auto *FD = dyn_cast<FieldDecl>(MD);
12105     // We do not care about non-data members.
12106     if (!FD || FD->isInvalidDecl())
12107       return;
12108 
12109     AnyIsPacked =
12110         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12111     ReverseMemberChain.push_back(FD);
12112 
12113     TopME = ME;
12114     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12115   } while (ME);
12116   assert(TopME && "We did not compute a topmost MemberExpr!");
12117 
12118   // Not the scope of this diagnostic.
12119   if (!AnyIsPacked)
12120     return;
12121 
12122   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12123   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12124   // TODO: The innermost base of the member expression may be too complicated.
12125   // For now, just disregard these cases. This is left for future
12126   // improvement.
12127   if (!DRE && !isa<CXXThisExpr>(TopBase))
12128       return;
12129 
12130   // Alignment expected by the whole expression.
12131   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12132 
12133   // No need to do anything else with this case.
12134   if (ExpectedAlignment.isOne())
12135     return;
12136 
12137   // Synthesize offset of the whole access.
12138   CharUnits Offset;
12139   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12140        I++) {
12141     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12142   }
12143 
12144   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12145   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12146       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12147 
12148   // The base expression of the innermost MemberExpr may give
12149   // stronger guarantees than the class containing the member.
12150   if (DRE && !TopME->isArrow()) {
12151     const ValueDecl *VD = DRE->getDecl();
12152     if (!VD->getType()->isReferenceType())
12153       CompleteObjectAlignment =
12154           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12155   }
12156 
12157   // Check if the synthesized offset fulfills the alignment.
12158   if (Offset % ExpectedAlignment != 0 ||
12159       // It may fulfill the offset it but the effective alignment may still be
12160       // lower than the expected expression alignment.
12161       CompleteObjectAlignment < ExpectedAlignment) {
12162     // If this happens, we want to determine a sensible culprit of this.
12163     // Intuitively, watching the chain of member expressions from right to
12164     // left, we start with the required alignment (as required by the field
12165     // type) but some packed attribute in that chain has reduced the alignment.
12166     // It may happen that another packed structure increases it again. But if
12167     // we are here such increase has not been enough. So pointing the first
12168     // FieldDecl that either is packed or else its RecordDecl is,
12169     // seems reasonable.
12170     FieldDecl *FD = nullptr;
12171     CharUnits Alignment;
12172     for (FieldDecl *FDI : ReverseMemberChain) {
12173       if (FDI->hasAttr<PackedAttr>() ||
12174           FDI->getParent()->hasAttr<PackedAttr>()) {
12175         FD = FDI;
12176         Alignment = std::min(
12177             Context.getTypeAlignInChars(FD->getType()),
12178             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12179         break;
12180       }
12181     }
12182     assert(FD && "We did not find a packed FieldDecl!");
12183     Action(E, FD->getParent(), FD, Alignment);
12184   }
12185 }
12186 
12187 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12188   using namespace std::placeholders;
12189   RefersToMemberWithReducedAlignment(
12190       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12191                      _2, _3, _4));
12192 }
12193 
12194