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.ActiveTemplateInstantiations.empty())
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_enqueue_kernel_expected_type) << "block";
313     return true;
314   }
315   return checkOpenCLBlockArgs(S, BlockArg);
316 }
317 
318 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319                                             unsigned Start, unsigned End);
320 
321 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322 /// 'local void*' parameter of passed block.
323 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324                                            Expr *BlockArg,
325                                            unsigned NumNonVarArgs) {
326   const BlockPointerType *BPT =
327       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328   unsigned NumBlockParams =
329       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330   unsigned TotalNumArgs = TheCall->getNumArgs();
331 
332   // For each argument passed to the block, a corresponding uint needs to
333   // be passed to describe the size of the local memory.
334   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335     S.Diag(TheCall->getLocStart(),
336            diag::err_opencl_enqueue_kernel_local_size_args);
337     return true;
338   }
339 
340   // Check that the sizes of the local memory are specified by integers.
341   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342                                          TotalNumArgs - 1);
343 }
344 
345 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346 /// overload formats specified in Table 6.13.17.1.
347 /// int enqueue_kernel(queue_t queue,
348 ///                    kernel_enqueue_flags_t flags,
349 ///                    const ndrange_t ndrange,
350 ///                    void (^block)(void))
351 /// int enqueue_kernel(queue_t queue,
352 ///                    kernel_enqueue_flags_t flags,
353 ///                    const ndrange_t ndrange,
354 ///                    uint num_events_in_wait_list,
355 ///                    clk_event_t *event_wait_list,
356 ///                    clk_event_t *event_ret,
357 ///                    void (^block)(void))
358 /// int enqueue_kernel(queue_t queue,
359 ///                    kernel_enqueue_flags_t flags,
360 ///                    const ndrange_t ndrange,
361 ///                    void (^block)(local void*, ...),
362 ///                    uint size0, ...)
363 /// int enqueue_kernel(queue_t queue,
364 ///                    kernel_enqueue_flags_t flags,
365 ///                    const ndrange_t ndrange,
366 ///                    uint num_events_in_wait_list,
367 ///                    clk_event_t *event_wait_list,
368 ///                    clk_event_t *event_ret,
369 ///                    void (^block)(local void*, ...),
370 ///                    uint size0, ...)
371 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372   unsigned NumArgs = TheCall->getNumArgs();
373 
374   if (NumArgs < 4) {
375     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376     return true;
377   }
378 
379   Expr *Arg0 = TheCall->getArg(0);
380   Expr *Arg1 = TheCall->getArg(1);
381   Expr *Arg2 = TheCall->getArg(2);
382   Expr *Arg3 = TheCall->getArg(3);
383 
384   // First argument always needs to be a queue_t type.
385   if (!Arg0->getType()->isQueueT()) {
386     S.Diag(TheCall->getArg(0)->getLocStart(),
387            diag::err_opencl_enqueue_kernel_expected_type)
388         << S.Context.OCLQueueTy;
389     return true;
390   }
391 
392   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393   if (!Arg1->getType()->isIntegerType()) {
394     S.Diag(TheCall->getArg(1)->getLocStart(),
395            diag::err_opencl_enqueue_kernel_expected_type)
396         << "'kernel_enqueue_flags_t' (i.e. uint)";
397     return true;
398   }
399 
400   // Third argument is always an ndrange_t type.
401   if (!Arg2->getType()->isNDRangeT()) {
402     S.Diag(TheCall->getArg(2)->getLocStart(),
403            diag::err_opencl_enqueue_kernel_expected_type)
404         << S.Context.OCLNDRangeTy;
405     return true;
406   }
407 
408   // With four arguments, there is only one form that the function could be
409   // called in: no events and no variable arguments.
410   if (NumArgs == 4) {
411     // check that the last argument is the right block type.
412     if (!isBlockPointer(Arg3)) {
413       S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414           << "block";
415       return true;
416     }
417     // we have a block type, check the prototype
418     const BlockPointerType *BPT =
419         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421       S.Diag(Arg3->getLocStart(),
422              diag::err_opencl_enqueue_kernel_blocks_no_args);
423       return true;
424     }
425     return false;
426   }
427   // we can have block + varargs.
428   if (isBlockPointer(Arg3))
429     return (checkOpenCLBlockArgs(S, Arg3) ||
430             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431   // last two cases with either exactly 7 args or 7 args and varargs.
432   if (NumArgs >= 7) {
433     // check common block argument.
434     Expr *Arg6 = TheCall->getArg(6);
435     if (!isBlockPointer(Arg6)) {
436       S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437           << "block";
438       return true;
439     }
440     if (checkOpenCLBlockArgs(S, Arg6))
441       return true;
442 
443     // Forth argument has to be any integer type.
444     if (!Arg3->getType()->isIntegerType()) {
445       S.Diag(TheCall->getArg(3)->getLocStart(),
446              diag::err_opencl_enqueue_kernel_expected_type)
447           << "integer";
448       return true;
449     }
450     // check remaining common arguments.
451     Expr *Arg4 = TheCall->getArg(4);
452     Expr *Arg5 = TheCall->getArg(5);
453 
454     // Fith argument is always passed as pointers to clk_event_t.
455     if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456       S.Diag(TheCall->getArg(4)->getLocStart(),
457              diag::err_opencl_enqueue_kernel_expected_type)
458           << S.Context.getPointerType(S.Context.OCLClkEventTy);
459       return true;
460     }
461 
462     // Sixth argument is always passed as pointers to clk_event_t.
463     if (!(Arg5->getType()->isPointerType() &&
464           Arg5->getType()->getPointeeType()->isClkEventT())) {
465       S.Diag(TheCall->getArg(5)->getLocStart(),
466              diag::err_opencl_enqueue_kernel_expected_type)
467           << S.Context.getPointerType(S.Context.OCLClkEventTy);
468       return true;
469     }
470 
471     if (NumArgs == 7)
472       return false;
473 
474     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475   }
476 
477   // None of the specific case has been detected, give generic error
478   S.Diag(TheCall->getLocStart(),
479          diag::err_opencl_enqueue_kernel_incorrect_args);
480   return true;
481 }
482 
483 /// Returns OpenCL access qual.
484 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
485     return D->getAttr<OpenCLAccessAttr>();
486 }
487 
488 /// Returns true if pipe element type is different from the pointer.
489 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490   const Expr *Arg0 = Call->getArg(0);
491   // First argument type should always be pipe.
492   if (!Arg0->getType()->isPipeType()) {
493     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
494         << Call->getDirectCallee() << Arg0->getSourceRange();
495     return true;
496   }
497   OpenCLAccessAttr *AccessQual =
498       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499   // Validates the access qualifier is compatible with the call.
500   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501   // read_only and write_only, and assumed to be read_only if no qualifier is
502   // specified.
503   switch (Call->getDirectCallee()->getBuiltinID()) {
504   case Builtin::BIread_pipe:
505   case Builtin::BIreserve_read_pipe:
506   case Builtin::BIcommit_read_pipe:
507   case Builtin::BIwork_group_reserve_read_pipe:
508   case Builtin::BIsub_group_reserve_read_pipe:
509   case Builtin::BIwork_group_commit_read_pipe:
510   case Builtin::BIsub_group_commit_read_pipe:
511     if (!(!AccessQual || AccessQual->isReadOnly())) {
512       S.Diag(Arg0->getLocStart(),
513              diag::err_opencl_builtin_pipe_invalid_access_modifier)
514           << "read_only" << Arg0->getSourceRange();
515       return true;
516     }
517     break;
518   case Builtin::BIwrite_pipe:
519   case Builtin::BIreserve_write_pipe:
520   case Builtin::BIcommit_write_pipe:
521   case Builtin::BIwork_group_reserve_write_pipe:
522   case Builtin::BIsub_group_reserve_write_pipe:
523   case Builtin::BIwork_group_commit_write_pipe:
524   case Builtin::BIsub_group_commit_write_pipe:
525     if (!(AccessQual && AccessQual->isWriteOnly())) {
526       S.Diag(Arg0->getLocStart(),
527              diag::err_opencl_builtin_pipe_invalid_access_modifier)
528           << "write_only" << Arg0->getSourceRange();
529       return true;
530     }
531     break;
532   default:
533     break;
534   }
535   return false;
536 }
537 
538 /// Returns true if pipe element type is different from the pointer.
539 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540   const Expr *Arg0 = Call->getArg(0);
541   const Expr *ArgIdx = Call->getArg(Idx);
542   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
543   const QualType EltTy = PipeTy->getElementType();
544   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
545   // The Idx argument should be a pointer and the type of the pointer and
546   // the type of pipe element should also be the same.
547   if (!ArgTy ||
548       !S.Context.hasSameType(
549           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
550     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
551         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
552         << ArgIdx->getType() << ArgIdx->getSourceRange();
553     return true;
554   }
555   return false;
556 }
557 
558 // \brief Performs semantic analysis for the read/write_pipe call.
559 // \param S Reference to the semantic analyzer.
560 // \param Call A pointer to the builtin call.
561 // \return True if a semantic error has been found, false otherwise.
562 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
563   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564   // functions have two forms.
565   switch (Call->getNumArgs()) {
566   case 2: {
567     if (checkOpenCLPipeArg(S, Call))
568       return true;
569     // The call with 2 arguments should be
570     // read/write_pipe(pipe T, T*).
571     // Check packet type T.
572     if (checkOpenCLPipePacketType(S, Call, 1))
573       return true;
574   } break;
575 
576   case 4: {
577     if (checkOpenCLPipeArg(S, Call))
578       return true;
579     // The call with 4 arguments should be
580     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581     // Check reserve_id_t.
582     if (!Call->getArg(1)->getType()->isReserveIDT()) {
583       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
584           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
585           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
586       return true;
587     }
588 
589     // Check the index.
590     const Expr *Arg2 = Call->getArg(2);
591     if (!Arg2->getType()->isIntegerType() &&
592         !Arg2->getType()->isUnsignedIntegerType()) {
593       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
594           << Call->getDirectCallee() << S.Context.UnsignedIntTy
595           << Arg2->getType() << Arg2->getSourceRange();
596       return true;
597     }
598 
599     // Check packet type T.
600     if (checkOpenCLPipePacketType(S, Call, 3))
601       return true;
602   } break;
603   default:
604     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
605         << Call->getDirectCallee() << Call->getSourceRange();
606     return true;
607   }
608 
609   return false;
610 }
611 
612 // \brief Performs a semantic analysis on the {work_group_/sub_group_
613 //        /_}reserve_{read/write}_pipe
614 // \param S Reference to the semantic analyzer.
615 // \param Call The call to the builtin function to be analyzed.
616 // \return True if a semantic error was found, false otherwise.
617 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618   if (checkArgCount(S, Call, 2))
619     return true;
620 
621   if (checkOpenCLPipeArg(S, Call))
622     return true;
623 
624   // Check the reserve size.
625   if (!Call->getArg(1)->getType()->isIntegerType() &&
626       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
628         << Call->getDirectCallee() << S.Context.UnsignedIntTy
629         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
630     return true;
631   }
632 
633   return false;
634 }
635 
636 // \brief Performs a semantic analysis on {work_group_/sub_group_
637 //        /_}commit_{read/write}_pipe
638 // \param S Reference to the semantic analyzer.
639 // \param Call The call to the builtin function to be analyzed.
640 // \return True if a semantic error was found, false otherwise.
641 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642   if (checkArgCount(S, Call, 2))
643     return true;
644 
645   if (checkOpenCLPipeArg(S, Call))
646     return true;
647 
648   // Check reserve_id_t.
649   if (!Call->getArg(1)->getType()->isReserveIDT()) {
650     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
651         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
652         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
653     return true;
654   }
655 
656   return false;
657 }
658 
659 // \brief Performs a semantic analysis on the call to built-in Pipe
660 //        Query Functions.
661 // \param S Reference to the semantic analyzer.
662 // \param Call The call to the builtin function to be analyzed.
663 // \return True if a semantic error was found, false otherwise.
664 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665   if (checkArgCount(S, Call, 1))
666     return true;
667 
668   if (!Call->getArg(0)->getType()->isPipeType()) {
669     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
670         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
671     return true;
672   }
673 
674   return false;
675 }
676 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
677 // \brief Performs semantic analysis for the to_global/local/private call.
678 // \param S Reference to the semantic analyzer.
679 // \param BuiltinID ID of the builtin function.
680 // \param Call A pointer to the builtin call.
681 // \return True if a semantic error has been found, false otherwise.
682 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683                                     CallExpr *Call) {
684   if (Call->getNumArgs() != 1) {
685     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686         << Call->getDirectCallee() << Call->getSourceRange();
687     return true;
688   }
689 
690   auto RT = Call->getArg(0)->getType();
691   if (!RT->isPointerType() || RT->getPointeeType()
692       .getAddressSpace() == LangAS::opencl_constant) {
693     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695     return true;
696   }
697 
698   RT = RT->getPointeeType();
699   auto Qual = RT.getQualifiers();
700   switch (BuiltinID) {
701   case Builtin::BIto_global:
702     Qual.setAddressSpace(LangAS::opencl_global);
703     break;
704   case Builtin::BIto_local:
705     Qual.setAddressSpace(LangAS::opencl_local);
706     break;
707   default:
708     Qual.removeAddressSpace();
709   }
710   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711       RT.getUnqualifiedType(), Qual)));
712 
713   return false;
714 }
715 
716 ExprResult
717 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718                                CallExpr *TheCall) {
719   ExprResult TheCallResult(TheCall);
720 
721   // Find out if any arguments are required to be integer constant expressions.
722   unsigned ICEArguments = 0;
723   ASTContext::GetBuiltinTypeError Error;
724   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725   if (Error != ASTContext::GE_None)
726     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
727 
728   // If any arguments are required to be ICE's, check and diagnose.
729   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730     // Skip arguments not required to be ICE's.
731     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732 
733     llvm::APSInt Result;
734     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735       return true;
736     ICEArguments &= ~(1 << ArgNo);
737   }
738 
739   switch (BuiltinID) {
740   case Builtin::BI__builtin___CFStringMakeConstantString:
741     assert(TheCall->getNumArgs() == 1 &&
742            "Wrong # arguments to builtin CFStringMakeConstantString");
743     if (CheckObjCString(TheCall->getArg(0)))
744       return ExprError();
745     break;
746   case Builtin::BI__builtin_stdarg_start:
747   case Builtin::BI__builtin_va_start:
748     if (SemaBuiltinVAStart(TheCall))
749       return ExprError();
750     break;
751   case Builtin::BI__va_start: {
752     switch (Context.getTargetInfo().getTriple().getArch()) {
753     case llvm::Triple::arm:
754     case llvm::Triple::thumb:
755       if (SemaBuiltinVAStartARM(TheCall))
756         return ExprError();
757       break;
758     default:
759       if (SemaBuiltinVAStart(TheCall))
760         return ExprError();
761       break;
762     }
763     break;
764   }
765   case Builtin::BI__builtin_isgreater:
766   case Builtin::BI__builtin_isgreaterequal:
767   case Builtin::BI__builtin_isless:
768   case Builtin::BI__builtin_islessequal:
769   case Builtin::BI__builtin_islessgreater:
770   case Builtin::BI__builtin_isunordered:
771     if (SemaBuiltinUnorderedCompare(TheCall))
772       return ExprError();
773     break;
774   case Builtin::BI__builtin_fpclassify:
775     if (SemaBuiltinFPClassification(TheCall, 6))
776       return ExprError();
777     break;
778   case Builtin::BI__builtin_isfinite:
779   case Builtin::BI__builtin_isinf:
780   case Builtin::BI__builtin_isinf_sign:
781   case Builtin::BI__builtin_isnan:
782   case Builtin::BI__builtin_isnormal:
783     if (SemaBuiltinFPClassification(TheCall, 1))
784       return ExprError();
785     break;
786   case Builtin::BI__builtin_shufflevector:
787     return SemaBuiltinShuffleVector(TheCall);
788     // TheCall will be freed by the smart pointer here, but that's fine, since
789     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
790   case Builtin::BI__builtin_prefetch:
791     if (SemaBuiltinPrefetch(TheCall))
792       return ExprError();
793     break;
794   case Builtin::BI__assume:
795   case Builtin::BI__builtin_assume:
796     if (SemaBuiltinAssume(TheCall))
797       return ExprError();
798     break;
799   case Builtin::BI__builtin_assume_aligned:
800     if (SemaBuiltinAssumeAligned(TheCall))
801       return ExprError();
802     break;
803   case Builtin::BI__builtin_object_size:
804     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
805       return ExprError();
806     break;
807   case Builtin::BI__builtin_longjmp:
808     if (SemaBuiltinLongjmp(TheCall))
809       return ExprError();
810     break;
811   case Builtin::BI__builtin_setjmp:
812     if (SemaBuiltinSetjmp(TheCall))
813       return ExprError();
814     break;
815   case Builtin::BI_setjmp:
816   case Builtin::BI_setjmpex:
817     if (checkArgCount(*this, TheCall, 1))
818       return true;
819     break;
820 
821   case Builtin::BI__builtin_classify_type:
822     if (checkArgCount(*this, TheCall, 1)) return true;
823     TheCall->setType(Context.IntTy);
824     break;
825   case Builtin::BI__builtin_constant_p:
826     if (checkArgCount(*this, TheCall, 1)) return true;
827     TheCall->setType(Context.IntTy);
828     break;
829   case Builtin::BI__sync_fetch_and_add:
830   case Builtin::BI__sync_fetch_and_add_1:
831   case Builtin::BI__sync_fetch_and_add_2:
832   case Builtin::BI__sync_fetch_and_add_4:
833   case Builtin::BI__sync_fetch_and_add_8:
834   case Builtin::BI__sync_fetch_and_add_16:
835   case Builtin::BI__sync_fetch_and_sub:
836   case Builtin::BI__sync_fetch_and_sub_1:
837   case Builtin::BI__sync_fetch_and_sub_2:
838   case Builtin::BI__sync_fetch_and_sub_4:
839   case Builtin::BI__sync_fetch_and_sub_8:
840   case Builtin::BI__sync_fetch_and_sub_16:
841   case Builtin::BI__sync_fetch_and_or:
842   case Builtin::BI__sync_fetch_and_or_1:
843   case Builtin::BI__sync_fetch_and_or_2:
844   case Builtin::BI__sync_fetch_and_or_4:
845   case Builtin::BI__sync_fetch_and_or_8:
846   case Builtin::BI__sync_fetch_and_or_16:
847   case Builtin::BI__sync_fetch_and_and:
848   case Builtin::BI__sync_fetch_and_and_1:
849   case Builtin::BI__sync_fetch_and_and_2:
850   case Builtin::BI__sync_fetch_and_and_4:
851   case Builtin::BI__sync_fetch_and_and_8:
852   case Builtin::BI__sync_fetch_and_and_16:
853   case Builtin::BI__sync_fetch_and_xor:
854   case Builtin::BI__sync_fetch_and_xor_1:
855   case Builtin::BI__sync_fetch_and_xor_2:
856   case Builtin::BI__sync_fetch_and_xor_4:
857   case Builtin::BI__sync_fetch_and_xor_8:
858   case Builtin::BI__sync_fetch_and_xor_16:
859   case Builtin::BI__sync_fetch_and_nand:
860   case Builtin::BI__sync_fetch_and_nand_1:
861   case Builtin::BI__sync_fetch_and_nand_2:
862   case Builtin::BI__sync_fetch_and_nand_4:
863   case Builtin::BI__sync_fetch_and_nand_8:
864   case Builtin::BI__sync_fetch_and_nand_16:
865   case Builtin::BI__sync_add_and_fetch:
866   case Builtin::BI__sync_add_and_fetch_1:
867   case Builtin::BI__sync_add_and_fetch_2:
868   case Builtin::BI__sync_add_and_fetch_4:
869   case Builtin::BI__sync_add_and_fetch_8:
870   case Builtin::BI__sync_add_and_fetch_16:
871   case Builtin::BI__sync_sub_and_fetch:
872   case Builtin::BI__sync_sub_and_fetch_1:
873   case Builtin::BI__sync_sub_and_fetch_2:
874   case Builtin::BI__sync_sub_and_fetch_4:
875   case Builtin::BI__sync_sub_and_fetch_8:
876   case Builtin::BI__sync_sub_and_fetch_16:
877   case Builtin::BI__sync_and_and_fetch:
878   case Builtin::BI__sync_and_and_fetch_1:
879   case Builtin::BI__sync_and_and_fetch_2:
880   case Builtin::BI__sync_and_and_fetch_4:
881   case Builtin::BI__sync_and_and_fetch_8:
882   case Builtin::BI__sync_and_and_fetch_16:
883   case Builtin::BI__sync_or_and_fetch:
884   case Builtin::BI__sync_or_and_fetch_1:
885   case Builtin::BI__sync_or_and_fetch_2:
886   case Builtin::BI__sync_or_and_fetch_4:
887   case Builtin::BI__sync_or_and_fetch_8:
888   case Builtin::BI__sync_or_and_fetch_16:
889   case Builtin::BI__sync_xor_and_fetch:
890   case Builtin::BI__sync_xor_and_fetch_1:
891   case Builtin::BI__sync_xor_and_fetch_2:
892   case Builtin::BI__sync_xor_and_fetch_4:
893   case Builtin::BI__sync_xor_and_fetch_8:
894   case Builtin::BI__sync_xor_and_fetch_16:
895   case Builtin::BI__sync_nand_and_fetch:
896   case Builtin::BI__sync_nand_and_fetch_1:
897   case Builtin::BI__sync_nand_and_fetch_2:
898   case Builtin::BI__sync_nand_and_fetch_4:
899   case Builtin::BI__sync_nand_and_fetch_8:
900   case Builtin::BI__sync_nand_and_fetch_16:
901   case Builtin::BI__sync_val_compare_and_swap:
902   case Builtin::BI__sync_val_compare_and_swap_1:
903   case Builtin::BI__sync_val_compare_and_swap_2:
904   case Builtin::BI__sync_val_compare_and_swap_4:
905   case Builtin::BI__sync_val_compare_and_swap_8:
906   case Builtin::BI__sync_val_compare_and_swap_16:
907   case Builtin::BI__sync_bool_compare_and_swap:
908   case Builtin::BI__sync_bool_compare_and_swap_1:
909   case Builtin::BI__sync_bool_compare_and_swap_2:
910   case Builtin::BI__sync_bool_compare_and_swap_4:
911   case Builtin::BI__sync_bool_compare_and_swap_8:
912   case Builtin::BI__sync_bool_compare_and_swap_16:
913   case Builtin::BI__sync_lock_test_and_set:
914   case Builtin::BI__sync_lock_test_and_set_1:
915   case Builtin::BI__sync_lock_test_and_set_2:
916   case Builtin::BI__sync_lock_test_and_set_4:
917   case Builtin::BI__sync_lock_test_and_set_8:
918   case Builtin::BI__sync_lock_test_and_set_16:
919   case Builtin::BI__sync_lock_release:
920   case Builtin::BI__sync_lock_release_1:
921   case Builtin::BI__sync_lock_release_2:
922   case Builtin::BI__sync_lock_release_4:
923   case Builtin::BI__sync_lock_release_8:
924   case Builtin::BI__sync_lock_release_16:
925   case Builtin::BI__sync_swap:
926   case Builtin::BI__sync_swap_1:
927   case Builtin::BI__sync_swap_2:
928   case Builtin::BI__sync_swap_4:
929   case Builtin::BI__sync_swap_8:
930   case Builtin::BI__sync_swap_16:
931     return SemaBuiltinAtomicOverloaded(TheCallResult);
932   case Builtin::BI__builtin_nontemporal_load:
933   case Builtin::BI__builtin_nontemporal_store:
934     return SemaBuiltinNontemporalOverloaded(TheCallResult);
935 #define BUILTIN(ID, TYPE, ATTRS)
936 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
937   case Builtin::BI##ID: \
938     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
939 #include "clang/Basic/Builtins.def"
940   case Builtin::BI__builtin_annotation:
941     if (SemaBuiltinAnnotation(*this, TheCall))
942       return ExprError();
943     break;
944   case Builtin::BI__builtin_addressof:
945     if (SemaBuiltinAddressof(*this, TheCall))
946       return ExprError();
947     break;
948   case Builtin::BI__builtin_add_overflow:
949   case Builtin::BI__builtin_sub_overflow:
950   case Builtin::BI__builtin_mul_overflow:
951     if (SemaBuiltinOverflow(*this, TheCall))
952       return ExprError();
953     break;
954   case Builtin::BI__builtin_operator_new:
955   case Builtin::BI__builtin_operator_delete:
956     if (!getLangOpts().CPlusPlus) {
957       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
958         << (BuiltinID == Builtin::BI__builtin_operator_new
959                 ? "__builtin_operator_new"
960                 : "__builtin_operator_delete")
961         << "C++";
962       return ExprError();
963     }
964     // CodeGen assumes it can find the global new and delete to call,
965     // so ensure that they are declared.
966     DeclareGlobalNewDelete();
967     break;
968 
969   // check secure string manipulation functions where overflows
970   // are detectable at compile time
971   case Builtin::BI__builtin___memcpy_chk:
972   case Builtin::BI__builtin___memmove_chk:
973   case Builtin::BI__builtin___memset_chk:
974   case Builtin::BI__builtin___strlcat_chk:
975   case Builtin::BI__builtin___strlcpy_chk:
976   case Builtin::BI__builtin___strncat_chk:
977   case Builtin::BI__builtin___strncpy_chk:
978   case Builtin::BI__builtin___stpncpy_chk:
979     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
980     break;
981   case Builtin::BI__builtin___memccpy_chk:
982     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
983     break;
984   case Builtin::BI__builtin___snprintf_chk:
985   case Builtin::BI__builtin___vsnprintf_chk:
986     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
987     break;
988   case Builtin::BI__builtin_call_with_static_chain:
989     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
990       return ExprError();
991     break;
992   case Builtin::BI__exception_code:
993   case Builtin::BI_exception_code:
994     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
995                                  diag::err_seh___except_block))
996       return ExprError();
997     break;
998   case Builtin::BI__exception_info:
999   case Builtin::BI_exception_info:
1000     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1001                                  diag::err_seh___except_filter))
1002       return ExprError();
1003     break;
1004   case Builtin::BI__GetExceptionInfo:
1005     if (checkArgCount(*this, TheCall, 1))
1006       return ExprError();
1007 
1008     if (CheckCXXThrowOperand(
1009             TheCall->getLocStart(),
1010             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1011             TheCall))
1012       return ExprError();
1013 
1014     TheCall->setType(Context.VoidPtrTy);
1015     break;
1016   // OpenCL v2.0, s6.13.16 - Pipe functions
1017   case Builtin::BIread_pipe:
1018   case Builtin::BIwrite_pipe:
1019     // Since those two functions are declared with var args, we need a semantic
1020     // check for the argument.
1021     if (SemaBuiltinRWPipe(*this, TheCall))
1022       return ExprError();
1023     TheCall->setType(Context.IntTy);
1024     break;
1025   case Builtin::BIreserve_read_pipe:
1026   case Builtin::BIreserve_write_pipe:
1027   case Builtin::BIwork_group_reserve_read_pipe:
1028   case Builtin::BIwork_group_reserve_write_pipe:
1029   case Builtin::BIsub_group_reserve_read_pipe:
1030   case Builtin::BIsub_group_reserve_write_pipe:
1031     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032       return ExprError();
1033     // Since return type of reserve_read/write_pipe built-in function is
1034     // reserve_id_t, which is not defined in the builtin def file , we used int
1035     // as return type and need to override the return type of these functions.
1036     TheCall->setType(Context.OCLReserveIDTy);
1037     break;
1038   case Builtin::BIcommit_read_pipe:
1039   case Builtin::BIcommit_write_pipe:
1040   case Builtin::BIwork_group_commit_read_pipe:
1041   case Builtin::BIwork_group_commit_write_pipe:
1042   case Builtin::BIsub_group_commit_read_pipe:
1043   case Builtin::BIsub_group_commit_write_pipe:
1044     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045       return ExprError();
1046     break;
1047   case Builtin::BIget_pipe_num_packets:
1048   case Builtin::BIget_pipe_max_packets:
1049     if (SemaBuiltinPipePackets(*this, TheCall))
1050       return ExprError();
1051     TheCall->setType(Context.UnsignedIntTy);
1052     break;
1053   case Builtin::BIto_global:
1054   case Builtin::BIto_local:
1055   case Builtin::BIto_private:
1056     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1057       return ExprError();
1058     break;
1059   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1060   case Builtin::BIenqueue_kernel:
1061     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1062       return ExprError();
1063     break;
1064   case Builtin::BIget_kernel_work_group_size:
1065   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1066     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1067       return ExprError();
1068   }
1069 
1070   // Since the target specific builtins for each arch overlap, only check those
1071   // of the arch we are compiling for.
1072   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1073     switch (Context.getTargetInfo().getTriple().getArch()) {
1074       case llvm::Triple::arm:
1075       case llvm::Triple::armeb:
1076       case llvm::Triple::thumb:
1077       case llvm::Triple::thumbeb:
1078         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1079           return ExprError();
1080         break;
1081       case llvm::Triple::aarch64:
1082       case llvm::Triple::aarch64_be:
1083         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1084           return ExprError();
1085         break;
1086       case llvm::Triple::mips:
1087       case llvm::Triple::mipsel:
1088       case llvm::Triple::mips64:
1089       case llvm::Triple::mips64el:
1090         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1091           return ExprError();
1092         break;
1093       case llvm::Triple::systemz:
1094         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1095           return ExprError();
1096         break;
1097       case llvm::Triple::x86:
1098       case llvm::Triple::x86_64:
1099         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1100           return ExprError();
1101         break;
1102       case llvm::Triple::ppc:
1103       case llvm::Triple::ppc64:
1104       case llvm::Triple::ppc64le:
1105         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1106           return ExprError();
1107         break;
1108       default:
1109         break;
1110     }
1111   }
1112 
1113   return TheCallResult;
1114 }
1115 
1116 // Get the valid immediate range for the specified NEON type code.
1117 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1118   NeonTypeFlags Type(t);
1119   int IsQuad = ForceQuad ? true : Type.isQuad();
1120   switch (Type.getEltType()) {
1121   case NeonTypeFlags::Int8:
1122   case NeonTypeFlags::Poly8:
1123     return shift ? 7 : (8 << IsQuad) - 1;
1124   case NeonTypeFlags::Int16:
1125   case NeonTypeFlags::Poly16:
1126     return shift ? 15 : (4 << IsQuad) - 1;
1127   case NeonTypeFlags::Int32:
1128     return shift ? 31 : (2 << IsQuad) - 1;
1129   case NeonTypeFlags::Int64:
1130   case NeonTypeFlags::Poly64:
1131     return shift ? 63 : (1 << IsQuad) - 1;
1132   case NeonTypeFlags::Poly128:
1133     return shift ? 127 : (1 << IsQuad) - 1;
1134   case NeonTypeFlags::Float16:
1135     assert(!shift && "cannot shift float types!");
1136     return (4 << IsQuad) - 1;
1137   case NeonTypeFlags::Float32:
1138     assert(!shift && "cannot shift float types!");
1139     return (2 << IsQuad) - 1;
1140   case NeonTypeFlags::Float64:
1141     assert(!shift && "cannot shift float types!");
1142     return (1 << IsQuad) - 1;
1143   }
1144   llvm_unreachable("Invalid NeonTypeFlag!");
1145 }
1146 
1147 /// getNeonEltType - Return the QualType corresponding to the elements of
1148 /// the vector type specified by the NeonTypeFlags.  This is used to check
1149 /// the pointer arguments for Neon load/store intrinsics.
1150 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1151                                bool IsPolyUnsigned, bool IsInt64Long) {
1152   switch (Flags.getEltType()) {
1153   case NeonTypeFlags::Int8:
1154     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1155   case NeonTypeFlags::Int16:
1156     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1157   case NeonTypeFlags::Int32:
1158     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1159   case NeonTypeFlags::Int64:
1160     if (IsInt64Long)
1161       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1162     else
1163       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1164                                 : Context.LongLongTy;
1165   case NeonTypeFlags::Poly8:
1166     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1167   case NeonTypeFlags::Poly16:
1168     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1169   case NeonTypeFlags::Poly64:
1170     if (IsInt64Long)
1171       return Context.UnsignedLongTy;
1172     else
1173       return Context.UnsignedLongLongTy;
1174   case NeonTypeFlags::Poly128:
1175     break;
1176   case NeonTypeFlags::Float16:
1177     return Context.HalfTy;
1178   case NeonTypeFlags::Float32:
1179     return Context.FloatTy;
1180   case NeonTypeFlags::Float64:
1181     return Context.DoubleTy;
1182   }
1183   llvm_unreachable("Invalid NeonTypeFlag!");
1184 }
1185 
1186 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1187   llvm::APSInt Result;
1188   uint64_t mask = 0;
1189   unsigned TV = 0;
1190   int PtrArgNum = -1;
1191   bool HasConstPtr = false;
1192   switch (BuiltinID) {
1193 #define GET_NEON_OVERLOAD_CHECK
1194 #include "clang/Basic/arm_neon.inc"
1195 #undef GET_NEON_OVERLOAD_CHECK
1196   }
1197 
1198   // For NEON intrinsics which are overloaded on vector element type, validate
1199   // the immediate which specifies which variant to emit.
1200   unsigned ImmArg = TheCall->getNumArgs()-1;
1201   if (mask) {
1202     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1203       return true;
1204 
1205     TV = Result.getLimitedValue(64);
1206     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1207       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1208         << TheCall->getArg(ImmArg)->getSourceRange();
1209   }
1210 
1211   if (PtrArgNum >= 0) {
1212     // Check that pointer arguments have the specified type.
1213     Expr *Arg = TheCall->getArg(PtrArgNum);
1214     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1215       Arg = ICE->getSubExpr();
1216     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1217     QualType RHSTy = RHS.get()->getType();
1218 
1219     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1220     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1221     bool IsInt64Long =
1222         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1223     QualType EltTy =
1224         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1225     if (HasConstPtr)
1226       EltTy = EltTy.withConst();
1227     QualType LHSTy = Context.getPointerType(EltTy);
1228     AssignConvertType ConvTy;
1229     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1230     if (RHS.isInvalid())
1231       return true;
1232     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1233                                  RHS.get(), AA_Assigning))
1234       return true;
1235   }
1236 
1237   // For NEON intrinsics which take an immediate value as part of the
1238   // instruction, range check them here.
1239   unsigned i = 0, l = 0, u = 0;
1240   switch (BuiltinID) {
1241   default:
1242     return false;
1243 #define GET_NEON_IMMEDIATE_CHECK
1244 #include "clang/Basic/arm_neon.inc"
1245 #undef GET_NEON_IMMEDIATE_CHECK
1246   }
1247 
1248   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1249 }
1250 
1251 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1252                                         unsigned MaxWidth) {
1253   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1254           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1255           BuiltinID == ARM::BI__builtin_arm_strex ||
1256           BuiltinID == ARM::BI__builtin_arm_stlex ||
1257           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1258           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1259           BuiltinID == AArch64::BI__builtin_arm_strex ||
1260           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1261          "unexpected ARM builtin");
1262   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1263                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1264                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1265                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1266 
1267   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1268 
1269   // Ensure that we have the proper number of arguments.
1270   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1271     return true;
1272 
1273   // Inspect the pointer argument of the atomic builtin.  This should always be
1274   // a pointer type, whose element is an integral scalar or pointer type.
1275   // Because it is a pointer type, we don't have to worry about any implicit
1276   // casts here.
1277   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1278   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1279   if (PointerArgRes.isInvalid())
1280     return true;
1281   PointerArg = PointerArgRes.get();
1282 
1283   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1284   if (!pointerType) {
1285     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1286       << PointerArg->getType() << PointerArg->getSourceRange();
1287     return true;
1288   }
1289 
1290   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1291   // task is to insert the appropriate casts into the AST. First work out just
1292   // what the appropriate type is.
1293   QualType ValType = pointerType->getPointeeType();
1294   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1295   if (IsLdrex)
1296     AddrType.addConst();
1297 
1298   // Issue a warning if the cast is dodgy.
1299   CastKind CastNeeded = CK_NoOp;
1300   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1301     CastNeeded = CK_BitCast;
1302     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1303       << PointerArg->getType()
1304       << Context.getPointerType(AddrType)
1305       << AA_Passing << PointerArg->getSourceRange();
1306   }
1307 
1308   // Finally, do the cast and replace the argument with the corrected version.
1309   AddrType = Context.getPointerType(AddrType);
1310   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1311   if (PointerArgRes.isInvalid())
1312     return true;
1313   PointerArg = PointerArgRes.get();
1314 
1315   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1316 
1317   // In general, we allow ints, floats and pointers to be loaded and stored.
1318   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1319       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1320     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1321       << PointerArg->getType() << PointerArg->getSourceRange();
1322     return true;
1323   }
1324 
1325   // But ARM doesn't have instructions to deal with 128-bit versions.
1326   if (Context.getTypeSize(ValType) > MaxWidth) {
1327     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1328     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1329       << PointerArg->getType() << PointerArg->getSourceRange();
1330     return true;
1331   }
1332 
1333   switch (ValType.getObjCLifetime()) {
1334   case Qualifiers::OCL_None:
1335   case Qualifiers::OCL_ExplicitNone:
1336     // okay
1337     break;
1338 
1339   case Qualifiers::OCL_Weak:
1340   case Qualifiers::OCL_Strong:
1341   case Qualifiers::OCL_Autoreleasing:
1342     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1343       << ValType << PointerArg->getSourceRange();
1344     return true;
1345   }
1346 
1347   if (IsLdrex) {
1348     TheCall->setType(ValType);
1349     return false;
1350   }
1351 
1352   // Initialize the argument to be stored.
1353   ExprResult ValArg = TheCall->getArg(0);
1354   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1355       Context, ValType, /*consume*/ false);
1356   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1357   if (ValArg.isInvalid())
1358     return true;
1359   TheCall->setArg(0, ValArg.get());
1360 
1361   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1362   // but the custom checker bypasses all default analysis.
1363   TheCall->setType(Context.IntTy);
1364   return false;
1365 }
1366 
1367 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1368   llvm::APSInt Result;
1369 
1370   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1371       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1372       BuiltinID == ARM::BI__builtin_arm_strex ||
1373       BuiltinID == ARM::BI__builtin_arm_stlex) {
1374     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1375   }
1376 
1377   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1378     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1379       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1380   }
1381 
1382   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1383       BuiltinID == ARM::BI__builtin_arm_wsr64)
1384     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1385 
1386   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1387       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1388       BuiltinID == ARM::BI__builtin_arm_wsr ||
1389       BuiltinID == ARM::BI__builtin_arm_wsrp)
1390     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1391 
1392   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1393     return true;
1394 
1395   // For intrinsics which take an immediate value as part of the instruction,
1396   // range check them here.
1397   unsigned i = 0, l = 0, u = 0;
1398   switch (BuiltinID) {
1399   default: return false;
1400   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1401   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1402   case ARM::BI__builtin_arm_vcvtr_f:
1403   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1404   case ARM::BI__builtin_arm_dmb:
1405   case ARM::BI__builtin_arm_dsb:
1406   case ARM::BI__builtin_arm_isb:
1407   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1408   }
1409 
1410   // FIXME: VFP Intrinsics should error if VFP not present.
1411   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1412 }
1413 
1414 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1415                                          CallExpr *TheCall) {
1416   llvm::APSInt Result;
1417 
1418   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1419       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1420       BuiltinID == AArch64::BI__builtin_arm_strex ||
1421       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1422     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1423   }
1424 
1425   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1426     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1427       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1428       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1429       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1430   }
1431 
1432   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1433       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1434     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1435 
1436   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1437       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1438       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1439       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1440     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1441 
1442   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1443     return true;
1444 
1445   // For intrinsics which take an immediate value as part of the instruction,
1446   // range check them here.
1447   unsigned i = 0, l = 0, u = 0;
1448   switch (BuiltinID) {
1449   default: return false;
1450   case AArch64::BI__builtin_arm_dmb:
1451   case AArch64::BI__builtin_arm_dsb:
1452   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1453   }
1454 
1455   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1456 }
1457 
1458 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1459 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1460 // ordering for DSP is unspecified. MSA is ordered by the data format used
1461 // by the underlying instruction i.e., df/m, df/n and then by size.
1462 //
1463 // FIXME: The size tests here should instead be tablegen'd along with the
1464 //        definitions from include/clang/Basic/BuiltinsMips.def.
1465 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1466 //        be too.
1467 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1468   unsigned i = 0, l = 0, u = 0, m = 0;
1469   switch (BuiltinID) {
1470   default: return false;
1471   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1472   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1473   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1474   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1475   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1476   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1477   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1478   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1479   // df/m field.
1480   // These intrinsics take an unsigned 3 bit immediate.
1481   case Mips::BI__builtin_msa_bclri_b:
1482   case Mips::BI__builtin_msa_bnegi_b:
1483   case Mips::BI__builtin_msa_bseti_b:
1484   case Mips::BI__builtin_msa_sat_s_b:
1485   case Mips::BI__builtin_msa_sat_u_b:
1486   case Mips::BI__builtin_msa_slli_b:
1487   case Mips::BI__builtin_msa_srai_b:
1488   case Mips::BI__builtin_msa_srari_b:
1489   case Mips::BI__builtin_msa_srli_b:
1490   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1491   case Mips::BI__builtin_msa_binsli_b:
1492   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1493   // These intrinsics take an unsigned 4 bit immediate.
1494   case Mips::BI__builtin_msa_bclri_h:
1495   case Mips::BI__builtin_msa_bnegi_h:
1496   case Mips::BI__builtin_msa_bseti_h:
1497   case Mips::BI__builtin_msa_sat_s_h:
1498   case Mips::BI__builtin_msa_sat_u_h:
1499   case Mips::BI__builtin_msa_slli_h:
1500   case Mips::BI__builtin_msa_srai_h:
1501   case Mips::BI__builtin_msa_srari_h:
1502   case Mips::BI__builtin_msa_srli_h:
1503   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1504   case Mips::BI__builtin_msa_binsli_h:
1505   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1506   // These intrinsics take an unsigned 5 bit immedate.
1507   // The first block of intrinsics actually have an unsigned 5 bit field,
1508   // not a df/n field.
1509   case Mips::BI__builtin_msa_clei_u_b:
1510   case Mips::BI__builtin_msa_clei_u_h:
1511   case Mips::BI__builtin_msa_clei_u_w:
1512   case Mips::BI__builtin_msa_clei_u_d:
1513   case Mips::BI__builtin_msa_clti_u_b:
1514   case Mips::BI__builtin_msa_clti_u_h:
1515   case Mips::BI__builtin_msa_clti_u_w:
1516   case Mips::BI__builtin_msa_clti_u_d:
1517   case Mips::BI__builtin_msa_maxi_u_b:
1518   case Mips::BI__builtin_msa_maxi_u_h:
1519   case Mips::BI__builtin_msa_maxi_u_w:
1520   case Mips::BI__builtin_msa_maxi_u_d:
1521   case Mips::BI__builtin_msa_mini_u_b:
1522   case Mips::BI__builtin_msa_mini_u_h:
1523   case Mips::BI__builtin_msa_mini_u_w:
1524   case Mips::BI__builtin_msa_mini_u_d:
1525   case Mips::BI__builtin_msa_addvi_b:
1526   case Mips::BI__builtin_msa_addvi_h:
1527   case Mips::BI__builtin_msa_addvi_w:
1528   case Mips::BI__builtin_msa_addvi_d:
1529   case Mips::BI__builtin_msa_bclri_w:
1530   case Mips::BI__builtin_msa_bnegi_w:
1531   case Mips::BI__builtin_msa_bseti_w:
1532   case Mips::BI__builtin_msa_sat_s_w:
1533   case Mips::BI__builtin_msa_sat_u_w:
1534   case Mips::BI__builtin_msa_slli_w:
1535   case Mips::BI__builtin_msa_srai_w:
1536   case Mips::BI__builtin_msa_srari_w:
1537   case Mips::BI__builtin_msa_srli_w:
1538   case Mips::BI__builtin_msa_srlri_w:
1539   case Mips::BI__builtin_msa_subvi_b:
1540   case Mips::BI__builtin_msa_subvi_h:
1541   case Mips::BI__builtin_msa_subvi_w:
1542   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1543   case Mips::BI__builtin_msa_binsli_w:
1544   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1545   // These intrinsics take an unsigned 6 bit immediate.
1546   case Mips::BI__builtin_msa_bclri_d:
1547   case Mips::BI__builtin_msa_bnegi_d:
1548   case Mips::BI__builtin_msa_bseti_d:
1549   case Mips::BI__builtin_msa_sat_s_d:
1550   case Mips::BI__builtin_msa_sat_u_d:
1551   case Mips::BI__builtin_msa_slli_d:
1552   case Mips::BI__builtin_msa_srai_d:
1553   case Mips::BI__builtin_msa_srari_d:
1554   case Mips::BI__builtin_msa_srli_d:
1555   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1556   case Mips::BI__builtin_msa_binsli_d:
1557   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1558   // These intrinsics take a signed 5 bit immediate.
1559   case Mips::BI__builtin_msa_ceqi_b:
1560   case Mips::BI__builtin_msa_ceqi_h:
1561   case Mips::BI__builtin_msa_ceqi_w:
1562   case Mips::BI__builtin_msa_ceqi_d:
1563   case Mips::BI__builtin_msa_clti_s_b:
1564   case Mips::BI__builtin_msa_clti_s_h:
1565   case Mips::BI__builtin_msa_clti_s_w:
1566   case Mips::BI__builtin_msa_clti_s_d:
1567   case Mips::BI__builtin_msa_clei_s_b:
1568   case Mips::BI__builtin_msa_clei_s_h:
1569   case Mips::BI__builtin_msa_clei_s_w:
1570   case Mips::BI__builtin_msa_clei_s_d:
1571   case Mips::BI__builtin_msa_maxi_s_b:
1572   case Mips::BI__builtin_msa_maxi_s_h:
1573   case Mips::BI__builtin_msa_maxi_s_w:
1574   case Mips::BI__builtin_msa_maxi_s_d:
1575   case Mips::BI__builtin_msa_mini_s_b:
1576   case Mips::BI__builtin_msa_mini_s_h:
1577   case Mips::BI__builtin_msa_mini_s_w:
1578   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1579   // These intrinsics take an unsigned 8 bit immediate.
1580   case Mips::BI__builtin_msa_andi_b:
1581   case Mips::BI__builtin_msa_nori_b:
1582   case Mips::BI__builtin_msa_ori_b:
1583   case Mips::BI__builtin_msa_shf_b:
1584   case Mips::BI__builtin_msa_shf_h:
1585   case Mips::BI__builtin_msa_shf_w:
1586   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1587   case Mips::BI__builtin_msa_bseli_b:
1588   case Mips::BI__builtin_msa_bmnzi_b:
1589   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1590   // df/n format
1591   // These intrinsics take an unsigned 4 bit immediate.
1592   case Mips::BI__builtin_msa_copy_s_b:
1593   case Mips::BI__builtin_msa_copy_u_b:
1594   case Mips::BI__builtin_msa_insve_b:
1595   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1596   case Mips::BI__builtin_msa_sld_b:
1597   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1598   // These intrinsics take an unsigned 3 bit immediate.
1599   case Mips::BI__builtin_msa_copy_s_h:
1600   case Mips::BI__builtin_msa_copy_u_h:
1601   case Mips::BI__builtin_msa_insve_h:
1602   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1603   case Mips::BI__builtin_msa_sld_h:
1604   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1605   // These intrinsics take an unsigned 2 bit immediate.
1606   case Mips::BI__builtin_msa_copy_s_w:
1607   case Mips::BI__builtin_msa_copy_u_w:
1608   case Mips::BI__builtin_msa_insve_w:
1609   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1610   case Mips::BI__builtin_msa_sld_w:
1611   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1612   // These intrinsics take an unsigned 1 bit immediate.
1613   case Mips::BI__builtin_msa_copy_s_d:
1614   case Mips::BI__builtin_msa_copy_u_d:
1615   case Mips::BI__builtin_msa_insve_d:
1616   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1617   case Mips::BI__builtin_msa_sld_d:
1618   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1619   // Memory offsets and immediate loads.
1620   // These intrinsics take a signed 10 bit immediate.
1621   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1622   case Mips::BI__builtin_msa_ldi_h:
1623   case Mips::BI__builtin_msa_ldi_w:
1624   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1625   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1626   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1627   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1628   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1629   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1630   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1631   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1632   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1633   }
1634 
1635   if (!m)
1636     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1637 
1638   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1639          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1640 }
1641 
1642 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1643   unsigned i = 0, l = 0, u = 0;
1644   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1645                       BuiltinID == PPC::BI__builtin_divdeu ||
1646                       BuiltinID == PPC::BI__builtin_bpermd;
1647   bool IsTarget64Bit = Context.getTargetInfo()
1648                               .getTypeWidth(Context
1649                                             .getTargetInfo()
1650                                             .getIntPtrType()) == 64;
1651   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1652                        BuiltinID == PPC::BI__builtin_divweu ||
1653                        BuiltinID == PPC::BI__builtin_divde ||
1654                        BuiltinID == PPC::BI__builtin_divdeu;
1655 
1656   if (Is64BitBltin && !IsTarget64Bit)
1657       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1658              << TheCall->getSourceRange();
1659 
1660   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1661       (BuiltinID == PPC::BI__builtin_bpermd &&
1662        !Context.getTargetInfo().hasFeature("bpermd")))
1663     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1664            << TheCall->getSourceRange();
1665 
1666   switch (BuiltinID) {
1667   default: return false;
1668   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1669   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1670     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1671            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1672   case PPC::BI__builtin_tbegin:
1673   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1674   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1675   case PPC::BI__builtin_tabortwc:
1676   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1677   case PPC::BI__builtin_tabortwci:
1678   case PPC::BI__builtin_tabortdci:
1679     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1680            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1681   }
1682   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1683 }
1684 
1685 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1686                                            CallExpr *TheCall) {
1687   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1688     Expr *Arg = TheCall->getArg(0);
1689     llvm::APSInt AbortCode(32);
1690     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1691         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1692       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1693              << Arg->getSourceRange();
1694   }
1695 
1696   // For intrinsics which take an immediate value as part of the instruction,
1697   // range check them here.
1698   unsigned i = 0, l = 0, u = 0;
1699   switch (BuiltinID) {
1700   default: return false;
1701   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1702   case SystemZ::BI__builtin_s390_verimb:
1703   case SystemZ::BI__builtin_s390_verimh:
1704   case SystemZ::BI__builtin_s390_verimf:
1705   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1706   case SystemZ::BI__builtin_s390_vfaeb:
1707   case SystemZ::BI__builtin_s390_vfaeh:
1708   case SystemZ::BI__builtin_s390_vfaef:
1709   case SystemZ::BI__builtin_s390_vfaebs:
1710   case SystemZ::BI__builtin_s390_vfaehs:
1711   case SystemZ::BI__builtin_s390_vfaefs:
1712   case SystemZ::BI__builtin_s390_vfaezb:
1713   case SystemZ::BI__builtin_s390_vfaezh:
1714   case SystemZ::BI__builtin_s390_vfaezf:
1715   case SystemZ::BI__builtin_s390_vfaezbs:
1716   case SystemZ::BI__builtin_s390_vfaezhs:
1717   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1718   case SystemZ::BI__builtin_s390_vfidb:
1719     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1720            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1721   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1722   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1723   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1724   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1725   case SystemZ::BI__builtin_s390_vstrcb:
1726   case SystemZ::BI__builtin_s390_vstrch:
1727   case SystemZ::BI__builtin_s390_vstrcf:
1728   case SystemZ::BI__builtin_s390_vstrczb:
1729   case SystemZ::BI__builtin_s390_vstrczh:
1730   case SystemZ::BI__builtin_s390_vstrczf:
1731   case SystemZ::BI__builtin_s390_vstrcbs:
1732   case SystemZ::BI__builtin_s390_vstrchs:
1733   case SystemZ::BI__builtin_s390_vstrcfs:
1734   case SystemZ::BI__builtin_s390_vstrczbs:
1735   case SystemZ::BI__builtin_s390_vstrczhs:
1736   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1737   }
1738   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1739 }
1740 
1741 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1742 /// This checks that the target supports __builtin_cpu_supports and
1743 /// that the string argument is constant and valid.
1744 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1745   Expr *Arg = TheCall->getArg(0);
1746 
1747   // Check if the argument is a string literal.
1748   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1749     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1750            << Arg->getSourceRange();
1751 
1752   // Check the contents of the string.
1753   StringRef Feature =
1754       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1755   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1756     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1757            << Arg->getSourceRange();
1758   return false;
1759 }
1760 
1761 // Check if the rounding mode is legal.
1762 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1763   // Indicates if this instruction has rounding control or just SAE.
1764   bool HasRC = false;
1765 
1766   unsigned ArgNum = 0;
1767   switch (BuiltinID) {
1768   default:
1769     return false;
1770   case X86::BI__builtin_ia32_vcvttsd2si32:
1771   case X86::BI__builtin_ia32_vcvttsd2si64:
1772   case X86::BI__builtin_ia32_vcvttsd2usi32:
1773   case X86::BI__builtin_ia32_vcvttsd2usi64:
1774   case X86::BI__builtin_ia32_vcvttss2si32:
1775   case X86::BI__builtin_ia32_vcvttss2si64:
1776   case X86::BI__builtin_ia32_vcvttss2usi32:
1777   case X86::BI__builtin_ia32_vcvttss2usi64:
1778     ArgNum = 1;
1779     break;
1780   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1781   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1782   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1783   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1784   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1785   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1786   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1787   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1788   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1789   case X86::BI__builtin_ia32_exp2pd_mask:
1790   case X86::BI__builtin_ia32_exp2ps_mask:
1791   case X86::BI__builtin_ia32_getexppd512_mask:
1792   case X86::BI__builtin_ia32_getexpps512_mask:
1793   case X86::BI__builtin_ia32_rcp28pd_mask:
1794   case X86::BI__builtin_ia32_rcp28ps_mask:
1795   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1796   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1797   case X86::BI__builtin_ia32_vcomisd:
1798   case X86::BI__builtin_ia32_vcomiss:
1799   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1800     ArgNum = 3;
1801     break;
1802   case X86::BI__builtin_ia32_cmppd512_mask:
1803   case X86::BI__builtin_ia32_cmpps512_mask:
1804   case X86::BI__builtin_ia32_cmpsd_mask:
1805   case X86::BI__builtin_ia32_cmpss_mask:
1806   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1807   case X86::BI__builtin_ia32_getexpss128_round_mask:
1808   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1809   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1810   case X86::BI__builtin_ia32_reducepd512_mask:
1811   case X86::BI__builtin_ia32_reduceps512_mask:
1812   case X86::BI__builtin_ia32_rndscalepd_mask:
1813   case X86::BI__builtin_ia32_rndscaleps_mask:
1814   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1815   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1816     ArgNum = 4;
1817     break;
1818   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1819   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1820   case X86::BI__builtin_ia32_fixupimmps512_mask:
1821   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1822   case X86::BI__builtin_ia32_fixupimmsd_mask:
1823   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1824   case X86::BI__builtin_ia32_fixupimmss_mask:
1825   case X86::BI__builtin_ia32_fixupimmss_maskz:
1826   case X86::BI__builtin_ia32_rangepd512_mask:
1827   case X86::BI__builtin_ia32_rangeps512_mask:
1828   case X86::BI__builtin_ia32_rangesd128_round_mask:
1829   case X86::BI__builtin_ia32_rangess128_round_mask:
1830   case X86::BI__builtin_ia32_reducesd_mask:
1831   case X86::BI__builtin_ia32_reducess_mask:
1832   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1833   case X86::BI__builtin_ia32_rndscaless_round_mask:
1834     ArgNum = 5;
1835     break;
1836   case X86::BI__builtin_ia32_vcvtsd2si64:
1837   case X86::BI__builtin_ia32_vcvtsd2si32:
1838   case X86::BI__builtin_ia32_vcvtsd2usi32:
1839   case X86::BI__builtin_ia32_vcvtsd2usi64:
1840   case X86::BI__builtin_ia32_vcvtss2si32:
1841   case X86::BI__builtin_ia32_vcvtss2si64:
1842   case X86::BI__builtin_ia32_vcvtss2usi32:
1843   case X86::BI__builtin_ia32_vcvtss2usi64:
1844     ArgNum = 1;
1845     HasRC = true;
1846     break;
1847   case X86::BI__builtin_ia32_cvtusi2sd64:
1848   case X86::BI__builtin_ia32_cvtusi2ss32:
1849   case X86::BI__builtin_ia32_cvtusi2ss64:
1850     ArgNum = 2;
1851     HasRC = true;
1852     break;
1853   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1854   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1855   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1856   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1857   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1858   case X86::BI__builtin_ia32_cvtps2qq512_mask:
1859   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1860   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1861   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1862   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1863   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1864     ArgNum = 3;
1865     HasRC = true;
1866     break;
1867   case X86::BI__builtin_ia32_addpd512_mask:
1868   case X86::BI__builtin_ia32_addps512_mask:
1869   case X86::BI__builtin_ia32_divpd512_mask:
1870   case X86::BI__builtin_ia32_divps512_mask:
1871   case X86::BI__builtin_ia32_mulpd512_mask:
1872   case X86::BI__builtin_ia32_mulps512_mask:
1873   case X86::BI__builtin_ia32_subpd512_mask:
1874   case X86::BI__builtin_ia32_subps512_mask:
1875   case X86::BI__builtin_ia32_addss_round_mask:
1876   case X86::BI__builtin_ia32_addsd_round_mask:
1877   case X86::BI__builtin_ia32_divss_round_mask:
1878   case X86::BI__builtin_ia32_divsd_round_mask:
1879   case X86::BI__builtin_ia32_mulss_round_mask:
1880   case X86::BI__builtin_ia32_mulsd_round_mask:
1881   case X86::BI__builtin_ia32_subss_round_mask:
1882   case X86::BI__builtin_ia32_subsd_round_mask:
1883   case X86::BI__builtin_ia32_scalefpd512_mask:
1884   case X86::BI__builtin_ia32_scalefps512_mask:
1885   case X86::BI__builtin_ia32_scalefsd_round_mask:
1886   case X86::BI__builtin_ia32_scalefss_round_mask:
1887   case X86::BI__builtin_ia32_getmantpd512_mask:
1888   case X86::BI__builtin_ia32_getmantps512_mask:
1889   case X86::BI__builtin_ia32_vfmaddpd512_mask:
1890   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1891   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1892   case X86::BI__builtin_ia32_vfmaddps512_mask:
1893   case X86::BI__builtin_ia32_vfmaddps512_mask3:
1894   case X86::BI__builtin_ia32_vfmaddps512_maskz:
1895   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1896   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1897   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1898   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1899   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1900   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1901   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1902   case X86::BI__builtin_ia32_vfmsubps512_mask3:
1903   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1904   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1905   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1906   case X86::BI__builtin_ia32_vfnmaddps512_mask:
1907   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1908   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1909   case X86::BI__builtin_ia32_vfnmsubps512_mask:
1910   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1911   case X86::BI__builtin_ia32_vfmaddsd3_mask:
1912   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1913   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1914   case X86::BI__builtin_ia32_vfmaddss3_mask:
1915   case X86::BI__builtin_ia32_vfmaddss3_maskz:
1916   case X86::BI__builtin_ia32_vfmaddss3_mask3:
1917     ArgNum = 4;
1918     HasRC = true;
1919     break;
1920   case X86::BI__builtin_ia32_getmantsd_round_mask:
1921   case X86::BI__builtin_ia32_getmantss_round_mask:
1922     ArgNum = 5;
1923     HasRC = true;
1924     break;
1925   }
1926 
1927   llvm::APSInt Result;
1928 
1929   // We can't check the value of a dependent argument.
1930   Expr *Arg = TheCall->getArg(ArgNum);
1931   if (Arg->isTypeDependent() || Arg->isValueDependent())
1932     return false;
1933 
1934   // Check constant-ness first.
1935   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1936     return true;
1937 
1938   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1939   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1940   // combined with ROUND_NO_EXC.
1941   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1942       Result == 8/*ROUND_NO_EXC*/ ||
1943       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1944     return false;
1945 
1946   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1947     << Arg->getSourceRange();
1948 }
1949 
1950 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1951   if (BuiltinID == X86::BI__builtin_cpu_supports)
1952     return SemaBuiltinCpuSupports(*this, TheCall);
1953 
1954   if (BuiltinID == X86::BI__builtin_ms_va_start)
1955     return SemaBuiltinMSVAStart(TheCall);
1956 
1957   // If the intrinsic has rounding or SAE make sure its valid.
1958   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1959     return true;
1960 
1961   // For intrinsics which take an immediate value as part of the instruction,
1962   // range check them here.
1963   int i = 0, l = 0, u = 0;
1964   switch (BuiltinID) {
1965   default:
1966     return false;
1967   case X86::BI__builtin_ia32_extractf64x4_mask:
1968   case X86::BI__builtin_ia32_extracti64x4_mask:
1969   case X86::BI__builtin_ia32_extractf32x8_mask:
1970   case X86::BI__builtin_ia32_extracti32x8_mask:
1971   case X86::BI__builtin_ia32_extractf64x2_256_mask:
1972   case X86::BI__builtin_ia32_extracti64x2_256_mask:
1973   case X86::BI__builtin_ia32_extractf32x4_256_mask:
1974   case X86::BI__builtin_ia32_extracti32x4_256_mask:
1975     i = 1; l = 0; u = 1;
1976     break;
1977   case X86::BI_mm_prefetch:
1978   case X86::BI__builtin_ia32_extractf32x4_mask:
1979   case X86::BI__builtin_ia32_extracti32x4_mask:
1980   case X86::BI__builtin_ia32_extractf64x2_512_mask:
1981   case X86::BI__builtin_ia32_extracti64x2_512_mask:
1982     i = 1; l = 0; u = 3;
1983     break;
1984   case X86::BI__builtin_ia32_insertf32x8_mask:
1985   case X86::BI__builtin_ia32_inserti32x8_mask:
1986   case X86::BI__builtin_ia32_insertf64x4_mask:
1987   case X86::BI__builtin_ia32_inserti64x4_mask:
1988   case X86::BI__builtin_ia32_insertf64x2_256_mask:
1989   case X86::BI__builtin_ia32_inserti64x2_256_mask:
1990   case X86::BI__builtin_ia32_insertf32x4_256_mask:
1991   case X86::BI__builtin_ia32_inserti32x4_256_mask:
1992     i = 2; l = 0; u = 1;
1993     break;
1994   case X86::BI__builtin_ia32_sha1rnds4:
1995   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1996   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1997   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1998   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1999   case X86::BI__builtin_ia32_insertf64x2_512_mask:
2000   case X86::BI__builtin_ia32_inserti64x2_512_mask:
2001   case X86::BI__builtin_ia32_insertf32x4_mask:
2002   case X86::BI__builtin_ia32_inserti32x4_mask:
2003     i = 2; l = 0; u = 3;
2004     break;
2005   case X86::BI__builtin_ia32_vpermil2pd:
2006   case X86::BI__builtin_ia32_vpermil2pd256:
2007   case X86::BI__builtin_ia32_vpermil2ps:
2008   case X86::BI__builtin_ia32_vpermil2ps256:
2009     i = 3; l = 0; u = 3;
2010     break;
2011   case X86::BI__builtin_ia32_cmpb128_mask:
2012   case X86::BI__builtin_ia32_cmpw128_mask:
2013   case X86::BI__builtin_ia32_cmpd128_mask:
2014   case X86::BI__builtin_ia32_cmpq128_mask:
2015   case X86::BI__builtin_ia32_cmpb256_mask:
2016   case X86::BI__builtin_ia32_cmpw256_mask:
2017   case X86::BI__builtin_ia32_cmpd256_mask:
2018   case X86::BI__builtin_ia32_cmpq256_mask:
2019   case X86::BI__builtin_ia32_cmpb512_mask:
2020   case X86::BI__builtin_ia32_cmpw512_mask:
2021   case X86::BI__builtin_ia32_cmpd512_mask:
2022   case X86::BI__builtin_ia32_cmpq512_mask:
2023   case X86::BI__builtin_ia32_ucmpb128_mask:
2024   case X86::BI__builtin_ia32_ucmpw128_mask:
2025   case X86::BI__builtin_ia32_ucmpd128_mask:
2026   case X86::BI__builtin_ia32_ucmpq128_mask:
2027   case X86::BI__builtin_ia32_ucmpb256_mask:
2028   case X86::BI__builtin_ia32_ucmpw256_mask:
2029   case X86::BI__builtin_ia32_ucmpd256_mask:
2030   case X86::BI__builtin_ia32_ucmpq256_mask:
2031   case X86::BI__builtin_ia32_ucmpb512_mask:
2032   case X86::BI__builtin_ia32_ucmpw512_mask:
2033   case X86::BI__builtin_ia32_ucmpd512_mask:
2034   case X86::BI__builtin_ia32_ucmpq512_mask:
2035   case X86::BI__builtin_ia32_vpcomub:
2036   case X86::BI__builtin_ia32_vpcomuw:
2037   case X86::BI__builtin_ia32_vpcomud:
2038   case X86::BI__builtin_ia32_vpcomuq:
2039   case X86::BI__builtin_ia32_vpcomb:
2040   case X86::BI__builtin_ia32_vpcomw:
2041   case X86::BI__builtin_ia32_vpcomd:
2042   case X86::BI__builtin_ia32_vpcomq:
2043     i = 2; l = 0; u = 7;
2044     break;
2045   case X86::BI__builtin_ia32_roundps:
2046   case X86::BI__builtin_ia32_roundpd:
2047   case X86::BI__builtin_ia32_roundps256:
2048   case X86::BI__builtin_ia32_roundpd256:
2049     i = 1; l = 0; u = 15;
2050     break;
2051   case X86::BI__builtin_ia32_roundss:
2052   case X86::BI__builtin_ia32_roundsd:
2053   case X86::BI__builtin_ia32_rangepd128_mask:
2054   case X86::BI__builtin_ia32_rangepd256_mask:
2055   case X86::BI__builtin_ia32_rangepd512_mask:
2056   case X86::BI__builtin_ia32_rangeps128_mask:
2057   case X86::BI__builtin_ia32_rangeps256_mask:
2058   case X86::BI__builtin_ia32_rangeps512_mask:
2059   case X86::BI__builtin_ia32_getmantsd_round_mask:
2060   case X86::BI__builtin_ia32_getmantss_round_mask:
2061     i = 2; l = 0; u = 15;
2062     break;
2063   case X86::BI__builtin_ia32_cmpps:
2064   case X86::BI__builtin_ia32_cmpss:
2065   case X86::BI__builtin_ia32_cmppd:
2066   case X86::BI__builtin_ia32_cmpsd:
2067   case X86::BI__builtin_ia32_cmpps256:
2068   case X86::BI__builtin_ia32_cmppd256:
2069   case X86::BI__builtin_ia32_cmpps128_mask:
2070   case X86::BI__builtin_ia32_cmppd128_mask:
2071   case X86::BI__builtin_ia32_cmpps256_mask:
2072   case X86::BI__builtin_ia32_cmppd256_mask:
2073   case X86::BI__builtin_ia32_cmpps512_mask:
2074   case X86::BI__builtin_ia32_cmppd512_mask:
2075   case X86::BI__builtin_ia32_cmpsd_mask:
2076   case X86::BI__builtin_ia32_cmpss_mask:
2077     i = 2; l = 0; u = 31;
2078     break;
2079   case X86::BI__builtin_ia32_xabort:
2080     i = 0; l = -128; u = 255;
2081     break;
2082   case X86::BI__builtin_ia32_pshufw:
2083   case X86::BI__builtin_ia32_aeskeygenassist128:
2084     i = 1; l = -128; u = 255;
2085     break;
2086   case X86::BI__builtin_ia32_vcvtps2ph:
2087   case X86::BI__builtin_ia32_vcvtps2ph256:
2088   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2089   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2090   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2091   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2092   case X86::BI__builtin_ia32_rndscaleps_mask:
2093   case X86::BI__builtin_ia32_rndscalepd_mask:
2094   case X86::BI__builtin_ia32_reducepd128_mask:
2095   case X86::BI__builtin_ia32_reducepd256_mask:
2096   case X86::BI__builtin_ia32_reducepd512_mask:
2097   case X86::BI__builtin_ia32_reduceps128_mask:
2098   case X86::BI__builtin_ia32_reduceps256_mask:
2099   case X86::BI__builtin_ia32_reduceps512_mask:
2100   case X86::BI__builtin_ia32_prold512_mask:
2101   case X86::BI__builtin_ia32_prolq512_mask:
2102   case X86::BI__builtin_ia32_prold128_mask:
2103   case X86::BI__builtin_ia32_prold256_mask:
2104   case X86::BI__builtin_ia32_prolq128_mask:
2105   case X86::BI__builtin_ia32_prolq256_mask:
2106   case X86::BI__builtin_ia32_prord128_mask:
2107   case X86::BI__builtin_ia32_prord256_mask:
2108   case X86::BI__builtin_ia32_prorq128_mask:
2109   case X86::BI__builtin_ia32_prorq256_mask:
2110   case X86::BI__builtin_ia32_psllwi512_mask:
2111   case X86::BI__builtin_ia32_psllwi128_mask:
2112   case X86::BI__builtin_ia32_psllwi256_mask:
2113   case X86::BI__builtin_ia32_psrldi128_mask:
2114   case X86::BI__builtin_ia32_psrldi256_mask:
2115   case X86::BI__builtin_ia32_psrldi512_mask:
2116   case X86::BI__builtin_ia32_psrlqi128_mask:
2117   case X86::BI__builtin_ia32_psrlqi256_mask:
2118   case X86::BI__builtin_ia32_psrlqi512_mask:
2119   case X86::BI__builtin_ia32_psrawi512_mask:
2120   case X86::BI__builtin_ia32_psrawi128_mask:
2121   case X86::BI__builtin_ia32_psrawi256_mask:
2122   case X86::BI__builtin_ia32_psrlwi512_mask:
2123   case X86::BI__builtin_ia32_psrlwi128_mask:
2124   case X86::BI__builtin_ia32_psrlwi256_mask:
2125   case X86::BI__builtin_ia32_psradi128_mask:
2126   case X86::BI__builtin_ia32_psradi256_mask:
2127   case X86::BI__builtin_ia32_psradi512_mask:
2128   case X86::BI__builtin_ia32_psraqi128_mask:
2129   case X86::BI__builtin_ia32_psraqi256_mask:
2130   case X86::BI__builtin_ia32_psraqi512_mask:
2131   case X86::BI__builtin_ia32_pslldi128_mask:
2132   case X86::BI__builtin_ia32_pslldi256_mask:
2133   case X86::BI__builtin_ia32_pslldi512_mask:
2134   case X86::BI__builtin_ia32_psllqi128_mask:
2135   case X86::BI__builtin_ia32_psllqi256_mask:
2136   case X86::BI__builtin_ia32_psllqi512_mask:
2137   case X86::BI__builtin_ia32_fpclasspd128_mask:
2138   case X86::BI__builtin_ia32_fpclasspd256_mask:
2139   case X86::BI__builtin_ia32_fpclassps128_mask:
2140   case X86::BI__builtin_ia32_fpclassps256_mask:
2141   case X86::BI__builtin_ia32_fpclassps512_mask:
2142   case X86::BI__builtin_ia32_fpclasspd512_mask:
2143   case X86::BI__builtin_ia32_fpclasssd_mask:
2144   case X86::BI__builtin_ia32_fpclassss_mask:
2145     i = 1; l = 0; u = 255;
2146     break;
2147   case X86::BI__builtin_ia32_palignr:
2148   case X86::BI__builtin_ia32_insertps128:
2149   case X86::BI__builtin_ia32_dpps:
2150   case X86::BI__builtin_ia32_dppd:
2151   case X86::BI__builtin_ia32_dpps256:
2152   case X86::BI__builtin_ia32_mpsadbw128:
2153   case X86::BI__builtin_ia32_mpsadbw256:
2154   case X86::BI__builtin_ia32_pcmpistrm128:
2155   case X86::BI__builtin_ia32_pcmpistri128:
2156   case X86::BI__builtin_ia32_pcmpistria128:
2157   case X86::BI__builtin_ia32_pcmpistric128:
2158   case X86::BI__builtin_ia32_pcmpistrio128:
2159   case X86::BI__builtin_ia32_pcmpistris128:
2160   case X86::BI__builtin_ia32_pcmpistriz128:
2161   case X86::BI__builtin_ia32_pclmulqdq128:
2162   case X86::BI__builtin_ia32_vperm2f128_pd256:
2163   case X86::BI__builtin_ia32_vperm2f128_ps256:
2164   case X86::BI__builtin_ia32_vperm2f128_si256:
2165   case X86::BI__builtin_ia32_permti256:
2166     i = 2; l = -128; u = 255;
2167     break;
2168   case X86::BI__builtin_ia32_palignr128:
2169   case X86::BI__builtin_ia32_palignr256:
2170   case X86::BI__builtin_ia32_palignr512_mask:
2171   case X86::BI__builtin_ia32_alignq512_mask:
2172   case X86::BI__builtin_ia32_alignd512_mask:
2173   case X86::BI__builtin_ia32_alignd128_mask:
2174   case X86::BI__builtin_ia32_alignd256_mask:
2175   case X86::BI__builtin_ia32_alignq128_mask:
2176   case X86::BI__builtin_ia32_alignq256_mask:
2177   case X86::BI__builtin_ia32_vcomisd:
2178   case X86::BI__builtin_ia32_vcomiss:
2179   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2180   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2181   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2182   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2183   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2184   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2185   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2186     i = 2; l = 0; u = 255;
2187     break;
2188   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2189   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2190   case X86::BI__builtin_ia32_fixupimmps512_mask:
2191   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2192   case X86::BI__builtin_ia32_fixupimmsd_mask:
2193   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2194   case X86::BI__builtin_ia32_fixupimmss_mask:
2195   case X86::BI__builtin_ia32_fixupimmss_maskz:
2196   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2197   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2198   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2199   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2200   case X86::BI__builtin_ia32_fixupimmps128_mask:
2201   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2202   case X86::BI__builtin_ia32_fixupimmps256_mask:
2203   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2204   case X86::BI__builtin_ia32_pternlogd512_mask:
2205   case X86::BI__builtin_ia32_pternlogd512_maskz:
2206   case X86::BI__builtin_ia32_pternlogq512_mask:
2207   case X86::BI__builtin_ia32_pternlogq512_maskz:
2208   case X86::BI__builtin_ia32_pternlogd128_mask:
2209   case X86::BI__builtin_ia32_pternlogd128_maskz:
2210   case X86::BI__builtin_ia32_pternlogd256_mask:
2211   case X86::BI__builtin_ia32_pternlogd256_maskz:
2212   case X86::BI__builtin_ia32_pternlogq128_mask:
2213   case X86::BI__builtin_ia32_pternlogq128_maskz:
2214   case X86::BI__builtin_ia32_pternlogq256_mask:
2215   case X86::BI__builtin_ia32_pternlogq256_maskz:
2216     i = 3; l = 0; u = 255;
2217     break;
2218   case X86::BI__builtin_ia32_pcmpestrm128:
2219   case X86::BI__builtin_ia32_pcmpestri128:
2220   case X86::BI__builtin_ia32_pcmpestria128:
2221   case X86::BI__builtin_ia32_pcmpestric128:
2222   case X86::BI__builtin_ia32_pcmpestrio128:
2223   case X86::BI__builtin_ia32_pcmpestris128:
2224   case X86::BI__builtin_ia32_pcmpestriz128:
2225     i = 4; l = -128; u = 255;
2226     break;
2227   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2228   case X86::BI__builtin_ia32_rndscaless_round_mask:
2229     i = 4; l = 0; u = 255;
2230     break;
2231   }
2232   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2233 }
2234 
2235 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2236 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2237 /// Returns true when the format fits the function and the FormatStringInfo has
2238 /// been populated.
2239 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2240                                FormatStringInfo *FSI) {
2241   FSI->HasVAListArg = Format->getFirstArg() == 0;
2242   FSI->FormatIdx = Format->getFormatIdx() - 1;
2243   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2244 
2245   // The way the format attribute works in GCC, the implicit this argument
2246   // of member functions is counted. However, it doesn't appear in our own
2247   // lists, so decrement format_idx in that case.
2248   if (IsCXXMember) {
2249     if(FSI->FormatIdx == 0)
2250       return false;
2251     --FSI->FormatIdx;
2252     if (FSI->FirstDataArg != 0)
2253       --FSI->FirstDataArg;
2254   }
2255   return true;
2256 }
2257 
2258 /// Checks if a the given expression evaluates to null.
2259 ///
2260 /// \brief Returns true if the value evaluates to null.
2261 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2262   // If the expression has non-null type, it doesn't evaluate to null.
2263   if (auto nullability
2264         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2265     if (*nullability == NullabilityKind::NonNull)
2266       return false;
2267   }
2268 
2269   // As a special case, transparent unions initialized with zero are
2270   // considered null for the purposes of the nonnull attribute.
2271   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2272     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2273       if (const CompoundLiteralExpr *CLE =
2274           dyn_cast<CompoundLiteralExpr>(Expr))
2275         if (const InitListExpr *ILE =
2276             dyn_cast<InitListExpr>(CLE->getInitializer()))
2277           Expr = ILE->getInit(0);
2278   }
2279 
2280   bool Result;
2281   return (!Expr->isValueDependent() &&
2282           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2283           !Result);
2284 }
2285 
2286 static void CheckNonNullArgument(Sema &S,
2287                                  const Expr *ArgExpr,
2288                                  SourceLocation CallSiteLoc) {
2289   if (CheckNonNullExpr(S, ArgExpr))
2290     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2291            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2292 }
2293 
2294 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2295   FormatStringInfo FSI;
2296   if ((GetFormatStringType(Format) == FST_NSString) &&
2297       getFormatStringInfo(Format, false, &FSI)) {
2298     Idx = FSI.FormatIdx;
2299     return true;
2300   }
2301   return false;
2302 }
2303 /// \brief Diagnose use of %s directive in an NSString which is being passed
2304 /// as formatting string to formatting method.
2305 static void
2306 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2307                                         const NamedDecl *FDecl,
2308                                         Expr **Args,
2309                                         unsigned NumArgs) {
2310   unsigned Idx = 0;
2311   bool Format = false;
2312   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2313   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2314     Idx = 2;
2315     Format = true;
2316   }
2317   else
2318     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2319       if (S.GetFormatNSStringIdx(I, Idx)) {
2320         Format = true;
2321         break;
2322       }
2323     }
2324   if (!Format || NumArgs <= Idx)
2325     return;
2326   const Expr *FormatExpr = Args[Idx];
2327   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2328     FormatExpr = CSCE->getSubExpr();
2329   const StringLiteral *FormatString;
2330   if (const ObjCStringLiteral *OSL =
2331       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2332     FormatString = OSL->getString();
2333   else
2334     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2335   if (!FormatString)
2336     return;
2337   if (S.FormatStringHasSArg(FormatString)) {
2338     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2339       << "%s" << 1 << 1;
2340     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2341       << FDecl->getDeclName();
2342   }
2343 }
2344 
2345 /// Determine whether the given type has a non-null nullability annotation.
2346 static bool isNonNullType(ASTContext &ctx, QualType type) {
2347   if (auto nullability = type->getNullability(ctx))
2348     return *nullability == NullabilityKind::NonNull;
2349 
2350   return false;
2351 }
2352 
2353 static void CheckNonNullArguments(Sema &S,
2354                                   const NamedDecl *FDecl,
2355                                   const FunctionProtoType *Proto,
2356                                   ArrayRef<const Expr *> Args,
2357                                   SourceLocation CallSiteLoc) {
2358   assert((FDecl || Proto) && "Need a function declaration or prototype");
2359 
2360   // Check the attributes attached to the method/function itself.
2361   llvm::SmallBitVector NonNullArgs;
2362   if (FDecl) {
2363     // Handle the nonnull attribute on the function/method declaration itself.
2364     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2365       if (!NonNull->args_size()) {
2366         // Easy case: all pointer arguments are nonnull.
2367         for (const auto *Arg : Args)
2368           if (S.isValidPointerAttrType(Arg->getType()))
2369             CheckNonNullArgument(S, Arg, CallSiteLoc);
2370         return;
2371       }
2372 
2373       for (unsigned Val : NonNull->args()) {
2374         if (Val >= Args.size())
2375           continue;
2376         if (NonNullArgs.empty())
2377           NonNullArgs.resize(Args.size());
2378         NonNullArgs.set(Val);
2379       }
2380     }
2381   }
2382 
2383   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2384     // Handle the nonnull attribute on the parameters of the
2385     // function/method.
2386     ArrayRef<ParmVarDecl*> parms;
2387     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2388       parms = FD->parameters();
2389     else
2390       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2391 
2392     unsigned ParamIndex = 0;
2393     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2394          I != E; ++I, ++ParamIndex) {
2395       const ParmVarDecl *PVD = *I;
2396       if (PVD->hasAttr<NonNullAttr>() ||
2397           isNonNullType(S.Context, PVD->getType())) {
2398         if (NonNullArgs.empty())
2399           NonNullArgs.resize(Args.size());
2400 
2401         NonNullArgs.set(ParamIndex);
2402       }
2403     }
2404   } else {
2405     // If we have a non-function, non-method declaration but no
2406     // function prototype, try to dig out the function prototype.
2407     if (!Proto) {
2408       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2409         QualType type = VD->getType().getNonReferenceType();
2410         if (auto pointerType = type->getAs<PointerType>())
2411           type = pointerType->getPointeeType();
2412         else if (auto blockType = type->getAs<BlockPointerType>())
2413           type = blockType->getPointeeType();
2414         // FIXME: data member pointers?
2415 
2416         // Dig out the function prototype, if there is one.
2417         Proto = type->getAs<FunctionProtoType>();
2418       }
2419     }
2420 
2421     // Fill in non-null argument information from the nullability
2422     // information on the parameter types (if we have them).
2423     if (Proto) {
2424       unsigned Index = 0;
2425       for (auto paramType : Proto->getParamTypes()) {
2426         if (isNonNullType(S.Context, paramType)) {
2427           if (NonNullArgs.empty())
2428             NonNullArgs.resize(Args.size());
2429 
2430           NonNullArgs.set(Index);
2431         }
2432 
2433         ++Index;
2434       }
2435     }
2436   }
2437 
2438   // Check for non-null arguments.
2439   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2440        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2441     if (NonNullArgs[ArgIndex])
2442       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2443   }
2444 }
2445 
2446 /// Handles the checks for format strings, non-POD arguments to vararg
2447 /// functions, and NULL arguments passed to non-NULL parameters.
2448 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2449                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
2450                      SourceLocation Loc, SourceRange Range,
2451                      VariadicCallType CallType) {
2452   // FIXME: We should check as much as we can in the template definition.
2453   if (CurContext->isDependentContext())
2454     return;
2455 
2456   // Printf and scanf checking.
2457   llvm::SmallBitVector CheckedVarArgs;
2458   if (FDecl) {
2459     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2460       // Only create vector if there are format attributes.
2461       CheckedVarArgs.resize(Args.size());
2462 
2463       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2464                            CheckedVarArgs);
2465     }
2466   }
2467 
2468   // Refuse POD arguments that weren't caught by the format string
2469   // checks above.
2470   if (CallType != VariadicDoesNotApply) {
2471     unsigned NumParams = Proto ? Proto->getNumParams()
2472                        : FDecl && isa<FunctionDecl>(FDecl)
2473                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2474                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2475                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2476                        : 0;
2477 
2478     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2479       // Args[ArgIdx] can be null in malformed code.
2480       if (const Expr *Arg = Args[ArgIdx]) {
2481         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2482           checkVariadicArgument(Arg, CallType);
2483       }
2484     }
2485   }
2486 
2487   if (FDecl || Proto) {
2488     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2489 
2490     // Type safety checking.
2491     if (FDecl) {
2492       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2493         CheckArgumentWithTypeTag(I, Args.data());
2494     }
2495   }
2496 }
2497 
2498 /// CheckConstructorCall - Check a constructor call for correctness and safety
2499 /// properties not enforced by the C type system.
2500 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2501                                 ArrayRef<const Expr *> Args,
2502                                 const FunctionProtoType *Proto,
2503                                 SourceLocation Loc) {
2504   VariadicCallType CallType =
2505     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2506   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2507             CallType);
2508 }
2509 
2510 /// CheckFunctionCall - Check a direct function call for various correctness
2511 /// and safety properties not strictly enforced by the C type system.
2512 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2513                              const FunctionProtoType *Proto) {
2514   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2515                               isa<CXXMethodDecl>(FDecl);
2516   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2517                           IsMemberOperatorCall;
2518   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2519                                                   TheCall->getCallee());
2520   Expr** Args = TheCall->getArgs();
2521   unsigned NumArgs = TheCall->getNumArgs();
2522   if (IsMemberOperatorCall) {
2523     // If this is a call to a member operator, hide the first argument
2524     // from checkCall.
2525     // FIXME: Our choice of AST representation here is less than ideal.
2526     ++Args;
2527     --NumArgs;
2528   }
2529   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2530             IsMemberFunction, TheCall->getRParenLoc(),
2531             TheCall->getCallee()->getSourceRange(), CallType);
2532 
2533   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2534   // None of the checks below are needed for functions that don't have
2535   // simple names (e.g., C++ conversion functions).
2536   if (!FnInfo)
2537     return false;
2538 
2539   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
2540   if (getLangOpts().ObjC1)
2541     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2542 
2543   unsigned CMId = FDecl->getMemoryFunctionKind();
2544   if (CMId == 0)
2545     return false;
2546 
2547   // Handle memory setting and copying functions.
2548   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2549     CheckStrlcpycatArguments(TheCall, FnInfo);
2550   else if (CMId == Builtin::BIstrncat)
2551     CheckStrncatArguments(TheCall, FnInfo);
2552   else
2553     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2554 
2555   return false;
2556 }
2557 
2558 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2559                                ArrayRef<const Expr *> Args) {
2560   VariadicCallType CallType =
2561       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2562 
2563   checkCall(Method, nullptr, Args,
2564             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2565             CallType);
2566 
2567   return false;
2568 }
2569 
2570 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2571                             const FunctionProtoType *Proto) {
2572   QualType Ty;
2573   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2574     Ty = V->getType().getNonReferenceType();
2575   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2576     Ty = F->getType().getNonReferenceType();
2577   else
2578     return false;
2579 
2580   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2581       !Ty->isFunctionProtoType())
2582     return false;
2583 
2584   VariadicCallType CallType;
2585   if (!Proto || !Proto->isVariadic()) {
2586     CallType = VariadicDoesNotApply;
2587   } else if (Ty->isBlockPointerType()) {
2588     CallType = VariadicBlock;
2589   } else { // Ty->isFunctionPointerType()
2590     CallType = VariadicFunction;
2591   }
2592 
2593   checkCall(NDecl, Proto,
2594             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2595             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2596             TheCall->getCallee()->getSourceRange(), CallType);
2597 
2598   return false;
2599 }
2600 
2601 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2602 /// such as function pointers returned from functions.
2603 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2604   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2605                                                   TheCall->getCallee());
2606   checkCall(/*FDecl=*/nullptr, Proto,
2607             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2608             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2609             TheCall->getCallee()->getSourceRange(), CallType);
2610 
2611   return false;
2612 }
2613 
2614 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2615   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2616     return false;
2617 
2618   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2619   switch (Op) {
2620   case AtomicExpr::AO__c11_atomic_init:
2621     llvm_unreachable("There is no ordering argument for an init");
2622 
2623   case AtomicExpr::AO__c11_atomic_load:
2624   case AtomicExpr::AO__atomic_load_n:
2625   case AtomicExpr::AO__atomic_load:
2626     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2627            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2628 
2629   case AtomicExpr::AO__c11_atomic_store:
2630   case AtomicExpr::AO__atomic_store:
2631   case AtomicExpr::AO__atomic_store_n:
2632     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2633            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2634            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2635 
2636   default:
2637     return true;
2638   }
2639 }
2640 
2641 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2642                                          AtomicExpr::AtomicOp Op) {
2643   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2644   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2645 
2646   // All these operations take one of the following forms:
2647   enum {
2648     // C    __c11_atomic_init(A *, C)
2649     Init,
2650     // C    __c11_atomic_load(A *, int)
2651     Load,
2652     // void __atomic_load(A *, CP, int)
2653     LoadCopy,
2654     // void __atomic_store(A *, CP, int)
2655     Copy,
2656     // C    __c11_atomic_add(A *, M, int)
2657     Arithmetic,
2658     // C    __atomic_exchange_n(A *, CP, int)
2659     Xchg,
2660     // void __atomic_exchange(A *, C *, CP, int)
2661     GNUXchg,
2662     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2663     C11CmpXchg,
2664     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2665     GNUCmpXchg
2666   } Form = Init;
2667   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2668   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2669   // where:
2670   //   C is an appropriate type,
2671   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2672   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2673   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2674   //   the int parameters are for orderings.
2675 
2676   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2677                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2678                         AtomicExpr::AO__atomic_load,
2679                 "need to update code for modified C11 atomics");
2680   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2681                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2682   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2683              Op == AtomicExpr::AO__atomic_store_n ||
2684              Op == AtomicExpr::AO__atomic_exchange_n ||
2685              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2686   bool IsAddSub = false;
2687 
2688   switch (Op) {
2689   case AtomicExpr::AO__c11_atomic_init:
2690     Form = Init;
2691     break;
2692 
2693   case AtomicExpr::AO__c11_atomic_load:
2694   case AtomicExpr::AO__atomic_load_n:
2695     Form = Load;
2696     break;
2697 
2698   case AtomicExpr::AO__atomic_load:
2699     Form = LoadCopy;
2700     break;
2701 
2702   case AtomicExpr::AO__c11_atomic_store:
2703   case AtomicExpr::AO__atomic_store:
2704   case AtomicExpr::AO__atomic_store_n:
2705     Form = Copy;
2706     break;
2707 
2708   case AtomicExpr::AO__c11_atomic_fetch_add:
2709   case AtomicExpr::AO__c11_atomic_fetch_sub:
2710   case AtomicExpr::AO__atomic_fetch_add:
2711   case AtomicExpr::AO__atomic_fetch_sub:
2712   case AtomicExpr::AO__atomic_add_fetch:
2713   case AtomicExpr::AO__atomic_sub_fetch:
2714     IsAddSub = true;
2715     // Fall through.
2716   case AtomicExpr::AO__c11_atomic_fetch_and:
2717   case AtomicExpr::AO__c11_atomic_fetch_or:
2718   case AtomicExpr::AO__c11_atomic_fetch_xor:
2719   case AtomicExpr::AO__atomic_fetch_and:
2720   case AtomicExpr::AO__atomic_fetch_or:
2721   case AtomicExpr::AO__atomic_fetch_xor:
2722   case AtomicExpr::AO__atomic_fetch_nand:
2723   case AtomicExpr::AO__atomic_and_fetch:
2724   case AtomicExpr::AO__atomic_or_fetch:
2725   case AtomicExpr::AO__atomic_xor_fetch:
2726   case AtomicExpr::AO__atomic_nand_fetch:
2727     Form = Arithmetic;
2728     break;
2729 
2730   case AtomicExpr::AO__c11_atomic_exchange:
2731   case AtomicExpr::AO__atomic_exchange_n:
2732     Form = Xchg;
2733     break;
2734 
2735   case AtomicExpr::AO__atomic_exchange:
2736     Form = GNUXchg;
2737     break;
2738 
2739   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2740   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2741     Form = C11CmpXchg;
2742     break;
2743 
2744   case AtomicExpr::AO__atomic_compare_exchange:
2745   case AtomicExpr::AO__atomic_compare_exchange_n:
2746     Form = GNUCmpXchg;
2747     break;
2748   }
2749 
2750   // Check we have the right number of arguments.
2751   if (TheCall->getNumArgs() < NumArgs[Form]) {
2752     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2753       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2754       << TheCall->getCallee()->getSourceRange();
2755     return ExprError();
2756   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2757     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2758          diag::err_typecheck_call_too_many_args)
2759       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2760       << TheCall->getCallee()->getSourceRange();
2761     return ExprError();
2762   }
2763 
2764   // Inspect the first argument of the atomic operation.
2765   Expr *Ptr = TheCall->getArg(0);
2766   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2767   if (ConvertedPtr.isInvalid())
2768     return ExprError();
2769 
2770   Ptr = ConvertedPtr.get();
2771   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2772   if (!pointerType) {
2773     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2774       << Ptr->getType() << Ptr->getSourceRange();
2775     return ExprError();
2776   }
2777 
2778   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2779   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2780   QualType ValType = AtomTy; // 'C'
2781   if (IsC11) {
2782     if (!AtomTy->isAtomicType()) {
2783       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2784         << Ptr->getType() << Ptr->getSourceRange();
2785       return ExprError();
2786     }
2787     if (AtomTy.isConstQualified()) {
2788       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2789         << Ptr->getType() << Ptr->getSourceRange();
2790       return ExprError();
2791     }
2792     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2793   } else if (Form != Load && Form != LoadCopy) {
2794     if (ValType.isConstQualified()) {
2795       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2796         << Ptr->getType() << Ptr->getSourceRange();
2797       return ExprError();
2798     }
2799   }
2800 
2801   // For an arithmetic operation, the implied arithmetic must be well-formed.
2802   if (Form == Arithmetic) {
2803     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2804     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2805       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2806         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2807       return ExprError();
2808     }
2809     if (!IsAddSub && !ValType->isIntegerType()) {
2810       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2811         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2812       return ExprError();
2813     }
2814     if (IsC11 && ValType->isPointerType() &&
2815         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2816                             diag::err_incomplete_type)) {
2817       return ExprError();
2818     }
2819   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2820     // For __atomic_*_n operations, the value type must be a scalar integral or
2821     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2822     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2823       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2824     return ExprError();
2825   }
2826 
2827   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2828       !AtomTy->isScalarType()) {
2829     // For GNU atomics, require a trivially-copyable type. This is not part of
2830     // the GNU atomics specification, but we enforce it for sanity.
2831     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2832       << Ptr->getType() << Ptr->getSourceRange();
2833     return ExprError();
2834   }
2835 
2836   switch (ValType.getObjCLifetime()) {
2837   case Qualifiers::OCL_None:
2838   case Qualifiers::OCL_ExplicitNone:
2839     // okay
2840     break;
2841 
2842   case Qualifiers::OCL_Weak:
2843   case Qualifiers::OCL_Strong:
2844   case Qualifiers::OCL_Autoreleasing:
2845     // FIXME: Can this happen? By this point, ValType should be known
2846     // to be trivially copyable.
2847     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2848       << ValType << Ptr->getSourceRange();
2849     return ExprError();
2850   }
2851 
2852   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2853   // volatile-ness of the pointee-type inject itself into the result or the
2854   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2855   ValType.removeLocalVolatile();
2856   ValType.removeLocalConst();
2857   QualType ResultType = ValType;
2858   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2859     ResultType = Context.VoidTy;
2860   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2861     ResultType = Context.BoolTy;
2862 
2863   // The type of a parameter passed 'by value'. In the GNU atomics, such
2864   // arguments are actually passed as pointers.
2865   QualType ByValType = ValType; // 'CP'
2866   if (!IsC11 && !IsN)
2867     ByValType = Ptr->getType();
2868 
2869   // The first argument --- the pointer --- has a fixed type; we
2870   // deduce the types of the rest of the arguments accordingly.  Walk
2871   // the remaining arguments, converting them to the deduced value type.
2872   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2873     QualType Ty;
2874     if (i < NumVals[Form] + 1) {
2875       switch (i) {
2876       case 1:
2877         // The second argument is the non-atomic operand. For arithmetic, this
2878         // is always passed by value, and for a compare_exchange it is always
2879         // passed by address. For the rest, GNU uses by-address and C11 uses
2880         // by-value.
2881         assert(Form != Load);
2882         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2883           Ty = ValType;
2884         else if (Form == Copy || Form == Xchg)
2885           Ty = ByValType;
2886         else if (Form == Arithmetic)
2887           Ty = Context.getPointerDiffType();
2888         else {
2889           Expr *ValArg = TheCall->getArg(i);
2890           unsigned AS = 0;
2891           // Keep address space of non-atomic pointer type.
2892           if (const PointerType *PtrTy =
2893                   ValArg->getType()->getAs<PointerType>()) {
2894             AS = PtrTy->getPointeeType().getAddressSpace();
2895           }
2896           Ty = Context.getPointerType(
2897               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2898         }
2899         break;
2900       case 2:
2901         // The third argument to compare_exchange / GNU exchange is a
2902         // (pointer to a) desired value.
2903         Ty = ByValType;
2904         break;
2905       case 3:
2906         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2907         Ty = Context.BoolTy;
2908         break;
2909       }
2910     } else {
2911       // The order(s) are always converted to int.
2912       Ty = Context.IntTy;
2913     }
2914 
2915     InitializedEntity Entity =
2916         InitializedEntity::InitializeParameter(Context, Ty, false);
2917     ExprResult Arg = TheCall->getArg(i);
2918     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2919     if (Arg.isInvalid())
2920       return true;
2921     TheCall->setArg(i, Arg.get());
2922   }
2923 
2924   // Permute the arguments into a 'consistent' order.
2925   SmallVector<Expr*, 5> SubExprs;
2926   SubExprs.push_back(Ptr);
2927   switch (Form) {
2928   case Init:
2929     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2930     SubExprs.push_back(TheCall->getArg(1)); // Val1
2931     break;
2932   case Load:
2933     SubExprs.push_back(TheCall->getArg(1)); // Order
2934     break;
2935   case LoadCopy:
2936   case Copy:
2937   case Arithmetic:
2938   case Xchg:
2939     SubExprs.push_back(TheCall->getArg(2)); // Order
2940     SubExprs.push_back(TheCall->getArg(1)); // Val1
2941     break;
2942   case GNUXchg:
2943     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2944     SubExprs.push_back(TheCall->getArg(3)); // Order
2945     SubExprs.push_back(TheCall->getArg(1)); // Val1
2946     SubExprs.push_back(TheCall->getArg(2)); // Val2
2947     break;
2948   case C11CmpXchg:
2949     SubExprs.push_back(TheCall->getArg(3)); // Order
2950     SubExprs.push_back(TheCall->getArg(1)); // Val1
2951     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2952     SubExprs.push_back(TheCall->getArg(2)); // Val2
2953     break;
2954   case GNUCmpXchg:
2955     SubExprs.push_back(TheCall->getArg(4)); // Order
2956     SubExprs.push_back(TheCall->getArg(1)); // Val1
2957     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2958     SubExprs.push_back(TheCall->getArg(2)); // Val2
2959     SubExprs.push_back(TheCall->getArg(3)); // Weak
2960     break;
2961   }
2962 
2963   if (SubExprs.size() >= 2 && Form != Init) {
2964     llvm::APSInt Result(32);
2965     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2966         !isValidOrderingForOp(Result.getSExtValue(), Op))
2967       Diag(SubExprs[1]->getLocStart(),
2968            diag::warn_atomic_op_has_invalid_memory_order)
2969           << SubExprs[1]->getSourceRange();
2970   }
2971 
2972   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2973                                             SubExprs, ResultType, Op,
2974                                             TheCall->getRParenLoc());
2975 
2976   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2977        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2978       Context.AtomicUsesUnsupportedLibcall(AE))
2979     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2980     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2981 
2982   return AE;
2983 }
2984 
2985 /// checkBuiltinArgument - Given a call to a builtin function, perform
2986 /// normal type-checking on the given argument, updating the call in
2987 /// place.  This is useful when a builtin function requires custom
2988 /// type-checking for some of its arguments but not necessarily all of
2989 /// them.
2990 ///
2991 /// Returns true on error.
2992 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2993   FunctionDecl *Fn = E->getDirectCallee();
2994   assert(Fn && "builtin call without direct callee!");
2995 
2996   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2997   InitializedEntity Entity =
2998     InitializedEntity::InitializeParameter(S.Context, Param);
2999 
3000   ExprResult Arg = E->getArg(0);
3001   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3002   if (Arg.isInvalid())
3003     return true;
3004 
3005   E->setArg(ArgIndex, Arg.get());
3006   return false;
3007 }
3008 
3009 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3010 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3011 /// type of its first argument.  The main ActOnCallExpr routines have already
3012 /// promoted the types of arguments because all of these calls are prototyped as
3013 /// void(...).
3014 ///
3015 /// This function goes through and does final semantic checking for these
3016 /// builtins,
3017 ExprResult
3018 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3019   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3020   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3021   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3022 
3023   // Ensure that we have at least one argument to do type inference from.
3024   if (TheCall->getNumArgs() < 1) {
3025     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3026       << 0 << 1 << TheCall->getNumArgs()
3027       << TheCall->getCallee()->getSourceRange();
3028     return ExprError();
3029   }
3030 
3031   // Inspect the first argument of the atomic builtin.  This should always be
3032   // a pointer type, whose element is an integral scalar or pointer type.
3033   // Because it is a pointer type, we don't have to worry about any implicit
3034   // casts here.
3035   // FIXME: We don't allow floating point scalars as input.
3036   Expr *FirstArg = TheCall->getArg(0);
3037   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3038   if (FirstArgResult.isInvalid())
3039     return ExprError();
3040   FirstArg = FirstArgResult.get();
3041   TheCall->setArg(0, FirstArg);
3042 
3043   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3044   if (!pointerType) {
3045     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3046       << FirstArg->getType() << FirstArg->getSourceRange();
3047     return ExprError();
3048   }
3049 
3050   QualType ValType = pointerType->getPointeeType();
3051   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3052       !ValType->isBlockPointerType()) {
3053     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3054       << FirstArg->getType() << FirstArg->getSourceRange();
3055     return ExprError();
3056   }
3057 
3058   switch (ValType.getObjCLifetime()) {
3059   case Qualifiers::OCL_None:
3060   case Qualifiers::OCL_ExplicitNone:
3061     // okay
3062     break;
3063 
3064   case Qualifiers::OCL_Weak:
3065   case Qualifiers::OCL_Strong:
3066   case Qualifiers::OCL_Autoreleasing:
3067     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3068       << ValType << FirstArg->getSourceRange();
3069     return ExprError();
3070   }
3071 
3072   // Strip any qualifiers off ValType.
3073   ValType = ValType.getUnqualifiedType();
3074 
3075   // The majority of builtins return a value, but a few have special return
3076   // types, so allow them to override appropriately below.
3077   QualType ResultType = ValType;
3078 
3079   // We need to figure out which concrete builtin this maps onto.  For example,
3080   // __sync_fetch_and_add with a 2 byte object turns into
3081   // __sync_fetch_and_add_2.
3082 #define BUILTIN_ROW(x) \
3083   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3084     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3085 
3086   static const unsigned BuiltinIndices[][5] = {
3087     BUILTIN_ROW(__sync_fetch_and_add),
3088     BUILTIN_ROW(__sync_fetch_and_sub),
3089     BUILTIN_ROW(__sync_fetch_and_or),
3090     BUILTIN_ROW(__sync_fetch_and_and),
3091     BUILTIN_ROW(__sync_fetch_and_xor),
3092     BUILTIN_ROW(__sync_fetch_and_nand),
3093 
3094     BUILTIN_ROW(__sync_add_and_fetch),
3095     BUILTIN_ROW(__sync_sub_and_fetch),
3096     BUILTIN_ROW(__sync_and_and_fetch),
3097     BUILTIN_ROW(__sync_or_and_fetch),
3098     BUILTIN_ROW(__sync_xor_and_fetch),
3099     BUILTIN_ROW(__sync_nand_and_fetch),
3100 
3101     BUILTIN_ROW(__sync_val_compare_and_swap),
3102     BUILTIN_ROW(__sync_bool_compare_and_swap),
3103     BUILTIN_ROW(__sync_lock_test_and_set),
3104     BUILTIN_ROW(__sync_lock_release),
3105     BUILTIN_ROW(__sync_swap)
3106   };
3107 #undef BUILTIN_ROW
3108 
3109   // Determine the index of the size.
3110   unsigned SizeIndex;
3111   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3112   case 1: SizeIndex = 0; break;
3113   case 2: SizeIndex = 1; break;
3114   case 4: SizeIndex = 2; break;
3115   case 8: SizeIndex = 3; break;
3116   case 16: SizeIndex = 4; break;
3117   default:
3118     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3119       << FirstArg->getType() << FirstArg->getSourceRange();
3120     return ExprError();
3121   }
3122 
3123   // Each of these builtins has one pointer argument, followed by some number of
3124   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3125   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3126   // as the number of fixed args.
3127   unsigned BuiltinID = FDecl->getBuiltinID();
3128   unsigned BuiltinIndex, NumFixed = 1;
3129   bool WarnAboutSemanticsChange = false;
3130   switch (BuiltinID) {
3131   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3132   case Builtin::BI__sync_fetch_and_add:
3133   case Builtin::BI__sync_fetch_and_add_1:
3134   case Builtin::BI__sync_fetch_and_add_2:
3135   case Builtin::BI__sync_fetch_and_add_4:
3136   case Builtin::BI__sync_fetch_and_add_8:
3137   case Builtin::BI__sync_fetch_and_add_16:
3138     BuiltinIndex = 0;
3139     break;
3140 
3141   case Builtin::BI__sync_fetch_and_sub:
3142   case Builtin::BI__sync_fetch_and_sub_1:
3143   case Builtin::BI__sync_fetch_and_sub_2:
3144   case Builtin::BI__sync_fetch_and_sub_4:
3145   case Builtin::BI__sync_fetch_and_sub_8:
3146   case Builtin::BI__sync_fetch_and_sub_16:
3147     BuiltinIndex = 1;
3148     break;
3149 
3150   case Builtin::BI__sync_fetch_and_or:
3151   case Builtin::BI__sync_fetch_and_or_1:
3152   case Builtin::BI__sync_fetch_and_or_2:
3153   case Builtin::BI__sync_fetch_and_or_4:
3154   case Builtin::BI__sync_fetch_and_or_8:
3155   case Builtin::BI__sync_fetch_and_or_16:
3156     BuiltinIndex = 2;
3157     break;
3158 
3159   case Builtin::BI__sync_fetch_and_and:
3160   case Builtin::BI__sync_fetch_and_and_1:
3161   case Builtin::BI__sync_fetch_and_and_2:
3162   case Builtin::BI__sync_fetch_and_and_4:
3163   case Builtin::BI__sync_fetch_and_and_8:
3164   case Builtin::BI__sync_fetch_and_and_16:
3165     BuiltinIndex = 3;
3166     break;
3167 
3168   case Builtin::BI__sync_fetch_and_xor:
3169   case Builtin::BI__sync_fetch_and_xor_1:
3170   case Builtin::BI__sync_fetch_and_xor_2:
3171   case Builtin::BI__sync_fetch_and_xor_4:
3172   case Builtin::BI__sync_fetch_and_xor_8:
3173   case Builtin::BI__sync_fetch_and_xor_16:
3174     BuiltinIndex = 4;
3175     break;
3176 
3177   case Builtin::BI__sync_fetch_and_nand:
3178   case Builtin::BI__sync_fetch_and_nand_1:
3179   case Builtin::BI__sync_fetch_and_nand_2:
3180   case Builtin::BI__sync_fetch_and_nand_4:
3181   case Builtin::BI__sync_fetch_and_nand_8:
3182   case Builtin::BI__sync_fetch_and_nand_16:
3183     BuiltinIndex = 5;
3184     WarnAboutSemanticsChange = true;
3185     break;
3186 
3187   case Builtin::BI__sync_add_and_fetch:
3188   case Builtin::BI__sync_add_and_fetch_1:
3189   case Builtin::BI__sync_add_and_fetch_2:
3190   case Builtin::BI__sync_add_and_fetch_4:
3191   case Builtin::BI__sync_add_and_fetch_8:
3192   case Builtin::BI__sync_add_and_fetch_16:
3193     BuiltinIndex = 6;
3194     break;
3195 
3196   case Builtin::BI__sync_sub_and_fetch:
3197   case Builtin::BI__sync_sub_and_fetch_1:
3198   case Builtin::BI__sync_sub_and_fetch_2:
3199   case Builtin::BI__sync_sub_and_fetch_4:
3200   case Builtin::BI__sync_sub_and_fetch_8:
3201   case Builtin::BI__sync_sub_and_fetch_16:
3202     BuiltinIndex = 7;
3203     break;
3204 
3205   case Builtin::BI__sync_and_and_fetch:
3206   case Builtin::BI__sync_and_and_fetch_1:
3207   case Builtin::BI__sync_and_and_fetch_2:
3208   case Builtin::BI__sync_and_and_fetch_4:
3209   case Builtin::BI__sync_and_and_fetch_8:
3210   case Builtin::BI__sync_and_and_fetch_16:
3211     BuiltinIndex = 8;
3212     break;
3213 
3214   case Builtin::BI__sync_or_and_fetch:
3215   case Builtin::BI__sync_or_and_fetch_1:
3216   case Builtin::BI__sync_or_and_fetch_2:
3217   case Builtin::BI__sync_or_and_fetch_4:
3218   case Builtin::BI__sync_or_and_fetch_8:
3219   case Builtin::BI__sync_or_and_fetch_16:
3220     BuiltinIndex = 9;
3221     break;
3222 
3223   case Builtin::BI__sync_xor_and_fetch:
3224   case Builtin::BI__sync_xor_and_fetch_1:
3225   case Builtin::BI__sync_xor_and_fetch_2:
3226   case Builtin::BI__sync_xor_and_fetch_4:
3227   case Builtin::BI__sync_xor_and_fetch_8:
3228   case Builtin::BI__sync_xor_and_fetch_16:
3229     BuiltinIndex = 10;
3230     break;
3231 
3232   case Builtin::BI__sync_nand_and_fetch:
3233   case Builtin::BI__sync_nand_and_fetch_1:
3234   case Builtin::BI__sync_nand_and_fetch_2:
3235   case Builtin::BI__sync_nand_and_fetch_4:
3236   case Builtin::BI__sync_nand_and_fetch_8:
3237   case Builtin::BI__sync_nand_and_fetch_16:
3238     BuiltinIndex = 11;
3239     WarnAboutSemanticsChange = true;
3240     break;
3241 
3242   case Builtin::BI__sync_val_compare_and_swap:
3243   case Builtin::BI__sync_val_compare_and_swap_1:
3244   case Builtin::BI__sync_val_compare_and_swap_2:
3245   case Builtin::BI__sync_val_compare_and_swap_4:
3246   case Builtin::BI__sync_val_compare_and_swap_8:
3247   case Builtin::BI__sync_val_compare_and_swap_16:
3248     BuiltinIndex = 12;
3249     NumFixed = 2;
3250     break;
3251 
3252   case Builtin::BI__sync_bool_compare_and_swap:
3253   case Builtin::BI__sync_bool_compare_and_swap_1:
3254   case Builtin::BI__sync_bool_compare_and_swap_2:
3255   case Builtin::BI__sync_bool_compare_and_swap_4:
3256   case Builtin::BI__sync_bool_compare_and_swap_8:
3257   case Builtin::BI__sync_bool_compare_and_swap_16:
3258     BuiltinIndex = 13;
3259     NumFixed = 2;
3260     ResultType = Context.BoolTy;
3261     break;
3262 
3263   case Builtin::BI__sync_lock_test_and_set:
3264   case Builtin::BI__sync_lock_test_and_set_1:
3265   case Builtin::BI__sync_lock_test_and_set_2:
3266   case Builtin::BI__sync_lock_test_and_set_4:
3267   case Builtin::BI__sync_lock_test_and_set_8:
3268   case Builtin::BI__sync_lock_test_and_set_16:
3269     BuiltinIndex = 14;
3270     break;
3271 
3272   case Builtin::BI__sync_lock_release:
3273   case Builtin::BI__sync_lock_release_1:
3274   case Builtin::BI__sync_lock_release_2:
3275   case Builtin::BI__sync_lock_release_4:
3276   case Builtin::BI__sync_lock_release_8:
3277   case Builtin::BI__sync_lock_release_16:
3278     BuiltinIndex = 15;
3279     NumFixed = 0;
3280     ResultType = Context.VoidTy;
3281     break;
3282 
3283   case Builtin::BI__sync_swap:
3284   case Builtin::BI__sync_swap_1:
3285   case Builtin::BI__sync_swap_2:
3286   case Builtin::BI__sync_swap_4:
3287   case Builtin::BI__sync_swap_8:
3288   case Builtin::BI__sync_swap_16:
3289     BuiltinIndex = 16;
3290     break;
3291   }
3292 
3293   // Now that we know how many fixed arguments we expect, first check that we
3294   // have at least that many.
3295   if (TheCall->getNumArgs() < 1+NumFixed) {
3296     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3297       << 0 << 1+NumFixed << TheCall->getNumArgs()
3298       << TheCall->getCallee()->getSourceRange();
3299     return ExprError();
3300   }
3301 
3302   if (WarnAboutSemanticsChange) {
3303     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3304       << TheCall->getCallee()->getSourceRange();
3305   }
3306 
3307   // Get the decl for the concrete builtin from this, we can tell what the
3308   // concrete integer type we should convert to is.
3309   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3310   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3311   FunctionDecl *NewBuiltinDecl;
3312   if (NewBuiltinID == BuiltinID)
3313     NewBuiltinDecl = FDecl;
3314   else {
3315     // Perform builtin lookup to avoid redeclaring it.
3316     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3317     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3318     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3319     assert(Res.getFoundDecl());
3320     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3321     if (!NewBuiltinDecl)
3322       return ExprError();
3323   }
3324 
3325   // The first argument --- the pointer --- has a fixed type; we
3326   // deduce the types of the rest of the arguments accordingly.  Walk
3327   // the remaining arguments, converting them to the deduced value type.
3328   for (unsigned i = 0; i != NumFixed; ++i) {
3329     ExprResult Arg = TheCall->getArg(i+1);
3330 
3331     // GCC does an implicit conversion to the pointer or integer ValType.  This
3332     // can fail in some cases (1i -> int**), check for this error case now.
3333     // Initialize the argument.
3334     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3335                                                    ValType, /*consume*/ false);
3336     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3337     if (Arg.isInvalid())
3338       return ExprError();
3339 
3340     // Okay, we have something that *can* be converted to the right type.  Check
3341     // to see if there is a potentially weird extension going on here.  This can
3342     // happen when you do an atomic operation on something like an char* and
3343     // pass in 42.  The 42 gets converted to char.  This is even more strange
3344     // for things like 45.123 -> char, etc.
3345     // FIXME: Do this check.
3346     TheCall->setArg(i+1, Arg.get());
3347   }
3348 
3349   ASTContext& Context = this->getASTContext();
3350 
3351   // Create a new DeclRefExpr to refer to the new decl.
3352   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3353       Context,
3354       DRE->getQualifierLoc(),
3355       SourceLocation(),
3356       NewBuiltinDecl,
3357       /*enclosing*/ false,
3358       DRE->getLocation(),
3359       Context.BuiltinFnTy,
3360       DRE->getValueKind());
3361 
3362   // Set the callee in the CallExpr.
3363   // FIXME: This loses syntactic information.
3364   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3365   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3366                                               CK_BuiltinFnToFnPtr);
3367   TheCall->setCallee(PromotedCall.get());
3368 
3369   // Change the result type of the call to match the original value type. This
3370   // is arbitrary, but the codegen for these builtins ins design to handle it
3371   // gracefully.
3372   TheCall->setType(ResultType);
3373 
3374   return TheCallResult;
3375 }
3376 
3377 /// SemaBuiltinNontemporalOverloaded - We have a call to
3378 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3379 /// overloaded function based on the pointer type of its last argument.
3380 ///
3381 /// This function goes through and does final semantic checking for these
3382 /// builtins.
3383 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3384   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3385   DeclRefExpr *DRE =
3386       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3387   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3388   unsigned BuiltinID = FDecl->getBuiltinID();
3389   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3390           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3391          "Unexpected nontemporal load/store builtin!");
3392   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3393   unsigned numArgs = isStore ? 2 : 1;
3394 
3395   // Ensure that we have the proper number of arguments.
3396   if (checkArgCount(*this, TheCall, numArgs))
3397     return ExprError();
3398 
3399   // Inspect the last argument of the nontemporal builtin.  This should always
3400   // be a pointer type, from which we imply the type of the memory access.
3401   // Because it is a pointer type, we don't have to worry about any implicit
3402   // casts here.
3403   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3404   ExprResult PointerArgResult =
3405       DefaultFunctionArrayLvalueConversion(PointerArg);
3406 
3407   if (PointerArgResult.isInvalid())
3408     return ExprError();
3409   PointerArg = PointerArgResult.get();
3410   TheCall->setArg(numArgs - 1, PointerArg);
3411 
3412   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3413   if (!pointerType) {
3414     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3415         << PointerArg->getType() << PointerArg->getSourceRange();
3416     return ExprError();
3417   }
3418 
3419   QualType ValType = pointerType->getPointeeType();
3420 
3421   // Strip any qualifiers off ValType.
3422   ValType = ValType.getUnqualifiedType();
3423   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3424       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3425       !ValType->isVectorType()) {
3426     Diag(DRE->getLocStart(),
3427          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3428         << PointerArg->getType() << PointerArg->getSourceRange();
3429     return ExprError();
3430   }
3431 
3432   if (!isStore) {
3433     TheCall->setType(ValType);
3434     return TheCallResult;
3435   }
3436 
3437   ExprResult ValArg = TheCall->getArg(0);
3438   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3439       Context, ValType, /*consume*/ false);
3440   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3441   if (ValArg.isInvalid())
3442     return ExprError();
3443 
3444   TheCall->setArg(0, ValArg.get());
3445   TheCall->setType(Context.VoidTy);
3446   return TheCallResult;
3447 }
3448 
3449 /// CheckObjCString - Checks that the argument to the builtin
3450 /// CFString constructor is correct
3451 /// Note: It might also make sense to do the UTF-16 conversion here (would
3452 /// simplify the backend).
3453 bool Sema::CheckObjCString(Expr *Arg) {
3454   Arg = Arg->IgnoreParenCasts();
3455   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3456 
3457   if (!Literal || !Literal->isAscii()) {
3458     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3459       << Arg->getSourceRange();
3460     return true;
3461   }
3462 
3463   if (Literal->containsNonAsciiOrNull()) {
3464     StringRef String = Literal->getString();
3465     unsigned NumBytes = String.size();
3466     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3467     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3468     llvm::UTF16 *ToPtr = &ToBuf[0];
3469 
3470     llvm::ConversionResult Result =
3471         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3472                                  ToPtr + NumBytes, llvm::strictConversion);
3473     // Check for conversion failure.
3474     if (Result != llvm::conversionOK)
3475       Diag(Arg->getLocStart(),
3476            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3477   }
3478   return false;
3479 }
3480 
3481 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3482 /// for validity.  Emit an error and return true on failure; return false
3483 /// on success.
3484 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3485   Expr *Fn = TheCall->getCallee();
3486   if (TheCall->getNumArgs() > 2) {
3487     Diag(TheCall->getArg(2)->getLocStart(),
3488          diag::err_typecheck_call_too_many_args)
3489       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3490       << Fn->getSourceRange()
3491       << SourceRange(TheCall->getArg(2)->getLocStart(),
3492                      (*(TheCall->arg_end()-1))->getLocEnd());
3493     return true;
3494   }
3495 
3496   if (TheCall->getNumArgs() < 2) {
3497     return Diag(TheCall->getLocEnd(),
3498       diag::err_typecheck_call_too_few_args_at_least)
3499       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3500   }
3501 
3502   // Type-check the first argument normally.
3503   if (checkBuiltinArgument(*this, TheCall, 0))
3504     return true;
3505 
3506   // Determine whether the current function is variadic or not.
3507   BlockScopeInfo *CurBlock = getCurBlock();
3508   bool isVariadic;
3509   if (CurBlock)
3510     isVariadic = CurBlock->TheDecl->isVariadic();
3511   else if (FunctionDecl *FD = getCurFunctionDecl())
3512     isVariadic = FD->isVariadic();
3513   else
3514     isVariadic = getCurMethodDecl()->isVariadic();
3515 
3516   if (!isVariadic) {
3517     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3518     return true;
3519   }
3520 
3521   // Verify that the second argument to the builtin is the last argument of the
3522   // current function or method.
3523   bool SecondArgIsLastNamedArgument = false;
3524   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3525 
3526   // These are valid if SecondArgIsLastNamedArgument is false after the next
3527   // block.
3528   QualType Type;
3529   SourceLocation ParamLoc;
3530   bool IsCRegister = false;
3531 
3532   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3533     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3534       // FIXME: This isn't correct for methods (results in bogus warning).
3535       // Get the last formal in the current function.
3536       const ParmVarDecl *LastArg;
3537       if (CurBlock)
3538         LastArg = CurBlock->TheDecl->parameters().back();
3539       else if (FunctionDecl *FD = getCurFunctionDecl())
3540         LastArg = FD->parameters().back();
3541       else
3542         LastArg = getCurMethodDecl()->parameters().back();
3543       SecondArgIsLastNamedArgument = PV == LastArg;
3544 
3545       Type = PV->getType();
3546       ParamLoc = PV->getLocation();
3547       IsCRegister =
3548           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3549     }
3550   }
3551 
3552   if (!SecondArgIsLastNamedArgument)
3553     Diag(TheCall->getArg(1)->getLocStart(),
3554          diag::warn_second_arg_of_va_start_not_last_named_param);
3555   else if (IsCRegister || Type->isReferenceType() ||
3556            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3557              // Promotable integers are UB, but enumerations need a bit of
3558              // extra checking to see what their promotable type actually is.
3559              if (!Type->isPromotableIntegerType())
3560                return false;
3561              if (!Type->isEnumeralType())
3562                return true;
3563              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3564              return !(ED &&
3565                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3566            }()) {
3567     unsigned Reason = 0;
3568     if (Type->isReferenceType())  Reason = 1;
3569     else if (IsCRegister)         Reason = 2;
3570     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3571     Diag(ParamLoc, diag::note_parameter_type) << Type;
3572   }
3573 
3574   TheCall->setType(Context.VoidTy);
3575   return false;
3576 }
3577 
3578 /// Check the arguments to '__builtin_va_start' for validity, and that
3579 /// it was called from a function of the native ABI.
3580 /// Emit an error and return true on failure; return false on success.
3581 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3582   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3583   // On x64 Windows, don't allow this in System V ABI functions.
3584   // (Yes, that means there's no corresponding way to support variadic
3585   // System V ABI functions on Windows.)
3586   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3587     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3588     clang::CallingConv CC = CC_C;
3589     if (const FunctionDecl *FD = getCurFunctionDecl())
3590       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3591     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3592         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3593       return Diag(TheCall->getCallee()->getLocStart(),
3594                   diag::err_va_start_used_in_wrong_abi_function)
3595              << (OS != llvm::Triple::Win32);
3596   }
3597   return SemaBuiltinVAStartImpl(TheCall);
3598 }
3599 
3600 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3601 /// it was called from a Win64 ABI function.
3602 /// Emit an error and return true on failure; return false on success.
3603 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3604   // This only makes sense for x86-64.
3605   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3606   Expr *Callee = TheCall->getCallee();
3607   if (TT.getArch() != llvm::Triple::x86_64)
3608     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3609   // Don't allow this in System V ABI functions.
3610   clang::CallingConv CC = CC_C;
3611   if (const FunctionDecl *FD = getCurFunctionDecl())
3612     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3613   if (CC == CC_X86_64SysV ||
3614       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3615     return Diag(Callee->getLocStart(),
3616                 diag::err_ms_va_start_used_in_sysv_function);
3617   return SemaBuiltinVAStartImpl(TheCall);
3618 }
3619 
3620 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3621   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3622   //                 const char *named_addr);
3623 
3624   Expr *Func = Call->getCallee();
3625 
3626   if (Call->getNumArgs() < 3)
3627     return Diag(Call->getLocEnd(),
3628                 diag::err_typecheck_call_too_few_args_at_least)
3629            << 0 /*function call*/ << 3 << Call->getNumArgs();
3630 
3631   // Determine whether the current function is variadic or not.
3632   bool IsVariadic;
3633   if (BlockScopeInfo *CurBlock = getCurBlock())
3634     IsVariadic = CurBlock->TheDecl->isVariadic();
3635   else if (FunctionDecl *FD = getCurFunctionDecl())
3636     IsVariadic = FD->isVariadic();
3637   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3638     IsVariadic = MD->isVariadic();
3639   else
3640     llvm_unreachable("unexpected statement type");
3641 
3642   if (!IsVariadic) {
3643     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3644     return true;
3645   }
3646 
3647   // Type-check the first argument normally.
3648   if (checkBuiltinArgument(*this, Call, 0))
3649     return true;
3650 
3651   const struct {
3652     unsigned ArgNo;
3653     QualType Type;
3654   } ArgumentTypes[] = {
3655     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3656     { 2, Context.getSizeType() },
3657   };
3658 
3659   for (const auto &AT : ArgumentTypes) {
3660     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3661     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3662       continue;
3663     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3664       << Arg->getType() << AT.Type << 1 /* different class */
3665       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3666       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3667   }
3668 
3669   return false;
3670 }
3671 
3672 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3673 /// friends.  This is declared to take (...), so we have to check everything.
3674 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3675   if (TheCall->getNumArgs() < 2)
3676     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3677       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3678   if (TheCall->getNumArgs() > 2)
3679     return Diag(TheCall->getArg(2)->getLocStart(),
3680                 diag::err_typecheck_call_too_many_args)
3681       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3682       << SourceRange(TheCall->getArg(2)->getLocStart(),
3683                      (*(TheCall->arg_end()-1))->getLocEnd());
3684 
3685   ExprResult OrigArg0 = TheCall->getArg(0);
3686   ExprResult OrigArg1 = TheCall->getArg(1);
3687 
3688   // Do standard promotions between the two arguments, returning their common
3689   // type.
3690   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3691   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3692     return true;
3693 
3694   // Make sure any conversions are pushed back into the call; this is
3695   // type safe since unordered compare builtins are declared as "_Bool
3696   // foo(...)".
3697   TheCall->setArg(0, OrigArg0.get());
3698   TheCall->setArg(1, OrigArg1.get());
3699 
3700   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3701     return false;
3702 
3703   // If the common type isn't a real floating type, then the arguments were
3704   // invalid for this operation.
3705   if (Res.isNull() || !Res->isRealFloatingType())
3706     return Diag(OrigArg0.get()->getLocStart(),
3707                 diag::err_typecheck_call_invalid_ordered_compare)
3708       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3709       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3710 
3711   return false;
3712 }
3713 
3714 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3715 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3716 /// to check everything. We expect the last argument to be a floating point
3717 /// value.
3718 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3719   if (TheCall->getNumArgs() < NumArgs)
3720     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3721       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3722   if (TheCall->getNumArgs() > NumArgs)
3723     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3724                 diag::err_typecheck_call_too_many_args)
3725       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3726       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3727                      (*(TheCall->arg_end()-1))->getLocEnd());
3728 
3729   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3730 
3731   if (OrigArg->isTypeDependent())
3732     return false;
3733 
3734   // This operation requires a non-_Complex floating-point number.
3735   if (!OrigArg->getType()->isRealFloatingType())
3736     return Diag(OrigArg->getLocStart(),
3737                 diag::err_typecheck_call_invalid_unary_fp)
3738       << OrigArg->getType() << OrigArg->getSourceRange();
3739 
3740   // If this is an implicit conversion from float -> double, remove it.
3741   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3742     Expr *CastArg = Cast->getSubExpr();
3743     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3744       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3745              "promotion from float to double is the only expected cast here");
3746       Cast->setSubExpr(nullptr);
3747       TheCall->setArg(NumArgs-1, CastArg);
3748     }
3749   }
3750 
3751   return false;
3752 }
3753 
3754 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3755 // This is declared to take (...), so we have to check everything.
3756 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3757   if (TheCall->getNumArgs() < 2)
3758     return ExprError(Diag(TheCall->getLocEnd(),
3759                           diag::err_typecheck_call_too_few_args_at_least)
3760                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3761                      << TheCall->getSourceRange());
3762 
3763   // Determine which of the following types of shufflevector we're checking:
3764   // 1) unary, vector mask: (lhs, mask)
3765   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3766   QualType resType = TheCall->getArg(0)->getType();
3767   unsigned numElements = 0;
3768 
3769   if (!TheCall->getArg(0)->isTypeDependent() &&
3770       !TheCall->getArg(1)->isTypeDependent()) {
3771     QualType LHSType = TheCall->getArg(0)->getType();
3772     QualType RHSType = TheCall->getArg(1)->getType();
3773 
3774     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3775       return ExprError(Diag(TheCall->getLocStart(),
3776                             diag::err_shufflevector_non_vector)
3777                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3778                                       TheCall->getArg(1)->getLocEnd()));
3779 
3780     numElements = LHSType->getAs<VectorType>()->getNumElements();
3781     unsigned numResElements = TheCall->getNumArgs() - 2;
3782 
3783     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3784     // with mask.  If so, verify that RHS is an integer vector type with the
3785     // same number of elts as lhs.
3786     if (TheCall->getNumArgs() == 2) {
3787       if (!RHSType->hasIntegerRepresentation() ||
3788           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3789         return ExprError(Diag(TheCall->getLocStart(),
3790                               diag::err_shufflevector_incompatible_vector)
3791                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3792                                         TheCall->getArg(1)->getLocEnd()));
3793     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3794       return ExprError(Diag(TheCall->getLocStart(),
3795                             diag::err_shufflevector_incompatible_vector)
3796                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3797                                       TheCall->getArg(1)->getLocEnd()));
3798     } else if (numElements != numResElements) {
3799       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3800       resType = Context.getVectorType(eltType, numResElements,
3801                                       VectorType::GenericVector);
3802     }
3803   }
3804 
3805   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3806     if (TheCall->getArg(i)->isTypeDependent() ||
3807         TheCall->getArg(i)->isValueDependent())
3808       continue;
3809 
3810     llvm::APSInt Result(32);
3811     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3812       return ExprError(Diag(TheCall->getLocStart(),
3813                             diag::err_shufflevector_nonconstant_argument)
3814                        << TheCall->getArg(i)->getSourceRange());
3815 
3816     // Allow -1 which will be translated to undef in the IR.
3817     if (Result.isSigned() && Result.isAllOnesValue())
3818       continue;
3819 
3820     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3821       return ExprError(Diag(TheCall->getLocStart(),
3822                             diag::err_shufflevector_argument_too_large)
3823                        << TheCall->getArg(i)->getSourceRange());
3824   }
3825 
3826   SmallVector<Expr*, 32> exprs;
3827 
3828   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3829     exprs.push_back(TheCall->getArg(i));
3830     TheCall->setArg(i, nullptr);
3831   }
3832 
3833   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3834                                          TheCall->getCallee()->getLocStart(),
3835                                          TheCall->getRParenLoc());
3836 }
3837 
3838 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3839 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3840                                        SourceLocation BuiltinLoc,
3841                                        SourceLocation RParenLoc) {
3842   ExprValueKind VK = VK_RValue;
3843   ExprObjectKind OK = OK_Ordinary;
3844   QualType DstTy = TInfo->getType();
3845   QualType SrcTy = E->getType();
3846 
3847   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3848     return ExprError(Diag(BuiltinLoc,
3849                           diag::err_convertvector_non_vector)
3850                      << E->getSourceRange());
3851   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3852     return ExprError(Diag(BuiltinLoc,
3853                           diag::err_convertvector_non_vector_type));
3854 
3855   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3856     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3857     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3858     if (SrcElts != DstElts)
3859       return ExprError(Diag(BuiltinLoc,
3860                             diag::err_convertvector_incompatible_vector)
3861                        << E->getSourceRange());
3862   }
3863 
3864   return new (Context)
3865       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3866 }
3867 
3868 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3869 // This is declared to take (const void*, ...) and can take two
3870 // optional constant int args.
3871 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3872   unsigned NumArgs = TheCall->getNumArgs();
3873 
3874   if (NumArgs > 3)
3875     return Diag(TheCall->getLocEnd(),
3876              diag::err_typecheck_call_too_many_args_at_most)
3877              << 0 /*function call*/ << 3 << NumArgs
3878              << TheCall->getSourceRange();
3879 
3880   // Argument 0 is checked for us and the remaining arguments must be
3881   // constant integers.
3882   for (unsigned i = 1; i != NumArgs; ++i)
3883     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3884       return true;
3885 
3886   return false;
3887 }
3888 
3889 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3890 // __assume does not evaluate its arguments, and should warn if its argument
3891 // has side effects.
3892 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3893   Expr *Arg = TheCall->getArg(0);
3894   if (Arg->isInstantiationDependent()) return false;
3895 
3896   if (Arg->HasSideEffects(Context))
3897     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3898       << Arg->getSourceRange()
3899       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3900 
3901   return false;
3902 }
3903 
3904 /// Handle __builtin_assume_aligned. This is declared
3905 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3906 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3907   unsigned NumArgs = TheCall->getNumArgs();
3908 
3909   if (NumArgs > 3)
3910     return Diag(TheCall->getLocEnd(),
3911              diag::err_typecheck_call_too_many_args_at_most)
3912              << 0 /*function call*/ << 3 << NumArgs
3913              << TheCall->getSourceRange();
3914 
3915   // The alignment must be a constant integer.
3916   Expr *Arg = TheCall->getArg(1);
3917 
3918   // We can't check the value of a dependent argument.
3919   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3920     llvm::APSInt Result;
3921     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3922       return true;
3923 
3924     if (!Result.isPowerOf2())
3925       return Diag(TheCall->getLocStart(),
3926                   diag::err_alignment_not_power_of_two)
3927            << Arg->getSourceRange();
3928   }
3929 
3930   if (NumArgs > 2) {
3931     ExprResult Arg(TheCall->getArg(2));
3932     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3933       Context.getSizeType(), false);
3934     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3935     if (Arg.isInvalid()) return true;
3936     TheCall->setArg(2, Arg.get());
3937   }
3938 
3939   return false;
3940 }
3941 
3942 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3943 /// TheCall is a constant expression.
3944 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3945                                   llvm::APSInt &Result) {
3946   Expr *Arg = TheCall->getArg(ArgNum);
3947   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3948   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3949 
3950   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3951 
3952   if (!Arg->isIntegerConstantExpr(Result, Context))
3953     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
3954                 << FDecl->getDeclName() <<  Arg->getSourceRange();
3955 
3956   return false;
3957 }
3958 
3959 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3960 /// TheCall is a constant expression in the range [Low, High].
3961 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3962                                        int Low, int High) {
3963   llvm::APSInt Result;
3964 
3965   // We can't check the value of a dependent argument.
3966   Expr *Arg = TheCall->getArg(ArgNum);
3967   if (Arg->isTypeDependent() || Arg->isValueDependent())
3968     return false;
3969 
3970   // Check constant-ness first.
3971   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3972     return true;
3973 
3974   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
3975     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
3976       << Low << High << Arg->getSourceRange();
3977 
3978   return false;
3979 }
3980 
3981 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
3982 /// TheCall is a constant expression is a multiple of Num..
3983 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
3984                                           unsigned Num) {
3985   llvm::APSInt Result;
3986 
3987   // We can't check the value of a dependent argument.
3988   Expr *Arg = TheCall->getArg(ArgNum);
3989   if (Arg->isTypeDependent() || Arg->isValueDependent())
3990     return false;
3991 
3992   // Check constant-ness first.
3993   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3994     return true;
3995 
3996   if (Result.getSExtValue() % Num != 0)
3997     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
3998       << Num << Arg->getSourceRange();
3999 
4000   return false;
4001 }
4002 
4003 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4004 /// TheCall is an ARM/AArch64 special register string literal.
4005 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4006                                     int ArgNum, unsigned ExpectedFieldNum,
4007                                     bool AllowName) {
4008   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4009                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4010                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4011                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4012                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4013                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4014   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4015                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4016                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4017                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4018                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4019                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4020   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4021 
4022   // We can't check the value of a dependent argument.
4023   Expr *Arg = TheCall->getArg(ArgNum);
4024   if (Arg->isTypeDependent() || Arg->isValueDependent())
4025     return false;
4026 
4027   // Check if the argument is a string literal.
4028   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4029     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4030            << Arg->getSourceRange();
4031 
4032   // Check the type of special register given.
4033   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4034   SmallVector<StringRef, 6> Fields;
4035   Reg.split(Fields, ":");
4036 
4037   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4038     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4039            << Arg->getSourceRange();
4040 
4041   // If the string is the name of a register then we cannot check that it is
4042   // valid here but if the string is of one the forms described in ACLE then we
4043   // can check that the supplied fields are integers and within the valid
4044   // ranges.
4045   if (Fields.size() > 1) {
4046     bool FiveFields = Fields.size() == 5;
4047 
4048     bool ValidString = true;
4049     if (IsARMBuiltin) {
4050       ValidString &= Fields[0].startswith_lower("cp") ||
4051                      Fields[0].startswith_lower("p");
4052       if (ValidString)
4053         Fields[0] =
4054           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4055 
4056       ValidString &= Fields[2].startswith_lower("c");
4057       if (ValidString)
4058         Fields[2] = Fields[2].drop_front(1);
4059 
4060       if (FiveFields) {
4061         ValidString &= Fields[3].startswith_lower("c");
4062         if (ValidString)
4063           Fields[3] = Fields[3].drop_front(1);
4064       }
4065     }
4066 
4067     SmallVector<int, 5> Ranges;
4068     if (FiveFields)
4069       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
4070     else
4071       Ranges.append({15, 7, 15});
4072 
4073     for (unsigned i=0; i<Fields.size(); ++i) {
4074       int IntField;
4075       ValidString &= !Fields[i].getAsInteger(10, IntField);
4076       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4077     }
4078 
4079     if (!ValidString)
4080       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4081              << Arg->getSourceRange();
4082 
4083   } else if (IsAArch64Builtin && Fields.size() == 1) {
4084     // If the register name is one of those that appear in the condition below
4085     // and the special register builtin being used is one of the write builtins,
4086     // then we require that the argument provided for writing to the register
4087     // is an integer constant expression. This is because it will be lowered to
4088     // an MSR (immediate) instruction, so we need to know the immediate at
4089     // compile time.
4090     if (TheCall->getNumArgs() != 2)
4091       return false;
4092 
4093     std::string RegLower = Reg.lower();
4094     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4095         RegLower != "pan" && RegLower != "uao")
4096       return false;
4097 
4098     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4099   }
4100 
4101   return false;
4102 }
4103 
4104 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4105 /// This checks that the target supports __builtin_longjmp and
4106 /// that val is a constant 1.
4107 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4108   if (!Context.getTargetInfo().hasSjLjLowering())
4109     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4110              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4111 
4112   Expr *Arg = TheCall->getArg(1);
4113   llvm::APSInt Result;
4114 
4115   // TODO: This is less than ideal. Overload this to take a value.
4116   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4117     return true;
4118 
4119   if (Result != 1)
4120     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4121              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4122 
4123   return false;
4124 }
4125 
4126 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4127 /// This checks that the target supports __builtin_setjmp.
4128 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4129   if (!Context.getTargetInfo().hasSjLjLowering())
4130     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4131              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4132   return false;
4133 }
4134 
4135 namespace {
4136 class UncoveredArgHandler {
4137   enum { Unknown = -1, AllCovered = -2 };
4138   signed FirstUncoveredArg;
4139   SmallVector<const Expr *, 4> DiagnosticExprs;
4140 
4141 public:
4142   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4143 
4144   bool hasUncoveredArg() const {
4145     return (FirstUncoveredArg >= 0);
4146   }
4147 
4148   unsigned getUncoveredArg() const {
4149     assert(hasUncoveredArg() && "no uncovered argument");
4150     return FirstUncoveredArg;
4151   }
4152 
4153   void setAllCovered() {
4154     // A string has been found with all arguments covered, so clear out
4155     // the diagnostics.
4156     DiagnosticExprs.clear();
4157     FirstUncoveredArg = AllCovered;
4158   }
4159 
4160   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4161     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4162 
4163     // Don't update if a previous string covers all arguments.
4164     if (FirstUncoveredArg == AllCovered)
4165       return;
4166 
4167     // UncoveredArgHandler tracks the highest uncovered argument index
4168     // and with it all the strings that match this index.
4169     if (NewFirstUncoveredArg == FirstUncoveredArg)
4170       DiagnosticExprs.push_back(StrExpr);
4171     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4172       DiagnosticExprs.clear();
4173       DiagnosticExprs.push_back(StrExpr);
4174       FirstUncoveredArg = NewFirstUncoveredArg;
4175     }
4176   }
4177 
4178   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4179 };
4180 
4181 enum StringLiteralCheckType {
4182   SLCT_NotALiteral,
4183   SLCT_UncheckedLiteral,
4184   SLCT_CheckedLiteral
4185 };
4186 } // end anonymous namespace
4187 
4188 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4189                                      BinaryOperatorKind BinOpKind,
4190                                      bool AddendIsRight) {
4191   unsigned BitWidth = Offset.getBitWidth();
4192   unsigned AddendBitWidth = Addend.getBitWidth();
4193   // There might be negative interim results.
4194   if (Addend.isUnsigned()) {
4195     Addend = Addend.zext(++AddendBitWidth);
4196     Addend.setIsSigned(true);
4197   }
4198   // Adjust the bit width of the APSInts.
4199   if (AddendBitWidth > BitWidth) {
4200     Offset = Offset.sext(AddendBitWidth);
4201     BitWidth = AddendBitWidth;
4202   } else if (BitWidth > AddendBitWidth) {
4203     Addend = Addend.sext(BitWidth);
4204   }
4205 
4206   bool Ov = false;
4207   llvm::APSInt ResOffset = Offset;
4208   if (BinOpKind == BO_Add)
4209     ResOffset = Offset.sadd_ov(Addend, Ov);
4210   else {
4211     assert(AddendIsRight && BinOpKind == BO_Sub &&
4212            "operator must be add or sub with addend on the right");
4213     ResOffset = Offset.ssub_ov(Addend, Ov);
4214   }
4215 
4216   // We add an offset to a pointer here so we should support an offset as big as
4217   // possible.
4218   if (Ov) {
4219     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4220     Offset = Offset.sext(2 * BitWidth);
4221     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4222     return;
4223   }
4224 
4225   Offset = ResOffset;
4226 }
4227 
4228 namespace {
4229 // This is a wrapper class around StringLiteral to support offsetted string
4230 // literals as format strings. It takes the offset into account when returning
4231 // the string and its length or the source locations to display notes correctly.
4232 class FormatStringLiteral {
4233   const StringLiteral *FExpr;
4234   int64_t Offset;
4235 
4236  public:
4237   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4238       : FExpr(fexpr), Offset(Offset) {}
4239 
4240   StringRef getString() const {
4241     return FExpr->getString().drop_front(Offset);
4242   }
4243 
4244   unsigned getByteLength() const {
4245     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4246   }
4247   unsigned getLength() const { return FExpr->getLength() - Offset; }
4248   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4249 
4250   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4251 
4252   QualType getType() const { return FExpr->getType(); }
4253 
4254   bool isAscii() const { return FExpr->isAscii(); }
4255   bool isWide() const { return FExpr->isWide(); }
4256   bool isUTF8() const { return FExpr->isUTF8(); }
4257   bool isUTF16() const { return FExpr->isUTF16(); }
4258   bool isUTF32() const { return FExpr->isUTF32(); }
4259   bool isPascal() const { return FExpr->isPascal(); }
4260 
4261   SourceLocation getLocationOfByte(
4262       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4263       const TargetInfo &Target, unsigned *StartToken = nullptr,
4264       unsigned *StartTokenByteOffset = nullptr) const {
4265     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4266                                     StartToken, StartTokenByteOffset);
4267   }
4268 
4269   SourceLocation getLocStart() const LLVM_READONLY {
4270     return FExpr->getLocStart().getLocWithOffset(Offset);
4271   }
4272   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4273 };
4274 }  // end anonymous namespace
4275 
4276 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4277                               const Expr *OrigFormatExpr,
4278                               ArrayRef<const Expr *> Args,
4279                               bool HasVAListArg, unsigned format_idx,
4280                               unsigned firstDataArg,
4281                               Sema::FormatStringType Type,
4282                               bool inFunctionCall,
4283                               Sema::VariadicCallType CallType,
4284                               llvm::SmallBitVector &CheckedVarArgs,
4285                               UncoveredArgHandler &UncoveredArg);
4286 
4287 // Determine if an expression is a string literal or constant string.
4288 // If this function returns false on the arguments to a function expecting a
4289 // format string, we will usually need to emit a warning.
4290 // True string literals are then checked by CheckFormatString.
4291 static StringLiteralCheckType
4292 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4293                       bool HasVAListArg, unsigned format_idx,
4294                       unsigned firstDataArg, Sema::FormatStringType Type,
4295                       Sema::VariadicCallType CallType, bool InFunctionCall,
4296                       llvm::SmallBitVector &CheckedVarArgs,
4297                       UncoveredArgHandler &UncoveredArg,
4298                       llvm::APSInt Offset) {
4299  tryAgain:
4300   assert(Offset.isSigned() && "invalid offset");
4301 
4302   if (E->isTypeDependent() || E->isValueDependent())
4303     return SLCT_NotALiteral;
4304 
4305   E = E->IgnoreParenCasts();
4306 
4307   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4308     // Technically -Wformat-nonliteral does not warn about this case.
4309     // The behavior of printf and friends in this case is implementation
4310     // dependent.  Ideally if the format string cannot be null then
4311     // it should have a 'nonnull' attribute in the function prototype.
4312     return SLCT_UncheckedLiteral;
4313 
4314   switch (E->getStmtClass()) {
4315   case Stmt::BinaryConditionalOperatorClass:
4316   case Stmt::ConditionalOperatorClass: {
4317     // The expression is a literal if both sub-expressions were, and it was
4318     // completely checked only if both sub-expressions were checked.
4319     const AbstractConditionalOperator *C =
4320         cast<AbstractConditionalOperator>(E);
4321 
4322     // Determine whether it is necessary to check both sub-expressions, for
4323     // example, because the condition expression is a constant that can be
4324     // evaluated at compile time.
4325     bool CheckLeft = true, CheckRight = true;
4326 
4327     bool Cond;
4328     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4329       if (Cond)
4330         CheckRight = false;
4331       else
4332         CheckLeft = false;
4333     }
4334 
4335     // We need to maintain the offsets for the right and the left hand side
4336     // separately to check if every possible indexed expression is a valid
4337     // string literal. They might have different offsets for different string
4338     // literals in the end.
4339     StringLiteralCheckType Left;
4340     if (!CheckLeft)
4341       Left = SLCT_UncheckedLiteral;
4342     else {
4343       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4344                                    HasVAListArg, format_idx, firstDataArg,
4345                                    Type, CallType, InFunctionCall,
4346                                    CheckedVarArgs, UncoveredArg, Offset);
4347       if (Left == SLCT_NotALiteral || !CheckRight) {
4348         return Left;
4349       }
4350     }
4351 
4352     StringLiteralCheckType Right =
4353         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4354                               HasVAListArg, format_idx, firstDataArg,
4355                               Type, CallType, InFunctionCall, CheckedVarArgs,
4356                               UncoveredArg, Offset);
4357 
4358     return (CheckLeft && Left < Right) ? Left : Right;
4359   }
4360 
4361   case Stmt::ImplicitCastExprClass: {
4362     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4363     goto tryAgain;
4364   }
4365 
4366   case Stmt::OpaqueValueExprClass:
4367     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4368       E = src;
4369       goto tryAgain;
4370     }
4371     return SLCT_NotALiteral;
4372 
4373   case Stmt::PredefinedExprClass:
4374     // While __func__, etc., are technically not string literals, they
4375     // cannot contain format specifiers and thus are not a security
4376     // liability.
4377     return SLCT_UncheckedLiteral;
4378 
4379   case Stmt::DeclRefExprClass: {
4380     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4381 
4382     // As an exception, do not flag errors for variables binding to
4383     // const string literals.
4384     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4385       bool isConstant = false;
4386       QualType T = DR->getType();
4387 
4388       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4389         isConstant = AT->getElementType().isConstant(S.Context);
4390       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4391         isConstant = T.isConstant(S.Context) &&
4392                      PT->getPointeeType().isConstant(S.Context);
4393       } else if (T->isObjCObjectPointerType()) {
4394         // In ObjC, there is usually no "const ObjectPointer" type,
4395         // so don't check if the pointee type is constant.
4396         isConstant = T.isConstant(S.Context);
4397       }
4398 
4399       if (isConstant) {
4400         if (const Expr *Init = VD->getAnyInitializer()) {
4401           // Look through initializers like const char c[] = { "foo" }
4402           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4403             if (InitList->isStringLiteralInit())
4404               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4405           }
4406           return checkFormatStringExpr(S, Init, Args,
4407                                        HasVAListArg, format_idx,
4408                                        firstDataArg, Type, CallType,
4409                                        /*InFunctionCall*/ false, CheckedVarArgs,
4410                                        UncoveredArg, Offset);
4411         }
4412       }
4413 
4414       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4415       // special check to see if the format string is a function parameter
4416       // of the function calling the printf function.  If the function
4417       // has an attribute indicating it is a printf-like function, then we
4418       // should suppress warnings concerning non-literals being used in a call
4419       // to a vprintf function.  For example:
4420       //
4421       // void
4422       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4423       //      va_list ap;
4424       //      va_start(ap, fmt);
4425       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4426       //      ...
4427       // }
4428       if (HasVAListArg) {
4429         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4430           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4431             int PVIndex = PV->getFunctionScopeIndex() + 1;
4432             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4433               // adjust for implicit parameter
4434               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4435                 if (MD->isInstance())
4436                   ++PVIndex;
4437               // We also check if the formats are compatible.
4438               // We can't pass a 'scanf' string to a 'printf' function.
4439               if (PVIndex == PVFormat->getFormatIdx() &&
4440                   Type == S.GetFormatStringType(PVFormat))
4441                 return SLCT_UncheckedLiteral;
4442             }
4443           }
4444         }
4445       }
4446     }
4447 
4448     return SLCT_NotALiteral;
4449   }
4450 
4451   case Stmt::CallExprClass:
4452   case Stmt::CXXMemberCallExprClass: {
4453     const CallExpr *CE = cast<CallExpr>(E);
4454     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4455       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4456         unsigned ArgIndex = FA->getFormatIdx();
4457         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4458           if (MD->isInstance())
4459             --ArgIndex;
4460         const Expr *Arg = CE->getArg(ArgIndex - 1);
4461 
4462         return checkFormatStringExpr(S, Arg, Args,
4463                                      HasVAListArg, format_idx, firstDataArg,
4464                                      Type, CallType, InFunctionCall,
4465                                      CheckedVarArgs, UncoveredArg, Offset);
4466       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4467         unsigned BuiltinID = FD->getBuiltinID();
4468         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4469             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4470           const Expr *Arg = CE->getArg(0);
4471           return checkFormatStringExpr(S, Arg, Args,
4472                                        HasVAListArg, format_idx,
4473                                        firstDataArg, Type, CallType,
4474                                        InFunctionCall, CheckedVarArgs,
4475                                        UncoveredArg, Offset);
4476         }
4477       }
4478     }
4479 
4480     return SLCT_NotALiteral;
4481   }
4482   case Stmt::ObjCStringLiteralClass:
4483   case Stmt::StringLiteralClass: {
4484     const StringLiteral *StrE = nullptr;
4485 
4486     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4487       StrE = ObjCFExpr->getString();
4488     else
4489       StrE = cast<StringLiteral>(E);
4490 
4491     if (StrE) {
4492       if (Offset.isNegative() || Offset > StrE->getLength()) {
4493         // TODO: It would be better to have an explicit warning for out of
4494         // bounds literals.
4495         return SLCT_NotALiteral;
4496       }
4497       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4498       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4499                         firstDataArg, Type, InFunctionCall, CallType,
4500                         CheckedVarArgs, UncoveredArg);
4501       return SLCT_CheckedLiteral;
4502     }
4503 
4504     return SLCT_NotALiteral;
4505   }
4506   case Stmt::BinaryOperatorClass: {
4507     llvm::APSInt LResult;
4508     llvm::APSInt RResult;
4509 
4510     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4511 
4512     // A string literal + an int offset is still a string literal.
4513     if (BinOp->isAdditiveOp()) {
4514       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4515       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4516 
4517       if (LIsInt != RIsInt) {
4518         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4519 
4520         if (LIsInt) {
4521           if (BinOpKind == BO_Add) {
4522             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4523             E = BinOp->getRHS();
4524             goto tryAgain;
4525           }
4526         } else {
4527           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4528           E = BinOp->getLHS();
4529           goto tryAgain;
4530         }
4531       }
4532     }
4533 
4534     return SLCT_NotALiteral;
4535   }
4536   case Stmt::UnaryOperatorClass: {
4537     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4538     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4539     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4540       llvm::APSInt IndexResult;
4541       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4542         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4543         E = ASE->getBase();
4544         goto tryAgain;
4545       }
4546     }
4547 
4548     return SLCT_NotALiteral;
4549   }
4550 
4551   default:
4552     return SLCT_NotALiteral;
4553   }
4554 }
4555 
4556 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4557   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4558   .Case("scanf", FST_Scanf)
4559   .Cases("printf", "printf0", FST_Printf)
4560   .Cases("NSString", "CFString", FST_NSString)
4561   .Case("strftime", FST_Strftime)
4562   .Case("strfmon", FST_Strfmon)
4563   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4564   .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4565   .Case("os_trace", FST_OSTrace)
4566   .Default(FST_Unknown);
4567 }
4568 
4569 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4570 /// functions) for correct use of format strings.
4571 /// Returns true if a format string has been fully checked.
4572 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4573                                 ArrayRef<const Expr *> Args,
4574                                 bool IsCXXMember,
4575                                 VariadicCallType CallType,
4576                                 SourceLocation Loc, SourceRange Range,
4577                                 llvm::SmallBitVector &CheckedVarArgs) {
4578   FormatStringInfo FSI;
4579   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4580     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4581                                 FSI.FirstDataArg, GetFormatStringType(Format),
4582                                 CallType, Loc, Range, CheckedVarArgs);
4583   return false;
4584 }
4585 
4586 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4587                                 bool HasVAListArg, unsigned format_idx,
4588                                 unsigned firstDataArg, FormatStringType Type,
4589                                 VariadicCallType CallType,
4590                                 SourceLocation Loc, SourceRange Range,
4591                                 llvm::SmallBitVector &CheckedVarArgs) {
4592   // CHECK: printf/scanf-like function is called with no format string.
4593   if (format_idx >= Args.size()) {
4594     Diag(Loc, diag::warn_missing_format_string) << Range;
4595     return false;
4596   }
4597 
4598   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4599 
4600   // CHECK: format string is not a string literal.
4601   //
4602   // Dynamically generated format strings are difficult to
4603   // automatically vet at compile time.  Requiring that format strings
4604   // are string literals: (1) permits the checking of format strings by
4605   // the compiler and thereby (2) can practically remove the source of
4606   // many format string exploits.
4607 
4608   // Format string can be either ObjC string (e.g. @"%d") or
4609   // C string (e.g. "%d")
4610   // ObjC string uses the same format specifiers as C string, so we can use
4611   // the same format string checking logic for both ObjC and C strings.
4612   UncoveredArgHandler UncoveredArg;
4613   StringLiteralCheckType CT =
4614       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4615                             format_idx, firstDataArg, Type, CallType,
4616                             /*IsFunctionCall*/ true, CheckedVarArgs,
4617                             UncoveredArg,
4618                             /*no string offset*/ llvm::APSInt(64, false) = 0);
4619 
4620   // Generate a diagnostic where an uncovered argument is detected.
4621   if (UncoveredArg.hasUncoveredArg()) {
4622     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4623     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4624     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4625   }
4626 
4627   if (CT != SLCT_NotALiteral)
4628     // Literal format string found, check done!
4629     return CT == SLCT_CheckedLiteral;
4630 
4631   // Strftime is particular as it always uses a single 'time' argument,
4632   // so it is safe to pass a non-literal string.
4633   if (Type == FST_Strftime)
4634     return false;
4635 
4636   // Do not emit diag when the string param is a macro expansion and the
4637   // format is either NSString or CFString. This is a hack to prevent
4638   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4639   // which are usually used in place of NS and CF string literals.
4640   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4641   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4642     return false;
4643 
4644   // If there are no arguments specified, warn with -Wformat-security, otherwise
4645   // warn only with -Wformat-nonliteral.
4646   if (Args.size() == firstDataArg) {
4647     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4648       << OrigFormatExpr->getSourceRange();
4649     switch (Type) {
4650     default:
4651       break;
4652     case FST_Kprintf:
4653     case FST_FreeBSDKPrintf:
4654     case FST_Printf:
4655       Diag(FormatLoc, diag::note_format_security_fixit)
4656         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4657       break;
4658     case FST_NSString:
4659       Diag(FormatLoc, diag::note_format_security_fixit)
4660         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4661       break;
4662     }
4663   } else {
4664     Diag(FormatLoc, diag::warn_format_nonliteral)
4665       << OrigFormatExpr->getSourceRange();
4666   }
4667   return false;
4668 }
4669 
4670 namespace {
4671 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4672 protected:
4673   Sema &S;
4674   const FormatStringLiteral *FExpr;
4675   const Expr *OrigFormatExpr;
4676   const unsigned FirstDataArg;
4677   const unsigned NumDataArgs;
4678   const char *Beg; // Start of format string.
4679   const bool HasVAListArg;
4680   ArrayRef<const Expr *> Args;
4681   unsigned FormatIdx;
4682   llvm::SmallBitVector CoveredArgs;
4683   bool usesPositionalArgs;
4684   bool atFirstArg;
4685   bool inFunctionCall;
4686   Sema::VariadicCallType CallType;
4687   llvm::SmallBitVector &CheckedVarArgs;
4688   UncoveredArgHandler &UncoveredArg;
4689 
4690 public:
4691   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4692                      const Expr *origFormatExpr, unsigned firstDataArg,
4693                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
4694                      ArrayRef<const Expr *> Args,
4695                      unsigned formatIdx, bool inFunctionCall,
4696                      Sema::VariadicCallType callType,
4697                      llvm::SmallBitVector &CheckedVarArgs,
4698                      UncoveredArgHandler &UncoveredArg)
4699     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
4700       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4701       Beg(beg), HasVAListArg(hasVAListArg),
4702       Args(Args), FormatIdx(formatIdx),
4703       usesPositionalArgs(false), atFirstArg(true),
4704       inFunctionCall(inFunctionCall), CallType(callType),
4705       CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4706     CoveredArgs.resize(numDataArgs);
4707     CoveredArgs.reset();
4708   }
4709 
4710   void DoneProcessing();
4711 
4712   void HandleIncompleteSpecifier(const char *startSpecifier,
4713                                  unsigned specifierLen) override;
4714 
4715   void HandleInvalidLengthModifier(
4716                            const analyze_format_string::FormatSpecifier &FS,
4717                            const analyze_format_string::ConversionSpecifier &CS,
4718                            const char *startSpecifier, unsigned specifierLen,
4719                            unsigned DiagID);
4720 
4721   void HandleNonStandardLengthModifier(
4722                     const analyze_format_string::FormatSpecifier &FS,
4723                     const char *startSpecifier, unsigned specifierLen);
4724 
4725   void HandleNonStandardConversionSpecifier(
4726                     const analyze_format_string::ConversionSpecifier &CS,
4727                     const char *startSpecifier, unsigned specifierLen);
4728 
4729   void HandlePosition(const char *startPos, unsigned posLen) override;
4730 
4731   void HandleInvalidPosition(const char *startSpecifier,
4732                              unsigned specifierLen,
4733                              analyze_format_string::PositionContext p) override;
4734 
4735   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4736 
4737   void HandleNullChar(const char *nullCharacter) override;
4738 
4739   template <typename Range>
4740   static void
4741   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4742                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4743                        bool IsStringLocation, Range StringRange,
4744                        ArrayRef<FixItHint> Fixit = None);
4745 
4746 protected:
4747   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4748                                         const char *startSpec,
4749                                         unsigned specifierLen,
4750                                         const char *csStart, unsigned csLen);
4751 
4752   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4753                                          const char *startSpec,
4754                                          unsigned specifierLen);
4755 
4756   SourceRange getFormatStringRange();
4757   CharSourceRange getSpecifierRange(const char *startSpecifier,
4758                                     unsigned specifierLen);
4759   SourceLocation getLocationOfByte(const char *x);
4760 
4761   const Expr *getDataArg(unsigned i) const;
4762 
4763   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4764                     const analyze_format_string::ConversionSpecifier &CS,
4765                     const char *startSpecifier, unsigned specifierLen,
4766                     unsigned argIndex);
4767 
4768   template <typename Range>
4769   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4770                             bool IsStringLocation, Range StringRange,
4771                             ArrayRef<FixItHint> Fixit = None);
4772 };
4773 } // end anonymous namespace
4774 
4775 SourceRange CheckFormatHandler::getFormatStringRange() {
4776   return OrigFormatExpr->getSourceRange();
4777 }
4778 
4779 CharSourceRange CheckFormatHandler::
4780 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4781   SourceLocation Start = getLocationOfByte(startSpecifier);
4782   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4783 
4784   // Advance the end SourceLocation by one due to half-open ranges.
4785   End = End.getLocWithOffset(1);
4786 
4787   return CharSourceRange::getCharRange(Start, End);
4788 }
4789 
4790 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4791   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4792                                   S.getLangOpts(), S.Context.getTargetInfo());
4793 }
4794 
4795 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4796                                                    unsigned specifierLen){
4797   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4798                        getLocationOfByte(startSpecifier),
4799                        /*IsStringLocation*/true,
4800                        getSpecifierRange(startSpecifier, specifierLen));
4801 }
4802 
4803 void CheckFormatHandler::HandleInvalidLengthModifier(
4804     const analyze_format_string::FormatSpecifier &FS,
4805     const analyze_format_string::ConversionSpecifier &CS,
4806     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4807   using namespace analyze_format_string;
4808 
4809   const LengthModifier &LM = FS.getLengthModifier();
4810   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4811 
4812   // See if we know how to fix this length modifier.
4813   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4814   if (FixedLM) {
4815     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4816                          getLocationOfByte(LM.getStart()),
4817                          /*IsStringLocation*/true,
4818                          getSpecifierRange(startSpecifier, specifierLen));
4819 
4820     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4821       << FixedLM->toString()
4822       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4823 
4824   } else {
4825     FixItHint Hint;
4826     if (DiagID == diag::warn_format_nonsensical_length)
4827       Hint = FixItHint::CreateRemoval(LMRange);
4828 
4829     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4830                          getLocationOfByte(LM.getStart()),
4831                          /*IsStringLocation*/true,
4832                          getSpecifierRange(startSpecifier, specifierLen),
4833                          Hint);
4834   }
4835 }
4836 
4837 void CheckFormatHandler::HandleNonStandardLengthModifier(
4838     const analyze_format_string::FormatSpecifier &FS,
4839     const char *startSpecifier, unsigned specifierLen) {
4840   using namespace analyze_format_string;
4841 
4842   const LengthModifier &LM = FS.getLengthModifier();
4843   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4844 
4845   // See if we know how to fix this length modifier.
4846   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4847   if (FixedLM) {
4848     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4849                            << LM.toString() << 0,
4850                          getLocationOfByte(LM.getStart()),
4851                          /*IsStringLocation*/true,
4852                          getSpecifierRange(startSpecifier, specifierLen));
4853 
4854     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4855       << FixedLM->toString()
4856       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4857 
4858   } else {
4859     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4860                            << LM.toString() << 0,
4861                          getLocationOfByte(LM.getStart()),
4862                          /*IsStringLocation*/true,
4863                          getSpecifierRange(startSpecifier, specifierLen));
4864   }
4865 }
4866 
4867 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4868     const analyze_format_string::ConversionSpecifier &CS,
4869     const char *startSpecifier, unsigned specifierLen) {
4870   using namespace analyze_format_string;
4871 
4872   // See if we know how to fix this conversion specifier.
4873   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
4874   if (FixedCS) {
4875     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4876                           << CS.toString() << /*conversion specifier*/1,
4877                          getLocationOfByte(CS.getStart()),
4878                          /*IsStringLocation*/true,
4879                          getSpecifierRange(startSpecifier, specifierLen));
4880 
4881     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4882     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4883       << FixedCS->toString()
4884       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4885   } else {
4886     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4887                           << CS.toString() << /*conversion specifier*/1,
4888                          getLocationOfByte(CS.getStart()),
4889                          /*IsStringLocation*/true,
4890                          getSpecifierRange(startSpecifier, specifierLen));
4891   }
4892 }
4893 
4894 void CheckFormatHandler::HandlePosition(const char *startPos,
4895                                         unsigned posLen) {
4896   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4897                                getLocationOfByte(startPos),
4898                                /*IsStringLocation*/true,
4899                                getSpecifierRange(startPos, posLen));
4900 }
4901 
4902 void
4903 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4904                                      analyze_format_string::PositionContext p) {
4905   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4906                          << (unsigned) p,
4907                        getLocationOfByte(startPos), /*IsStringLocation*/true,
4908                        getSpecifierRange(startPos, posLen));
4909 }
4910 
4911 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
4912                                             unsigned posLen) {
4913   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4914                                getLocationOfByte(startPos),
4915                                /*IsStringLocation*/true,
4916                                getSpecifierRange(startPos, posLen));
4917 }
4918 
4919 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
4920   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
4921     // The presence of a null character is likely an error.
4922     EmitFormatDiagnostic(
4923       S.PDiag(diag::warn_printf_format_string_contains_null_char),
4924       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4925       getFormatStringRange());
4926   }
4927 }
4928 
4929 // Note that this may return NULL if there was an error parsing or building
4930 // one of the argument expressions.
4931 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
4932   return Args[FirstDataArg + i];
4933 }
4934 
4935 void CheckFormatHandler::DoneProcessing() {
4936   // Does the number of data arguments exceed the number of
4937   // format conversions in the format string?
4938   if (!HasVAListArg) {
4939       // Find any arguments that weren't covered.
4940     CoveredArgs.flip();
4941     signed notCoveredArg = CoveredArgs.find_first();
4942     if (notCoveredArg >= 0) {
4943       assert((unsigned)notCoveredArg < NumDataArgs);
4944       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4945     } else {
4946       UncoveredArg.setAllCovered();
4947     }
4948   }
4949 }
4950 
4951 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4952                                    const Expr *ArgExpr) {
4953   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4954          "Invalid state");
4955 
4956   if (!ArgExpr)
4957     return;
4958 
4959   SourceLocation Loc = ArgExpr->getLocStart();
4960 
4961   if (S.getSourceManager().isInSystemMacro(Loc))
4962     return;
4963 
4964   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4965   for (auto E : DiagnosticExprs)
4966     PDiag << E->getSourceRange();
4967 
4968   CheckFormatHandler::EmitFormatDiagnostic(
4969                                   S, IsFunctionCall, DiagnosticExprs[0],
4970                                   PDiag, Loc, /*IsStringLocation*/false,
4971                                   DiagnosticExprs[0]->getSourceRange());
4972 }
4973 
4974 bool
4975 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4976                                                      SourceLocation Loc,
4977                                                      const char *startSpec,
4978                                                      unsigned specifierLen,
4979                                                      const char *csStart,
4980                                                      unsigned csLen) {
4981   bool keepGoing = true;
4982   if (argIndex < NumDataArgs) {
4983     // Consider the argument coverered, even though the specifier doesn't
4984     // make sense.
4985     CoveredArgs.set(argIndex);
4986   }
4987   else {
4988     // If argIndex exceeds the number of data arguments we
4989     // don't issue a warning because that is just a cascade of warnings (and
4990     // they may have intended '%%' anyway). We don't want to continue processing
4991     // the format string after this point, however, as we will like just get
4992     // gibberish when trying to match arguments.
4993     keepGoing = false;
4994   }
4995 
4996   StringRef Specifier(csStart, csLen);
4997 
4998   // If the specifier in non-printable, it could be the first byte of a UTF-8
4999   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5000   // hex value.
5001   std::string CodePointStr;
5002   if (!llvm::sys::locale::isPrint(*csStart)) {
5003     llvm::UTF32 CodePoint;
5004     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5005     const llvm::UTF8 *E =
5006         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5007     llvm::ConversionResult Result =
5008         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5009 
5010     if (Result != llvm::conversionOK) {
5011       unsigned char FirstChar = *csStart;
5012       CodePoint = (llvm::UTF32)FirstChar;
5013     }
5014 
5015     llvm::raw_string_ostream OS(CodePointStr);
5016     if (CodePoint < 256)
5017       OS << "\\x" << llvm::format("%02x", CodePoint);
5018     else if (CodePoint <= 0xFFFF)
5019       OS << "\\u" << llvm::format("%04x", CodePoint);
5020     else
5021       OS << "\\U" << llvm::format("%08x", CodePoint);
5022     OS.flush();
5023     Specifier = CodePointStr;
5024   }
5025 
5026   EmitFormatDiagnostic(
5027       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5028       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5029 
5030   return keepGoing;
5031 }
5032 
5033 void
5034 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5035                                                       const char *startSpec,
5036                                                       unsigned specifierLen) {
5037   EmitFormatDiagnostic(
5038     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5039     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5040 }
5041 
5042 bool
5043 CheckFormatHandler::CheckNumArgs(
5044   const analyze_format_string::FormatSpecifier &FS,
5045   const analyze_format_string::ConversionSpecifier &CS,
5046   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5047 
5048   if (argIndex >= NumDataArgs) {
5049     PartialDiagnostic PDiag = FS.usesPositionalArg()
5050       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5051            << (argIndex+1) << NumDataArgs)
5052       : S.PDiag(diag::warn_printf_insufficient_data_args);
5053     EmitFormatDiagnostic(
5054       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5055       getSpecifierRange(startSpecifier, specifierLen));
5056 
5057     // Since more arguments than conversion tokens are given, by extension
5058     // all arguments are covered, so mark this as so.
5059     UncoveredArg.setAllCovered();
5060     return false;
5061   }
5062   return true;
5063 }
5064 
5065 template<typename Range>
5066 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5067                                               SourceLocation Loc,
5068                                               bool IsStringLocation,
5069                                               Range StringRange,
5070                                               ArrayRef<FixItHint> FixIt) {
5071   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5072                        Loc, IsStringLocation, StringRange, FixIt);
5073 }
5074 
5075 /// \brief If the format string is not within the funcion call, emit a note
5076 /// so that the function call and string are in diagnostic messages.
5077 ///
5078 /// \param InFunctionCall if true, the format string is within the function
5079 /// call and only one diagnostic message will be produced.  Otherwise, an
5080 /// extra note will be emitted pointing to location of the format string.
5081 ///
5082 /// \param ArgumentExpr the expression that is passed as the format string
5083 /// argument in the function call.  Used for getting locations when two
5084 /// diagnostics are emitted.
5085 ///
5086 /// \param PDiag the callee should already have provided any strings for the
5087 /// diagnostic message.  This function only adds locations and fixits
5088 /// to diagnostics.
5089 ///
5090 /// \param Loc primary location for diagnostic.  If two diagnostics are
5091 /// required, one will be at Loc and a new SourceLocation will be created for
5092 /// the other one.
5093 ///
5094 /// \param IsStringLocation if true, Loc points to the format string should be
5095 /// used for the note.  Otherwise, Loc points to the argument list and will
5096 /// be used with PDiag.
5097 ///
5098 /// \param StringRange some or all of the string to highlight.  This is
5099 /// templated so it can accept either a CharSourceRange or a SourceRange.
5100 ///
5101 /// \param FixIt optional fix it hint for the format string.
5102 template <typename Range>
5103 void CheckFormatHandler::EmitFormatDiagnostic(
5104     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5105     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5106     Range StringRange, ArrayRef<FixItHint> FixIt) {
5107   if (InFunctionCall) {
5108     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5109     D << StringRange;
5110     D << FixIt;
5111   } else {
5112     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5113       << ArgumentExpr->getSourceRange();
5114 
5115     const Sema::SemaDiagnosticBuilder &Note =
5116       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5117              diag::note_format_string_defined);
5118 
5119     Note << StringRange;
5120     Note << FixIt;
5121   }
5122 }
5123 
5124 //===--- CHECK: Printf format string checking ------------------------------===//
5125 
5126 namespace {
5127 class CheckPrintfHandler : public CheckFormatHandler {
5128   bool ObjCContext;
5129 
5130 public:
5131   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5132                      const Expr *origFormatExpr, unsigned firstDataArg,
5133                      unsigned numDataArgs, bool isObjC,
5134                      const char *beg, bool hasVAListArg,
5135                      ArrayRef<const Expr *> Args,
5136                      unsigned formatIdx, bool inFunctionCall,
5137                      Sema::VariadicCallType CallType,
5138                      llvm::SmallBitVector &CheckedVarArgs,
5139                      UncoveredArgHandler &UncoveredArg)
5140     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5141                          numDataArgs, beg, hasVAListArg, Args,
5142                          formatIdx, inFunctionCall, CallType, CheckedVarArgs,
5143                          UncoveredArg),
5144       ObjCContext(isObjC)
5145   {}
5146 
5147   bool HandleInvalidPrintfConversionSpecifier(
5148                                       const analyze_printf::PrintfSpecifier &FS,
5149                                       const char *startSpecifier,
5150                                       unsigned specifierLen) override;
5151 
5152   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5153                              const char *startSpecifier,
5154                              unsigned specifierLen) override;
5155   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5156                        const char *StartSpecifier,
5157                        unsigned SpecifierLen,
5158                        const Expr *E);
5159 
5160   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5161                     const char *startSpecifier, unsigned specifierLen);
5162   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5163                            const analyze_printf::OptionalAmount &Amt,
5164                            unsigned type,
5165                            const char *startSpecifier, unsigned specifierLen);
5166   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5167                   const analyze_printf::OptionalFlag &flag,
5168                   const char *startSpecifier, unsigned specifierLen);
5169   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5170                          const analyze_printf::OptionalFlag &ignoredFlag,
5171                          const analyze_printf::OptionalFlag &flag,
5172                          const char *startSpecifier, unsigned specifierLen);
5173   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5174                            const Expr *E);
5175 
5176   void HandleEmptyObjCModifierFlag(const char *startFlag,
5177                                    unsigned flagLen) override;
5178 
5179   void HandleInvalidObjCModifierFlag(const char *startFlag,
5180                                             unsigned flagLen) override;
5181 
5182   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5183                                            const char *flagsEnd,
5184                                            const char *conversionPosition)
5185                                              override;
5186 };
5187 } // end anonymous namespace
5188 
5189 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5190                                       const analyze_printf::PrintfSpecifier &FS,
5191                                       const char *startSpecifier,
5192                                       unsigned specifierLen) {
5193   const analyze_printf::PrintfConversionSpecifier &CS =
5194     FS.getConversionSpecifier();
5195 
5196   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5197                                           getLocationOfByte(CS.getStart()),
5198                                           startSpecifier, specifierLen,
5199                                           CS.getStart(), CS.getLength());
5200 }
5201 
5202 bool CheckPrintfHandler::HandleAmount(
5203                                const analyze_format_string::OptionalAmount &Amt,
5204                                unsigned k, const char *startSpecifier,
5205                                unsigned specifierLen) {
5206   if (Amt.hasDataArgument()) {
5207     if (!HasVAListArg) {
5208       unsigned argIndex = Amt.getArgIndex();
5209       if (argIndex >= NumDataArgs) {
5210         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5211                                << k,
5212                              getLocationOfByte(Amt.getStart()),
5213                              /*IsStringLocation*/true,
5214                              getSpecifierRange(startSpecifier, specifierLen));
5215         // Don't do any more checking.  We will just emit
5216         // spurious errors.
5217         return false;
5218       }
5219 
5220       // Type check the data argument.  It should be an 'int'.
5221       // Although not in conformance with C99, we also allow the argument to be
5222       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5223       // doesn't emit a warning for that case.
5224       CoveredArgs.set(argIndex);
5225       const Expr *Arg = getDataArg(argIndex);
5226       if (!Arg)
5227         return false;
5228 
5229       QualType T = Arg->getType();
5230 
5231       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5232       assert(AT.isValid());
5233 
5234       if (!AT.matchesType(S.Context, T)) {
5235         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5236                                << k << AT.getRepresentativeTypeName(S.Context)
5237                                << T << Arg->getSourceRange(),
5238                              getLocationOfByte(Amt.getStart()),
5239                              /*IsStringLocation*/true,
5240                              getSpecifierRange(startSpecifier, specifierLen));
5241         // Don't do any more checking.  We will just emit
5242         // spurious errors.
5243         return false;
5244       }
5245     }
5246   }
5247   return true;
5248 }
5249 
5250 void CheckPrintfHandler::HandleInvalidAmount(
5251                                       const analyze_printf::PrintfSpecifier &FS,
5252                                       const analyze_printf::OptionalAmount &Amt,
5253                                       unsigned type,
5254                                       const char *startSpecifier,
5255                                       unsigned specifierLen) {
5256   const analyze_printf::PrintfConversionSpecifier &CS =
5257     FS.getConversionSpecifier();
5258 
5259   FixItHint fixit =
5260     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5261       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5262                                  Amt.getConstantLength()))
5263       : FixItHint();
5264 
5265   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5266                          << type << CS.toString(),
5267                        getLocationOfByte(Amt.getStart()),
5268                        /*IsStringLocation*/true,
5269                        getSpecifierRange(startSpecifier, specifierLen),
5270                        fixit);
5271 }
5272 
5273 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5274                                     const analyze_printf::OptionalFlag &flag,
5275                                     const char *startSpecifier,
5276                                     unsigned specifierLen) {
5277   // Warn about pointless flag with a fixit removal.
5278   const analyze_printf::PrintfConversionSpecifier &CS =
5279     FS.getConversionSpecifier();
5280   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5281                          << flag.toString() << CS.toString(),
5282                        getLocationOfByte(flag.getPosition()),
5283                        /*IsStringLocation*/true,
5284                        getSpecifierRange(startSpecifier, specifierLen),
5285                        FixItHint::CreateRemoval(
5286                          getSpecifierRange(flag.getPosition(), 1)));
5287 }
5288 
5289 void CheckPrintfHandler::HandleIgnoredFlag(
5290                                 const analyze_printf::PrintfSpecifier &FS,
5291                                 const analyze_printf::OptionalFlag &ignoredFlag,
5292                                 const analyze_printf::OptionalFlag &flag,
5293                                 const char *startSpecifier,
5294                                 unsigned specifierLen) {
5295   // Warn about ignored flag with a fixit removal.
5296   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5297                          << ignoredFlag.toString() << flag.toString(),
5298                        getLocationOfByte(ignoredFlag.getPosition()),
5299                        /*IsStringLocation*/true,
5300                        getSpecifierRange(startSpecifier, specifierLen),
5301                        FixItHint::CreateRemoval(
5302                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5303 }
5304 
5305 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5306 //                            bool IsStringLocation, Range StringRange,
5307 //                            ArrayRef<FixItHint> Fixit = None);
5308 
5309 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5310                                                      unsigned flagLen) {
5311   // Warn about an empty flag.
5312   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5313                        getLocationOfByte(startFlag),
5314                        /*IsStringLocation*/true,
5315                        getSpecifierRange(startFlag, flagLen));
5316 }
5317 
5318 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5319                                                        unsigned flagLen) {
5320   // Warn about an invalid flag.
5321   auto Range = getSpecifierRange(startFlag, flagLen);
5322   StringRef flag(startFlag, flagLen);
5323   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5324                       getLocationOfByte(startFlag),
5325                       /*IsStringLocation*/true,
5326                       Range, FixItHint::CreateRemoval(Range));
5327 }
5328 
5329 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5330     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5331     // Warn about using '[...]' without a '@' conversion.
5332     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5333     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5334     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5335                          getLocationOfByte(conversionPosition),
5336                          /*IsStringLocation*/true,
5337                          Range, FixItHint::CreateRemoval(Range));
5338 }
5339 
5340 // Determines if the specified is a C++ class or struct containing
5341 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5342 // "c_str()").
5343 template<typename MemberKind>
5344 static llvm::SmallPtrSet<MemberKind*, 1>
5345 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5346   const RecordType *RT = Ty->getAs<RecordType>();
5347   llvm::SmallPtrSet<MemberKind*, 1> Results;
5348 
5349   if (!RT)
5350     return Results;
5351   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5352   if (!RD || !RD->getDefinition())
5353     return Results;
5354 
5355   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5356                  Sema::LookupMemberName);
5357   R.suppressDiagnostics();
5358 
5359   // We just need to include all members of the right kind turned up by the
5360   // filter, at this point.
5361   if (S.LookupQualifiedName(R, RT->getDecl()))
5362     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5363       NamedDecl *decl = (*I)->getUnderlyingDecl();
5364       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5365         Results.insert(FK);
5366     }
5367   return Results;
5368 }
5369 
5370 /// Check if we could call '.c_str()' on an object.
5371 ///
5372 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5373 /// allow the call, or if it would be ambiguous).
5374 bool Sema::hasCStrMethod(const Expr *E) {
5375   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5376   MethodSet Results =
5377       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5378   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5379        MI != ME; ++MI)
5380     if ((*MI)->getMinRequiredArguments() == 0)
5381       return true;
5382   return false;
5383 }
5384 
5385 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5386 // better diagnostic if so. AT is assumed to be valid.
5387 // Returns true when a c_str() conversion method is found.
5388 bool CheckPrintfHandler::checkForCStrMembers(
5389     const analyze_printf::ArgType &AT, const Expr *E) {
5390   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5391 
5392   MethodSet Results =
5393       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5394 
5395   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5396        MI != ME; ++MI) {
5397     const CXXMethodDecl *Method = *MI;
5398     if (Method->getMinRequiredArguments() == 0 &&
5399         AT.matchesType(S.Context, Method->getReturnType())) {
5400       // FIXME: Suggest parens if the expression needs them.
5401       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5402       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5403           << "c_str()"
5404           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5405       return true;
5406     }
5407   }
5408 
5409   return false;
5410 }
5411 
5412 bool
5413 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5414                                             &FS,
5415                                           const char *startSpecifier,
5416                                           unsigned specifierLen) {
5417   using namespace analyze_format_string;
5418   using namespace analyze_printf;
5419   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5420 
5421   if (FS.consumesDataArgument()) {
5422     if (atFirstArg) {
5423         atFirstArg = false;
5424         usesPositionalArgs = FS.usesPositionalArg();
5425     }
5426     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5427       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5428                                         startSpecifier, specifierLen);
5429       return false;
5430     }
5431   }
5432 
5433   // First check if the field width, precision, and conversion specifier
5434   // have matching data arguments.
5435   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5436                     startSpecifier, specifierLen)) {
5437     return false;
5438   }
5439 
5440   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5441                     startSpecifier, specifierLen)) {
5442     return false;
5443   }
5444 
5445   if (!CS.consumesDataArgument()) {
5446     // FIXME: Technically specifying a precision or field width here
5447     // makes no sense.  Worth issuing a warning at some point.
5448     return true;
5449   }
5450 
5451   // Consume the argument.
5452   unsigned argIndex = FS.getArgIndex();
5453   if (argIndex < NumDataArgs) {
5454     // The check to see if the argIndex is valid will come later.
5455     // We set the bit here because we may exit early from this
5456     // function if we encounter some other error.
5457     CoveredArgs.set(argIndex);
5458   }
5459 
5460   // FreeBSD kernel extensions.
5461   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5462       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5463     // We need at least two arguments.
5464     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5465       return false;
5466 
5467     // Claim the second argument.
5468     CoveredArgs.set(argIndex + 1);
5469 
5470     // Type check the first argument (int for %b, pointer for %D)
5471     const Expr *Ex = getDataArg(argIndex);
5472     const analyze_printf::ArgType &AT =
5473       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5474         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5475     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5476       EmitFormatDiagnostic(
5477         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5478         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5479         << false << Ex->getSourceRange(),
5480         Ex->getLocStart(), /*IsStringLocation*/false,
5481         getSpecifierRange(startSpecifier, specifierLen));
5482 
5483     // Type check the second argument (char * for both %b and %D)
5484     Ex = getDataArg(argIndex + 1);
5485     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5486     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5487       EmitFormatDiagnostic(
5488         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5489         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5490         << false << Ex->getSourceRange(),
5491         Ex->getLocStart(), /*IsStringLocation*/false,
5492         getSpecifierRange(startSpecifier, specifierLen));
5493 
5494      return true;
5495   }
5496 
5497   // Check for using an Objective-C specific conversion specifier
5498   // in a non-ObjC literal.
5499   if (!ObjCContext && CS.isObjCArg()) {
5500     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5501                                                   specifierLen);
5502   }
5503 
5504   // Check for invalid use of field width
5505   if (!FS.hasValidFieldWidth()) {
5506     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5507         startSpecifier, specifierLen);
5508   }
5509 
5510   // Check for invalid use of precision
5511   if (!FS.hasValidPrecision()) {
5512     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5513         startSpecifier, specifierLen);
5514   }
5515 
5516   // Check each flag does not conflict with any other component.
5517   if (!FS.hasValidThousandsGroupingPrefix())
5518     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5519   if (!FS.hasValidLeadingZeros())
5520     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5521   if (!FS.hasValidPlusPrefix())
5522     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5523   if (!FS.hasValidSpacePrefix())
5524     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5525   if (!FS.hasValidAlternativeForm())
5526     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5527   if (!FS.hasValidLeftJustified())
5528     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5529 
5530   // Check that flags are not ignored by another flag
5531   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5532     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5533         startSpecifier, specifierLen);
5534   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5535     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5536             startSpecifier, specifierLen);
5537 
5538   // Check the length modifier is valid with the given conversion specifier.
5539   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5540     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5541                                 diag::warn_format_nonsensical_length);
5542   else if (!FS.hasStandardLengthModifier())
5543     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5544   else if (!FS.hasStandardLengthConversionCombination())
5545     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5546                                 diag::warn_format_non_standard_conversion_spec);
5547 
5548   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5549     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5550 
5551   // The remaining checks depend on the data arguments.
5552   if (HasVAListArg)
5553     return true;
5554 
5555   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5556     return false;
5557 
5558   const Expr *Arg = getDataArg(argIndex);
5559   if (!Arg)
5560     return true;
5561 
5562   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5563 }
5564 
5565 static bool requiresParensToAddCast(const Expr *E) {
5566   // FIXME: We should have a general way to reason about operator
5567   // precedence and whether parens are actually needed here.
5568   // Take care of a few common cases where they aren't.
5569   const Expr *Inside = E->IgnoreImpCasts();
5570   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5571     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5572 
5573   switch (Inside->getStmtClass()) {
5574   case Stmt::ArraySubscriptExprClass:
5575   case Stmt::CallExprClass:
5576   case Stmt::CharacterLiteralClass:
5577   case Stmt::CXXBoolLiteralExprClass:
5578   case Stmt::DeclRefExprClass:
5579   case Stmt::FloatingLiteralClass:
5580   case Stmt::IntegerLiteralClass:
5581   case Stmt::MemberExprClass:
5582   case Stmt::ObjCArrayLiteralClass:
5583   case Stmt::ObjCBoolLiteralExprClass:
5584   case Stmt::ObjCBoxedExprClass:
5585   case Stmt::ObjCDictionaryLiteralClass:
5586   case Stmt::ObjCEncodeExprClass:
5587   case Stmt::ObjCIvarRefExprClass:
5588   case Stmt::ObjCMessageExprClass:
5589   case Stmt::ObjCPropertyRefExprClass:
5590   case Stmt::ObjCStringLiteralClass:
5591   case Stmt::ObjCSubscriptRefExprClass:
5592   case Stmt::ParenExprClass:
5593   case Stmt::StringLiteralClass:
5594   case Stmt::UnaryOperatorClass:
5595     return false;
5596   default:
5597     return true;
5598   }
5599 }
5600 
5601 static std::pair<QualType, StringRef>
5602 shouldNotPrintDirectly(const ASTContext &Context,
5603                        QualType IntendedTy,
5604                        const Expr *E) {
5605   // Use a 'while' to peel off layers of typedefs.
5606   QualType TyTy = IntendedTy;
5607   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5608     StringRef Name = UserTy->getDecl()->getName();
5609     QualType CastTy = llvm::StringSwitch<QualType>(Name)
5610       .Case("NSInteger", Context.LongTy)
5611       .Case("NSUInteger", Context.UnsignedLongTy)
5612       .Case("SInt32", Context.IntTy)
5613       .Case("UInt32", Context.UnsignedIntTy)
5614       .Default(QualType());
5615 
5616     if (!CastTy.isNull())
5617       return std::make_pair(CastTy, Name);
5618 
5619     TyTy = UserTy->desugar();
5620   }
5621 
5622   // Strip parens if necessary.
5623   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5624     return shouldNotPrintDirectly(Context,
5625                                   PE->getSubExpr()->getType(),
5626                                   PE->getSubExpr());
5627 
5628   // If this is a conditional expression, then its result type is constructed
5629   // via usual arithmetic conversions and thus there might be no necessary
5630   // typedef sugar there.  Recurse to operands to check for NSInteger &
5631   // Co. usage condition.
5632   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5633     QualType TrueTy, FalseTy;
5634     StringRef TrueName, FalseName;
5635 
5636     std::tie(TrueTy, TrueName) =
5637       shouldNotPrintDirectly(Context,
5638                              CO->getTrueExpr()->getType(),
5639                              CO->getTrueExpr());
5640     std::tie(FalseTy, FalseName) =
5641       shouldNotPrintDirectly(Context,
5642                              CO->getFalseExpr()->getType(),
5643                              CO->getFalseExpr());
5644 
5645     if (TrueTy == FalseTy)
5646       return std::make_pair(TrueTy, TrueName);
5647     else if (TrueTy.isNull())
5648       return std::make_pair(FalseTy, FalseName);
5649     else if (FalseTy.isNull())
5650       return std::make_pair(TrueTy, TrueName);
5651   }
5652 
5653   return std::make_pair(QualType(), StringRef());
5654 }
5655 
5656 bool
5657 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5658                                     const char *StartSpecifier,
5659                                     unsigned SpecifierLen,
5660                                     const Expr *E) {
5661   using namespace analyze_format_string;
5662   using namespace analyze_printf;
5663   // Now type check the data expression that matches the
5664   // format specifier.
5665   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5666                                                     ObjCContext);
5667   if (!AT.isValid())
5668     return true;
5669 
5670   QualType ExprTy = E->getType();
5671   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5672     ExprTy = TET->getUnderlyingExpr()->getType();
5673   }
5674 
5675   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5676 
5677   if (match == analyze_printf::ArgType::Match) {
5678     return true;
5679   }
5680 
5681   // Look through argument promotions for our error message's reported type.
5682   // This includes the integral and floating promotions, but excludes array
5683   // and function pointer decay; seeing that an argument intended to be a
5684   // string has type 'char [6]' is probably more confusing than 'char *'.
5685   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5686     if (ICE->getCastKind() == CK_IntegralCast ||
5687         ICE->getCastKind() == CK_FloatingCast) {
5688       E = ICE->getSubExpr();
5689       ExprTy = E->getType();
5690 
5691       // Check if we didn't match because of an implicit cast from a 'char'
5692       // or 'short' to an 'int'.  This is done because printf is a varargs
5693       // function.
5694       if (ICE->getType() == S.Context.IntTy ||
5695           ICE->getType() == S.Context.UnsignedIntTy) {
5696         // All further checking is done on the subexpression.
5697         if (AT.matchesType(S.Context, ExprTy))
5698           return true;
5699       }
5700     }
5701   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5702     // Special case for 'a', which has type 'int' in C.
5703     // Note, however, that we do /not/ want to treat multibyte constants like
5704     // 'MooV' as characters! This form is deprecated but still exists.
5705     if (ExprTy == S.Context.IntTy)
5706       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5707         ExprTy = S.Context.CharTy;
5708   }
5709 
5710   // Look through enums to their underlying type.
5711   bool IsEnum = false;
5712   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5713     ExprTy = EnumTy->getDecl()->getIntegerType();
5714     IsEnum = true;
5715   }
5716 
5717   // %C in an Objective-C context prints a unichar, not a wchar_t.
5718   // If the argument is an integer of some kind, believe the %C and suggest
5719   // a cast instead of changing the conversion specifier.
5720   QualType IntendedTy = ExprTy;
5721   if (ObjCContext &&
5722       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5723     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5724         !ExprTy->isCharType()) {
5725       // 'unichar' is defined as a typedef of unsigned short, but we should
5726       // prefer using the typedef if it is visible.
5727       IntendedTy = S.Context.UnsignedShortTy;
5728 
5729       // While we are here, check if the value is an IntegerLiteral that happens
5730       // to be within the valid range.
5731       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5732         const llvm::APInt &V = IL->getValue();
5733         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5734           return true;
5735       }
5736 
5737       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5738                           Sema::LookupOrdinaryName);
5739       if (S.LookupName(Result, S.getCurScope())) {
5740         NamedDecl *ND = Result.getFoundDecl();
5741         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5742           if (TD->getUnderlyingType() == IntendedTy)
5743             IntendedTy = S.Context.getTypedefType(TD);
5744       }
5745     }
5746   }
5747 
5748   // Special-case some of Darwin's platform-independence types by suggesting
5749   // casts to primitive types that are known to be large enough.
5750   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5751   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5752     QualType CastTy;
5753     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5754     if (!CastTy.isNull()) {
5755       IntendedTy = CastTy;
5756       ShouldNotPrintDirectly = true;
5757     }
5758   }
5759 
5760   // We may be able to offer a FixItHint if it is a supported type.
5761   PrintfSpecifier fixedFS = FS;
5762   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
5763                                  S.Context, ObjCContext);
5764 
5765   if (success) {
5766     // Get the fix string from the fixed format specifier
5767     SmallString<16> buf;
5768     llvm::raw_svector_ostream os(buf);
5769     fixedFS.toString(os);
5770 
5771     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5772 
5773     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5774       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5775       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5776         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5777       }
5778       // In this case, the specifier is wrong and should be changed to match
5779       // the argument.
5780       EmitFormatDiagnostic(S.PDiag(diag)
5781                                << AT.getRepresentativeTypeName(S.Context)
5782                                << IntendedTy << IsEnum << E->getSourceRange(),
5783                            E->getLocStart(),
5784                            /*IsStringLocation*/ false, SpecRange,
5785                            FixItHint::CreateReplacement(SpecRange, os.str()));
5786     } else {
5787       // The canonical type for formatting this value is different from the
5788       // actual type of the expression. (This occurs, for example, with Darwin's
5789       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5790       // should be printed as 'long' for 64-bit compatibility.)
5791       // Rather than emitting a normal format/argument mismatch, we want to
5792       // add a cast to the recommended type (and correct the format string
5793       // if necessary).
5794       SmallString<16> CastBuf;
5795       llvm::raw_svector_ostream CastFix(CastBuf);
5796       CastFix << "(";
5797       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5798       CastFix << ")";
5799 
5800       SmallVector<FixItHint,4> Hints;
5801       if (!AT.matchesType(S.Context, IntendedTy))
5802         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5803 
5804       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5805         // If there's already a cast present, just replace it.
5806         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5807         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5808 
5809       } else if (!requiresParensToAddCast(E)) {
5810         // If the expression has high enough precedence,
5811         // just write the C-style cast.
5812         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5813                                                    CastFix.str()));
5814       } else {
5815         // Otherwise, add parens around the expression as well as the cast.
5816         CastFix << "(";
5817         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5818                                                    CastFix.str()));
5819 
5820         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
5821         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5822       }
5823 
5824       if (ShouldNotPrintDirectly) {
5825         // The expression has a type that should not be printed directly.
5826         // We extract the name from the typedef because we don't want to show
5827         // the underlying type in the diagnostic.
5828         StringRef Name;
5829         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5830           Name = TypedefTy->getDecl()->getName();
5831         else
5832           Name = CastTyName;
5833         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
5834                                << Name << IntendedTy << IsEnum
5835                                << E->getSourceRange(),
5836                              E->getLocStart(), /*IsStringLocation=*/false,
5837                              SpecRange, Hints);
5838       } else {
5839         // In this case, the expression could be printed using a different
5840         // specifier, but we've decided that the specifier is probably correct
5841         // and we should cast instead. Just use the normal warning message.
5842         EmitFormatDiagnostic(
5843           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5844             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
5845             << E->getSourceRange(),
5846           E->getLocStart(), /*IsStringLocation*/false,
5847           SpecRange, Hints);
5848       }
5849     }
5850   } else {
5851     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5852                                                    SpecifierLen);
5853     // Since the warning for passing non-POD types to variadic functions
5854     // was deferred until now, we emit a warning for non-POD
5855     // arguments here.
5856     switch (S.isValidVarArgType(ExprTy)) {
5857     case Sema::VAK_Valid:
5858     case Sema::VAK_ValidInCXX11: {
5859       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5860       if (match == analyze_printf::ArgType::NoMatchPedantic) {
5861         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5862       }
5863 
5864       EmitFormatDiagnostic(
5865           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5866                         << IsEnum << CSR << E->getSourceRange(),
5867           E->getLocStart(), /*IsStringLocation*/ false, CSR);
5868       break;
5869     }
5870     case Sema::VAK_Undefined:
5871     case Sema::VAK_MSVCUndefined:
5872       EmitFormatDiagnostic(
5873         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
5874           << S.getLangOpts().CPlusPlus11
5875           << ExprTy
5876           << CallType
5877           << AT.getRepresentativeTypeName(S.Context)
5878           << CSR
5879           << E->getSourceRange(),
5880         E->getLocStart(), /*IsStringLocation*/false, CSR);
5881       checkForCStrMembers(AT, E);
5882       break;
5883 
5884     case Sema::VAK_Invalid:
5885       if (ExprTy->isObjCObjectType())
5886         EmitFormatDiagnostic(
5887           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5888             << S.getLangOpts().CPlusPlus11
5889             << ExprTy
5890             << CallType
5891             << AT.getRepresentativeTypeName(S.Context)
5892             << CSR
5893             << E->getSourceRange(),
5894           E->getLocStart(), /*IsStringLocation*/false, CSR);
5895       else
5896         // FIXME: If this is an initializer list, suggest removing the braces
5897         // or inserting a cast to the target type.
5898         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5899           << isa<InitListExpr>(E) << ExprTy << CallType
5900           << AT.getRepresentativeTypeName(S.Context)
5901           << E->getSourceRange();
5902       break;
5903     }
5904 
5905     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5906            "format string specifier index out of range");
5907     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
5908   }
5909 
5910   return true;
5911 }
5912 
5913 //===--- CHECK: Scanf format string checking ------------------------------===//
5914 
5915 namespace {
5916 class CheckScanfHandler : public CheckFormatHandler {
5917 public:
5918   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
5919                     const Expr *origFormatExpr, unsigned firstDataArg,
5920                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
5921                     ArrayRef<const Expr *> Args,
5922                     unsigned formatIdx, bool inFunctionCall,
5923                     Sema::VariadicCallType CallType,
5924                     llvm::SmallBitVector &CheckedVarArgs,
5925                     UncoveredArgHandler &UncoveredArg)
5926     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5927                          numDataArgs, beg, hasVAListArg,
5928                          Args, formatIdx, inFunctionCall, CallType,
5929                          CheckedVarArgs, UncoveredArg)
5930   {}
5931 
5932   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5933                             const char *startSpecifier,
5934                             unsigned specifierLen) override;
5935 
5936   bool HandleInvalidScanfConversionSpecifier(
5937           const analyze_scanf::ScanfSpecifier &FS,
5938           const char *startSpecifier,
5939           unsigned specifierLen) override;
5940 
5941   void HandleIncompleteScanList(const char *start, const char *end) override;
5942 };
5943 } // end anonymous namespace
5944 
5945 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5946                                                  const char *end) {
5947   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5948                        getLocationOfByte(end), /*IsStringLocation*/true,
5949                        getSpecifierRange(start, end - start));
5950 }
5951 
5952 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5953                                         const analyze_scanf::ScanfSpecifier &FS,
5954                                         const char *startSpecifier,
5955                                         unsigned specifierLen) {
5956 
5957   const analyze_scanf::ScanfConversionSpecifier &CS =
5958     FS.getConversionSpecifier();
5959 
5960   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5961                                           getLocationOfByte(CS.getStart()),
5962                                           startSpecifier, specifierLen,
5963                                           CS.getStart(), CS.getLength());
5964 }
5965 
5966 bool CheckScanfHandler::HandleScanfSpecifier(
5967                                        const analyze_scanf::ScanfSpecifier &FS,
5968                                        const char *startSpecifier,
5969                                        unsigned specifierLen) {
5970   using namespace analyze_scanf;
5971   using namespace analyze_format_string;
5972 
5973   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
5974 
5975   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
5976   // be used to decide if we are using positional arguments consistently.
5977   if (FS.consumesDataArgument()) {
5978     if (atFirstArg) {
5979       atFirstArg = false;
5980       usesPositionalArgs = FS.usesPositionalArg();
5981     }
5982     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5983       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5984                                         startSpecifier, specifierLen);
5985       return false;
5986     }
5987   }
5988 
5989   // Check if the field with is non-zero.
5990   const OptionalAmount &Amt = FS.getFieldWidth();
5991   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5992     if (Amt.getConstantAmount() == 0) {
5993       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5994                                                    Amt.getConstantLength());
5995       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5996                            getLocationOfByte(Amt.getStart()),
5997                            /*IsStringLocation*/true, R,
5998                            FixItHint::CreateRemoval(R));
5999     }
6000   }
6001 
6002   if (!FS.consumesDataArgument()) {
6003     // FIXME: Technically specifying a precision or field width here
6004     // makes no sense.  Worth issuing a warning at some point.
6005     return true;
6006   }
6007 
6008   // Consume the argument.
6009   unsigned argIndex = FS.getArgIndex();
6010   if (argIndex < NumDataArgs) {
6011       // The check to see if the argIndex is valid will come later.
6012       // We set the bit here because we may exit early from this
6013       // function if we encounter some other error.
6014     CoveredArgs.set(argIndex);
6015   }
6016 
6017   // Check the length modifier is valid with the given conversion specifier.
6018   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6019     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6020                                 diag::warn_format_nonsensical_length);
6021   else if (!FS.hasStandardLengthModifier())
6022     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6023   else if (!FS.hasStandardLengthConversionCombination())
6024     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6025                                 diag::warn_format_non_standard_conversion_spec);
6026 
6027   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6028     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6029 
6030   // The remaining checks depend on the data arguments.
6031   if (HasVAListArg)
6032     return true;
6033 
6034   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6035     return false;
6036 
6037   // Check that the argument type matches the format specifier.
6038   const Expr *Ex = getDataArg(argIndex);
6039   if (!Ex)
6040     return true;
6041 
6042   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6043 
6044   if (!AT.isValid()) {
6045     return true;
6046   }
6047 
6048   analyze_format_string::ArgType::MatchKind match =
6049       AT.matchesType(S.Context, Ex->getType());
6050   if (match == analyze_format_string::ArgType::Match) {
6051     return true;
6052   }
6053 
6054   ScanfSpecifier fixedFS = FS;
6055   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6056                                  S.getLangOpts(), S.Context);
6057 
6058   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6059   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6060     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6061   }
6062 
6063   if (success) {
6064     // Get the fix string from the fixed format specifier.
6065     SmallString<128> buf;
6066     llvm::raw_svector_ostream os(buf);
6067     fixedFS.toString(os);
6068 
6069     EmitFormatDiagnostic(
6070         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6071                       << Ex->getType() << false << Ex->getSourceRange(),
6072         Ex->getLocStart(),
6073         /*IsStringLocation*/ false,
6074         getSpecifierRange(startSpecifier, specifierLen),
6075         FixItHint::CreateReplacement(
6076             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6077   } else {
6078     EmitFormatDiagnostic(S.PDiag(diag)
6079                              << AT.getRepresentativeTypeName(S.Context)
6080                              << Ex->getType() << false << Ex->getSourceRange(),
6081                          Ex->getLocStart(),
6082                          /*IsStringLocation*/ false,
6083                          getSpecifierRange(startSpecifier, specifierLen));
6084   }
6085 
6086   return true;
6087 }
6088 
6089 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6090                               const Expr *OrigFormatExpr,
6091                               ArrayRef<const Expr *> Args,
6092                               bool HasVAListArg, unsigned format_idx,
6093                               unsigned firstDataArg,
6094                               Sema::FormatStringType Type,
6095                               bool inFunctionCall,
6096                               Sema::VariadicCallType CallType,
6097                               llvm::SmallBitVector &CheckedVarArgs,
6098                               UncoveredArgHandler &UncoveredArg) {
6099   // CHECK: is the format string a wide literal?
6100   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6101     CheckFormatHandler::EmitFormatDiagnostic(
6102       S, inFunctionCall, Args[format_idx],
6103       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6104       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6105     return;
6106   }
6107 
6108   // Str - The format string.  NOTE: this is NOT null-terminated!
6109   StringRef StrRef = FExpr->getString();
6110   const char *Str = StrRef.data();
6111   // Account for cases where the string literal is truncated in a declaration.
6112   const ConstantArrayType *T =
6113     S.Context.getAsConstantArrayType(FExpr->getType());
6114   assert(T && "String literal not of constant array type!");
6115   size_t TypeSize = T->getSize().getZExtValue();
6116   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6117   const unsigned numDataArgs = Args.size() - firstDataArg;
6118 
6119   // Emit a warning if the string literal is truncated and does not contain an
6120   // embedded null character.
6121   if (TypeSize <= StrRef.size() &&
6122       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6123     CheckFormatHandler::EmitFormatDiagnostic(
6124         S, inFunctionCall, Args[format_idx],
6125         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6126         FExpr->getLocStart(),
6127         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6128     return;
6129   }
6130 
6131   // CHECK: empty format string?
6132   if (StrLen == 0 && numDataArgs > 0) {
6133     CheckFormatHandler::EmitFormatDiagnostic(
6134       S, inFunctionCall, Args[format_idx],
6135       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6136       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6137     return;
6138   }
6139 
6140   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6141       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
6142     CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
6143                          numDataArgs, (Type == Sema::FST_NSString ||
6144                                        Type == Sema::FST_OSTrace),
6145                          Str, HasVAListArg, Args, format_idx,
6146                          inFunctionCall, CallType, CheckedVarArgs,
6147                          UncoveredArg);
6148 
6149     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6150                                                   S.getLangOpts(),
6151                                                   S.Context.getTargetInfo(),
6152                                             Type == Sema::FST_FreeBSDKPrintf))
6153       H.DoneProcessing();
6154   } else if (Type == Sema::FST_Scanf) {
6155     CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
6156                         Str, HasVAListArg, Args, format_idx,
6157                         inFunctionCall, CallType, CheckedVarArgs,
6158                         UncoveredArg);
6159 
6160     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6161                                                  S.getLangOpts(),
6162                                                  S.Context.getTargetInfo()))
6163       H.DoneProcessing();
6164   } // TODO: handle other formats
6165 }
6166 
6167 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6168   // Str - The format string.  NOTE: this is NOT null-terminated!
6169   StringRef StrRef = FExpr->getString();
6170   const char *Str = StrRef.data();
6171   // Account for cases where the string literal is truncated in a declaration.
6172   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6173   assert(T && "String literal not of constant array type!");
6174   size_t TypeSize = T->getSize().getZExtValue();
6175   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6176   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6177                                                          getLangOpts(),
6178                                                          Context.getTargetInfo());
6179 }
6180 
6181 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6182 
6183 // Returns the related absolute value function that is larger, of 0 if one
6184 // does not exist.
6185 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6186   switch (AbsFunction) {
6187   default:
6188     return 0;
6189 
6190   case Builtin::BI__builtin_abs:
6191     return Builtin::BI__builtin_labs;
6192   case Builtin::BI__builtin_labs:
6193     return Builtin::BI__builtin_llabs;
6194   case Builtin::BI__builtin_llabs:
6195     return 0;
6196 
6197   case Builtin::BI__builtin_fabsf:
6198     return Builtin::BI__builtin_fabs;
6199   case Builtin::BI__builtin_fabs:
6200     return Builtin::BI__builtin_fabsl;
6201   case Builtin::BI__builtin_fabsl:
6202     return 0;
6203 
6204   case Builtin::BI__builtin_cabsf:
6205     return Builtin::BI__builtin_cabs;
6206   case Builtin::BI__builtin_cabs:
6207     return Builtin::BI__builtin_cabsl;
6208   case Builtin::BI__builtin_cabsl:
6209     return 0;
6210 
6211   case Builtin::BIabs:
6212     return Builtin::BIlabs;
6213   case Builtin::BIlabs:
6214     return Builtin::BIllabs;
6215   case Builtin::BIllabs:
6216     return 0;
6217 
6218   case Builtin::BIfabsf:
6219     return Builtin::BIfabs;
6220   case Builtin::BIfabs:
6221     return Builtin::BIfabsl;
6222   case Builtin::BIfabsl:
6223     return 0;
6224 
6225   case Builtin::BIcabsf:
6226    return Builtin::BIcabs;
6227   case Builtin::BIcabs:
6228     return Builtin::BIcabsl;
6229   case Builtin::BIcabsl:
6230     return 0;
6231   }
6232 }
6233 
6234 // Returns the argument type of the absolute value function.
6235 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6236                                              unsigned AbsType) {
6237   if (AbsType == 0)
6238     return QualType();
6239 
6240   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6241   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6242   if (Error != ASTContext::GE_None)
6243     return QualType();
6244 
6245   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6246   if (!FT)
6247     return QualType();
6248 
6249   if (FT->getNumParams() != 1)
6250     return QualType();
6251 
6252   return FT->getParamType(0);
6253 }
6254 
6255 // Returns the best absolute value function, or zero, based on type and
6256 // current absolute value function.
6257 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6258                                    unsigned AbsFunctionKind) {
6259   unsigned BestKind = 0;
6260   uint64_t ArgSize = Context.getTypeSize(ArgType);
6261   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6262        Kind = getLargerAbsoluteValueFunction(Kind)) {
6263     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6264     if (Context.getTypeSize(ParamType) >= ArgSize) {
6265       if (BestKind == 0)
6266         BestKind = Kind;
6267       else if (Context.hasSameType(ParamType, ArgType)) {
6268         BestKind = Kind;
6269         break;
6270       }
6271     }
6272   }
6273   return BestKind;
6274 }
6275 
6276 enum AbsoluteValueKind {
6277   AVK_Integer,
6278   AVK_Floating,
6279   AVK_Complex
6280 };
6281 
6282 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6283   if (T->isIntegralOrEnumerationType())
6284     return AVK_Integer;
6285   if (T->isRealFloatingType())
6286     return AVK_Floating;
6287   if (T->isAnyComplexType())
6288     return AVK_Complex;
6289 
6290   llvm_unreachable("Type not integer, floating, or complex");
6291 }
6292 
6293 // Changes the absolute value function to a different type.  Preserves whether
6294 // the function is a builtin.
6295 static unsigned changeAbsFunction(unsigned AbsKind,
6296                                   AbsoluteValueKind ValueKind) {
6297   switch (ValueKind) {
6298   case AVK_Integer:
6299     switch (AbsKind) {
6300     default:
6301       return 0;
6302     case Builtin::BI__builtin_fabsf:
6303     case Builtin::BI__builtin_fabs:
6304     case Builtin::BI__builtin_fabsl:
6305     case Builtin::BI__builtin_cabsf:
6306     case Builtin::BI__builtin_cabs:
6307     case Builtin::BI__builtin_cabsl:
6308       return Builtin::BI__builtin_abs;
6309     case Builtin::BIfabsf:
6310     case Builtin::BIfabs:
6311     case Builtin::BIfabsl:
6312     case Builtin::BIcabsf:
6313     case Builtin::BIcabs:
6314     case Builtin::BIcabsl:
6315       return Builtin::BIabs;
6316     }
6317   case AVK_Floating:
6318     switch (AbsKind) {
6319     default:
6320       return 0;
6321     case Builtin::BI__builtin_abs:
6322     case Builtin::BI__builtin_labs:
6323     case Builtin::BI__builtin_llabs:
6324     case Builtin::BI__builtin_cabsf:
6325     case Builtin::BI__builtin_cabs:
6326     case Builtin::BI__builtin_cabsl:
6327       return Builtin::BI__builtin_fabsf;
6328     case Builtin::BIabs:
6329     case Builtin::BIlabs:
6330     case Builtin::BIllabs:
6331     case Builtin::BIcabsf:
6332     case Builtin::BIcabs:
6333     case Builtin::BIcabsl:
6334       return Builtin::BIfabsf;
6335     }
6336   case AVK_Complex:
6337     switch (AbsKind) {
6338     default:
6339       return 0;
6340     case Builtin::BI__builtin_abs:
6341     case Builtin::BI__builtin_labs:
6342     case Builtin::BI__builtin_llabs:
6343     case Builtin::BI__builtin_fabsf:
6344     case Builtin::BI__builtin_fabs:
6345     case Builtin::BI__builtin_fabsl:
6346       return Builtin::BI__builtin_cabsf;
6347     case Builtin::BIabs:
6348     case Builtin::BIlabs:
6349     case Builtin::BIllabs:
6350     case Builtin::BIfabsf:
6351     case Builtin::BIfabs:
6352     case Builtin::BIfabsl:
6353       return Builtin::BIcabsf;
6354     }
6355   }
6356   llvm_unreachable("Unable to convert function");
6357 }
6358 
6359 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6360   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6361   if (!FnInfo)
6362     return 0;
6363 
6364   switch (FDecl->getBuiltinID()) {
6365   default:
6366     return 0;
6367   case Builtin::BI__builtin_abs:
6368   case Builtin::BI__builtin_fabs:
6369   case Builtin::BI__builtin_fabsf:
6370   case Builtin::BI__builtin_fabsl:
6371   case Builtin::BI__builtin_labs:
6372   case Builtin::BI__builtin_llabs:
6373   case Builtin::BI__builtin_cabs:
6374   case Builtin::BI__builtin_cabsf:
6375   case Builtin::BI__builtin_cabsl:
6376   case Builtin::BIabs:
6377   case Builtin::BIlabs:
6378   case Builtin::BIllabs:
6379   case Builtin::BIfabs:
6380   case Builtin::BIfabsf:
6381   case Builtin::BIfabsl:
6382   case Builtin::BIcabs:
6383   case Builtin::BIcabsf:
6384   case Builtin::BIcabsl:
6385     return FDecl->getBuiltinID();
6386   }
6387   llvm_unreachable("Unknown Builtin type");
6388 }
6389 
6390 // If the replacement is valid, emit a note with replacement function.
6391 // Additionally, suggest including the proper header if not already included.
6392 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6393                             unsigned AbsKind, QualType ArgType) {
6394   bool EmitHeaderHint = true;
6395   const char *HeaderName = nullptr;
6396   const char *FunctionName = nullptr;
6397   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6398     FunctionName = "std::abs";
6399     if (ArgType->isIntegralOrEnumerationType()) {
6400       HeaderName = "cstdlib";
6401     } else if (ArgType->isRealFloatingType()) {
6402       HeaderName = "cmath";
6403     } else {
6404       llvm_unreachable("Invalid Type");
6405     }
6406 
6407     // Lookup all std::abs
6408     if (NamespaceDecl *Std = S.getStdNamespace()) {
6409       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6410       R.suppressDiagnostics();
6411       S.LookupQualifiedName(R, Std);
6412 
6413       for (const auto *I : R) {
6414         const FunctionDecl *FDecl = nullptr;
6415         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6416           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6417         } else {
6418           FDecl = dyn_cast<FunctionDecl>(I);
6419         }
6420         if (!FDecl)
6421           continue;
6422 
6423         // Found std::abs(), check that they are the right ones.
6424         if (FDecl->getNumParams() != 1)
6425           continue;
6426 
6427         // Check that the parameter type can handle the argument.
6428         QualType ParamType = FDecl->getParamDecl(0)->getType();
6429         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6430             S.Context.getTypeSize(ArgType) <=
6431                 S.Context.getTypeSize(ParamType)) {
6432           // Found a function, don't need the header hint.
6433           EmitHeaderHint = false;
6434           break;
6435         }
6436       }
6437     }
6438   } else {
6439     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6440     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6441 
6442     if (HeaderName) {
6443       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6444       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6445       R.suppressDiagnostics();
6446       S.LookupName(R, S.getCurScope());
6447 
6448       if (R.isSingleResult()) {
6449         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6450         if (FD && FD->getBuiltinID() == AbsKind) {
6451           EmitHeaderHint = false;
6452         } else {
6453           return;
6454         }
6455       } else if (!R.empty()) {
6456         return;
6457       }
6458     }
6459   }
6460 
6461   S.Diag(Loc, diag::note_replace_abs_function)
6462       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6463 
6464   if (!HeaderName)
6465     return;
6466 
6467   if (!EmitHeaderHint)
6468     return;
6469 
6470   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6471                                                     << FunctionName;
6472 }
6473 
6474 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6475   if (!FDecl)
6476     return false;
6477 
6478   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6479     return false;
6480 
6481   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6482 
6483   while (ND && ND->isInlineNamespace()) {
6484     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
6485   }
6486 
6487   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6488     return false;
6489 
6490   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6491     return false;
6492 
6493   return true;
6494 }
6495 
6496 // Warn when using the wrong abs() function.
6497 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6498                                       const FunctionDecl *FDecl,
6499                                       IdentifierInfo *FnInfo) {
6500   if (Call->getNumArgs() != 1)
6501     return;
6502 
6503   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6504   bool IsStdAbs = IsFunctionStdAbs(FDecl);
6505   if (AbsKind == 0 && !IsStdAbs)
6506     return;
6507 
6508   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6509   QualType ParamType = Call->getArg(0)->getType();
6510 
6511   // Unsigned types cannot be negative.  Suggest removing the absolute value
6512   // function call.
6513   if (ArgType->isUnsignedIntegerType()) {
6514     const char *FunctionName =
6515         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6516     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6517     Diag(Call->getExprLoc(), diag::note_remove_abs)
6518         << FunctionName
6519         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6520     return;
6521   }
6522 
6523   // Taking the absolute value of a pointer is very suspicious, they probably
6524   // wanted to index into an array, dereference a pointer, call a function, etc.
6525   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6526     unsigned DiagType = 0;
6527     if (ArgType->isFunctionType())
6528       DiagType = 1;
6529     else if (ArgType->isArrayType())
6530       DiagType = 2;
6531 
6532     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6533     return;
6534   }
6535 
6536   // std::abs has overloads which prevent most of the absolute value problems
6537   // from occurring.
6538   if (IsStdAbs)
6539     return;
6540 
6541   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6542   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6543 
6544   // The argument and parameter are the same kind.  Check if they are the right
6545   // size.
6546   if (ArgValueKind == ParamValueKind) {
6547     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6548       return;
6549 
6550     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6551     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6552         << FDecl << ArgType << ParamType;
6553 
6554     if (NewAbsKind == 0)
6555       return;
6556 
6557     emitReplacement(*this, Call->getExprLoc(),
6558                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6559     return;
6560   }
6561 
6562   // ArgValueKind != ParamValueKind
6563   // The wrong type of absolute value function was used.  Attempt to find the
6564   // proper one.
6565   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6566   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6567   if (NewAbsKind == 0)
6568     return;
6569 
6570   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6571       << FDecl << ParamValueKind << ArgValueKind;
6572 
6573   emitReplacement(*this, Call->getExprLoc(),
6574                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6575 }
6576 
6577 //===--- CHECK: Standard memory functions ---------------------------------===//
6578 
6579 /// \brief Takes the expression passed to the size_t parameter of functions
6580 /// such as memcmp, strncat, etc and warns if it's a comparison.
6581 ///
6582 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6583 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6584                                            IdentifierInfo *FnName,
6585                                            SourceLocation FnLoc,
6586                                            SourceLocation RParenLoc) {
6587   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6588   if (!Size)
6589     return false;
6590 
6591   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6592   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6593     return false;
6594 
6595   SourceRange SizeRange = Size->getSourceRange();
6596   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6597       << SizeRange << FnName;
6598   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6599       << FnName << FixItHint::CreateInsertion(
6600                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6601       << FixItHint::CreateRemoval(RParenLoc);
6602   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6603       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6604       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6605                                     ")");
6606 
6607   return true;
6608 }
6609 
6610 /// \brief Determine whether the given type is or contains a dynamic class type
6611 /// (e.g., whether it has a vtable).
6612 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6613                                                      bool &IsContained) {
6614   // Look through array types while ignoring qualifiers.
6615   const Type *Ty = T->getBaseElementTypeUnsafe();
6616   IsContained = false;
6617 
6618   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6619   RD = RD ? RD->getDefinition() : nullptr;
6620   if (!RD || RD->isInvalidDecl())
6621     return nullptr;
6622 
6623   if (RD->isDynamicClass())
6624     return RD;
6625 
6626   // Check all the fields.  If any bases were dynamic, the class is dynamic.
6627   // It's impossible for a class to transitively contain itself by value, so
6628   // infinite recursion is impossible.
6629   for (auto *FD : RD->fields()) {
6630     bool SubContained;
6631     if (const CXXRecordDecl *ContainedRD =
6632             getContainedDynamicClass(FD->getType(), SubContained)) {
6633       IsContained = true;
6634       return ContainedRD;
6635     }
6636   }
6637 
6638   return nullptr;
6639 }
6640 
6641 /// \brief If E is a sizeof expression, returns its argument expression,
6642 /// otherwise returns NULL.
6643 static const Expr *getSizeOfExprArg(const Expr *E) {
6644   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6645       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6646     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6647       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6648 
6649   return nullptr;
6650 }
6651 
6652 /// \brief If E is a sizeof expression, returns its argument type.
6653 static QualType getSizeOfArgType(const Expr *E) {
6654   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6655       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6656     if (SizeOf->getKind() == clang::UETT_SizeOf)
6657       return SizeOf->getTypeOfArgument();
6658 
6659   return QualType();
6660 }
6661 
6662 /// \brief Check for dangerous or invalid arguments to memset().
6663 ///
6664 /// This issues warnings on known problematic, dangerous or unspecified
6665 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6666 /// function calls.
6667 ///
6668 /// \param Call The call expression to diagnose.
6669 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6670                                    unsigned BId,
6671                                    IdentifierInfo *FnName) {
6672   assert(BId != 0);
6673 
6674   // It is possible to have a non-standard definition of memset.  Validate
6675   // we have enough arguments, and if not, abort further checking.
6676   unsigned ExpectedNumArgs =
6677       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6678   if (Call->getNumArgs() < ExpectedNumArgs)
6679     return;
6680 
6681   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6682                       BId == Builtin::BIstrndup ? 1 : 2);
6683   unsigned LenArg =
6684       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6685   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6686 
6687   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6688                                      Call->getLocStart(), Call->getRParenLoc()))
6689     return;
6690 
6691   // We have special checking when the length is a sizeof expression.
6692   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6693   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6694   llvm::FoldingSetNodeID SizeOfArgID;
6695 
6696   // Although widely used, 'bzero' is not a standard function. Be more strict
6697   // with the argument types before allowing diagnostics and only allow the
6698   // form bzero(ptr, sizeof(...)).
6699   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6700   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6701     return;
6702 
6703   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6704     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6705     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6706 
6707     QualType DestTy = Dest->getType();
6708     QualType PointeeTy;
6709     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6710       PointeeTy = DestPtrTy->getPointeeType();
6711 
6712       // Never warn about void type pointers. This can be used to suppress
6713       // false positives.
6714       if (PointeeTy->isVoidType())
6715         continue;
6716 
6717       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6718       // actually comparing the expressions for equality. Because computing the
6719       // expression IDs can be expensive, we only do this if the diagnostic is
6720       // enabled.
6721       if (SizeOfArg &&
6722           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6723                            SizeOfArg->getExprLoc())) {
6724         // We only compute IDs for expressions if the warning is enabled, and
6725         // cache the sizeof arg's ID.
6726         if (SizeOfArgID == llvm::FoldingSetNodeID())
6727           SizeOfArg->Profile(SizeOfArgID, Context, true);
6728         llvm::FoldingSetNodeID DestID;
6729         Dest->Profile(DestID, Context, true);
6730         if (DestID == SizeOfArgID) {
6731           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6732           //       over sizeof(src) as well.
6733           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6734           StringRef ReadableName = FnName->getName();
6735 
6736           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6737             if (UnaryOp->getOpcode() == UO_AddrOf)
6738               ActionIdx = 1; // If its an address-of operator, just remove it.
6739           if (!PointeeTy->isIncompleteType() &&
6740               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6741             ActionIdx = 2; // If the pointee's size is sizeof(char),
6742                            // suggest an explicit length.
6743 
6744           // If the function is defined as a builtin macro, do not show macro
6745           // expansion.
6746           SourceLocation SL = SizeOfArg->getExprLoc();
6747           SourceRange DSR = Dest->getSourceRange();
6748           SourceRange SSR = SizeOfArg->getSourceRange();
6749           SourceManager &SM = getSourceManager();
6750 
6751           if (SM.isMacroArgExpansion(SL)) {
6752             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6753             SL = SM.getSpellingLoc(SL);
6754             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6755                              SM.getSpellingLoc(DSR.getEnd()));
6756             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6757                              SM.getSpellingLoc(SSR.getEnd()));
6758           }
6759 
6760           DiagRuntimeBehavior(SL, SizeOfArg,
6761                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6762                                 << ReadableName
6763                                 << PointeeTy
6764                                 << DestTy
6765                                 << DSR
6766                                 << SSR);
6767           DiagRuntimeBehavior(SL, SizeOfArg,
6768                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6769                                 << ActionIdx
6770                                 << SSR);
6771 
6772           break;
6773         }
6774       }
6775 
6776       // Also check for cases where the sizeof argument is the exact same
6777       // type as the memory argument, and where it points to a user-defined
6778       // record type.
6779       if (SizeOfArgTy != QualType()) {
6780         if (PointeeTy->isRecordType() &&
6781             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6782           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6783                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
6784                                 << FnName << SizeOfArgTy << ArgIdx
6785                                 << PointeeTy << Dest->getSourceRange()
6786                                 << LenExpr->getSourceRange());
6787           break;
6788         }
6789       }
6790     } else if (DestTy->isArrayType()) {
6791       PointeeTy = DestTy;
6792     }
6793 
6794     if (PointeeTy == QualType())
6795       continue;
6796 
6797     // Always complain about dynamic classes.
6798     bool IsContained;
6799     if (const CXXRecordDecl *ContainedRD =
6800             getContainedDynamicClass(PointeeTy, IsContained)) {
6801 
6802       unsigned OperationType = 0;
6803       // "overwritten" if we're warning about the destination for any call
6804       // but memcmp; otherwise a verb appropriate to the call.
6805       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6806         if (BId == Builtin::BImemcpy)
6807           OperationType = 1;
6808         else if(BId == Builtin::BImemmove)
6809           OperationType = 2;
6810         else if (BId == Builtin::BImemcmp)
6811           OperationType = 3;
6812       }
6813 
6814       DiagRuntimeBehavior(
6815         Dest->getExprLoc(), Dest,
6816         PDiag(diag::warn_dyn_class_memaccess)
6817           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6818           << FnName << IsContained << ContainedRD << OperationType
6819           << Call->getCallee()->getSourceRange());
6820     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6821              BId != Builtin::BImemset)
6822       DiagRuntimeBehavior(
6823         Dest->getExprLoc(), Dest,
6824         PDiag(diag::warn_arc_object_memaccess)
6825           << ArgIdx << FnName << PointeeTy
6826           << Call->getCallee()->getSourceRange());
6827     else
6828       continue;
6829 
6830     DiagRuntimeBehavior(
6831       Dest->getExprLoc(), Dest,
6832       PDiag(diag::note_bad_memaccess_silence)
6833         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6834     break;
6835   }
6836 }
6837 
6838 // A little helper routine: ignore addition and subtraction of integer literals.
6839 // This intentionally does not ignore all integer constant expressions because
6840 // we don't want to remove sizeof().
6841 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6842   Ex = Ex->IgnoreParenCasts();
6843 
6844   for (;;) {
6845     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6846     if (!BO || !BO->isAdditiveOp())
6847       break;
6848 
6849     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6850     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6851 
6852     if (isa<IntegerLiteral>(RHS))
6853       Ex = LHS;
6854     else if (isa<IntegerLiteral>(LHS))
6855       Ex = RHS;
6856     else
6857       break;
6858   }
6859 
6860   return Ex;
6861 }
6862 
6863 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6864                                                       ASTContext &Context) {
6865   // Only handle constant-sized or VLAs, but not flexible members.
6866   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6867     // Only issue the FIXIT for arrays of size > 1.
6868     if (CAT->getSize().getSExtValue() <= 1)
6869       return false;
6870   } else if (!Ty->isVariableArrayType()) {
6871     return false;
6872   }
6873   return true;
6874 }
6875 
6876 // Warn if the user has made the 'size' argument to strlcpy or strlcat
6877 // be the size of the source, instead of the destination.
6878 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6879                                     IdentifierInfo *FnName) {
6880 
6881   // Don't crash if the user has the wrong number of arguments
6882   unsigned NumArgs = Call->getNumArgs();
6883   if ((NumArgs != 3) && (NumArgs != 4))
6884     return;
6885 
6886   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6887   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
6888   const Expr *CompareWithSrc = nullptr;
6889 
6890   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6891                                      Call->getLocStart(), Call->getRParenLoc()))
6892     return;
6893 
6894   // Look for 'strlcpy(dst, x, sizeof(x))'
6895   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6896     CompareWithSrc = Ex;
6897   else {
6898     // Look for 'strlcpy(dst, x, strlen(x))'
6899     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
6900       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6901           SizeCall->getNumArgs() == 1)
6902         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6903     }
6904   }
6905 
6906   if (!CompareWithSrc)
6907     return;
6908 
6909   // Determine if the argument to sizeof/strlen is equal to the source
6910   // argument.  In principle there's all kinds of things you could do
6911   // here, for instance creating an == expression and evaluating it with
6912   // EvaluateAsBooleanCondition, but this uses a more direct technique:
6913   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6914   if (!SrcArgDRE)
6915     return;
6916 
6917   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6918   if (!CompareWithSrcDRE ||
6919       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6920     return;
6921 
6922   const Expr *OriginalSizeArg = Call->getArg(2);
6923   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6924     << OriginalSizeArg->getSourceRange() << FnName;
6925 
6926   // Output a FIXIT hint if the destination is an array (rather than a
6927   // pointer to an array).  This could be enhanced to handle some
6928   // pointers if we know the actual size, like if DstArg is 'array+2'
6929   // we could say 'sizeof(array)-2'.
6930   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
6931   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
6932     return;
6933 
6934   SmallString<128> sizeString;
6935   llvm::raw_svector_ostream OS(sizeString);
6936   OS << "sizeof(";
6937   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6938   OS << ")";
6939 
6940   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6941     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6942                                     OS.str());
6943 }
6944 
6945 /// Check if two expressions refer to the same declaration.
6946 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6947   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6948     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6949       return D1->getDecl() == D2->getDecl();
6950   return false;
6951 }
6952 
6953 static const Expr *getStrlenExprArg(const Expr *E) {
6954   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6955     const FunctionDecl *FD = CE->getDirectCallee();
6956     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
6957       return nullptr;
6958     return CE->getArg(0)->IgnoreParenCasts();
6959   }
6960   return nullptr;
6961 }
6962 
6963 // Warn on anti-patterns as the 'size' argument to strncat.
6964 // The correct size argument should look like following:
6965 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6966 void Sema::CheckStrncatArguments(const CallExpr *CE,
6967                                  IdentifierInfo *FnName) {
6968   // Don't crash if the user has the wrong number of arguments.
6969   if (CE->getNumArgs() < 3)
6970     return;
6971   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6972   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6973   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6974 
6975   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6976                                      CE->getRParenLoc()))
6977     return;
6978 
6979   // Identify common expressions, which are wrongly used as the size argument
6980   // to strncat and may lead to buffer overflows.
6981   unsigned PatternType = 0;
6982   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6983     // - sizeof(dst)
6984     if (referToTheSameDecl(SizeOfArg, DstArg))
6985       PatternType = 1;
6986     // - sizeof(src)
6987     else if (referToTheSameDecl(SizeOfArg, SrcArg))
6988       PatternType = 2;
6989   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6990     if (BE->getOpcode() == BO_Sub) {
6991       const Expr *L = BE->getLHS()->IgnoreParenCasts();
6992       const Expr *R = BE->getRHS()->IgnoreParenCasts();
6993       // - sizeof(dst) - strlen(dst)
6994       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6995           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6996         PatternType = 1;
6997       // - sizeof(src) - (anything)
6998       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6999         PatternType = 2;
7000     }
7001   }
7002 
7003   if (PatternType == 0)
7004     return;
7005 
7006   // Generate the diagnostic.
7007   SourceLocation SL = LenArg->getLocStart();
7008   SourceRange SR = LenArg->getSourceRange();
7009   SourceManager &SM = getSourceManager();
7010 
7011   // If the function is defined as a builtin macro, do not show macro expansion.
7012   if (SM.isMacroArgExpansion(SL)) {
7013     SL = SM.getSpellingLoc(SL);
7014     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7015                      SM.getSpellingLoc(SR.getEnd()));
7016   }
7017 
7018   // Check if the destination is an array (rather than a pointer to an array).
7019   QualType DstTy = DstArg->getType();
7020   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7021                                                                     Context);
7022   if (!isKnownSizeArray) {
7023     if (PatternType == 1)
7024       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7025     else
7026       Diag(SL, diag::warn_strncat_src_size) << SR;
7027     return;
7028   }
7029 
7030   if (PatternType == 1)
7031     Diag(SL, diag::warn_strncat_large_size) << SR;
7032   else
7033     Diag(SL, diag::warn_strncat_src_size) << SR;
7034 
7035   SmallString<128> sizeString;
7036   llvm::raw_svector_ostream OS(sizeString);
7037   OS << "sizeof(";
7038   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7039   OS << ") - ";
7040   OS << "strlen(";
7041   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7042   OS << ") - 1";
7043 
7044   Diag(SL, diag::note_strncat_wrong_size)
7045     << FixItHint::CreateReplacement(SR, OS.str());
7046 }
7047 
7048 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7049 
7050 static const Expr *EvalVal(const Expr *E,
7051                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7052                            const Decl *ParentDecl);
7053 static const Expr *EvalAddr(const Expr *E,
7054                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7055                             const Decl *ParentDecl);
7056 
7057 /// CheckReturnStackAddr - Check if a return statement returns the address
7058 ///   of a stack variable.
7059 static void
7060 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7061                      SourceLocation ReturnLoc) {
7062 
7063   const Expr *stackE = nullptr;
7064   SmallVector<const DeclRefExpr *, 8> refVars;
7065 
7066   // Perform checking for returned stack addresses, local blocks,
7067   // label addresses or references to temporaries.
7068   if (lhsType->isPointerType() ||
7069       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7070     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7071   } else if (lhsType->isReferenceType()) {
7072     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7073   }
7074 
7075   if (!stackE)
7076     return; // Nothing suspicious was found.
7077 
7078   // Parameters are initalized in the calling scope, so taking the address
7079   // of a parameter reference doesn't need a warning.
7080   for (auto *DRE : refVars)
7081     if (isa<ParmVarDecl>(DRE->getDecl()))
7082       return;
7083 
7084   SourceLocation diagLoc;
7085   SourceRange diagRange;
7086   if (refVars.empty()) {
7087     diagLoc = stackE->getLocStart();
7088     diagRange = stackE->getSourceRange();
7089   } else {
7090     // We followed through a reference variable. 'stackE' contains the
7091     // problematic expression but we will warn at the return statement pointing
7092     // at the reference variable. We will later display the "trail" of
7093     // reference variables using notes.
7094     diagLoc = refVars[0]->getLocStart();
7095     diagRange = refVars[0]->getSourceRange();
7096   }
7097 
7098   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7099     // address of local var
7100     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7101      << DR->getDecl()->getDeclName() << diagRange;
7102   } else if (isa<BlockExpr>(stackE)) { // local block.
7103     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7104   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7105     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7106   } else { // local temporary.
7107     // If there is an LValue->RValue conversion, then the value of the
7108     // reference type is used, not the reference.
7109     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7110       if (ICE->getCastKind() == CK_LValueToRValue) {
7111         return;
7112       }
7113     }
7114     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7115      << lhsType->isReferenceType() << diagRange;
7116   }
7117 
7118   // Display the "trail" of reference variables that we followed until we
7119   // found the problematic expression using notes.
7120   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7121     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7122     // If this var binds to another reference var, show the range of the next
7123     // var, otherwise the var binds to the problematic expression, in which case
7124     // show the range of the expression.
7125     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7126                                     : stackE->getSourceRange();
7127     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7128         << VD->getDeclName() << range;
7129   }
7130 }
7131 
7132 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7133 ///  check if the expression in a return statement evaluates to an address
7134 ///  to a location on the stack, a local block, an address of a label, or a
7135 ///  reference to local temporary. The recursion is used to traverse the
7136 ///  AST of the return expression, with recursion backtracking when we
7137 ///  encounter a subexpression that (1) clearly does not lead to one of the
7138 ///  above problematic expressions (2) is something we cannot determine leads to
7139 ///  a problematic expression based on such local checking.
7140 ///
7141 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7142 ///  the expression that they point to. Such variables are added to the
7143 ///  'refVars' vector so that we know what the reference variable "trail" was.
7144 ///
7145 ///  EvalAddr processes expressions that are pointers that are used as
7146 ///  references (and not L-values).  EvalVal handles all other values.
7147 ///  At the base case of the recursion is a check for the above problematic
7148 ///  expressions.
7149 ///
7150 ///  This implementation handles:
7151 ///
7152 ///   * pointer-to-pointer casts
7153 ///   * implicit conversions from array references to pointers
7154 ///   * taking the address of fields
7155 ///   * arbitrary interplay between "&" and "*" operators
7156 ///   * pointer arithmetic from an address of a stack variable
7157 ///   * taking the address of an array element where the array is on the stack
7158 static const Expr *EvalAddr(const Expr *E,
7159                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7160                             const Decl *ParentDecl) {
7161   if (E->isTypeDependent())
7162     return nullptr;
7163 
7164   // We should only be called for evaluating pointer expressions.
7165   assert((E->getType()->isAnyPointerType() ||
7166           E->getType()->isBlockPointerType() ||
7167           E->getType()->isObjCQualifiedIdType()) &&
7168          "EvalAddr only works on pointers");
7169 
7170   E = E->IgnoreParens();
7171 
7172   // Our "symbolic interpreter" is just a dispatch off the currently
7173   // viewed AST node.  We then recursively traverse the AST by calling
7174   // EvalAddr and EvalVal appropriately.
7175   switch (E->getStmtClass()) {
7176   case Stmt::DeclRefExprClass: {
7177     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7178 
7179     // If we leave the immediate function, the lifetime isn't about to end.
7180     if (DR->refersToEnclosingVariableOrCapture())
7181       return nullptr;
7182 
7183     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7184       // If this is a reference variable, follow through to the expression that
7185       // it points to.
7186       if (V->hasLocalStorage() &&
7187           V->getType()->isReferenceType() && V->hasInit()) {
7188         // Add the reference variable to the "trail".
7189         refVars.push_back(DR);
7190         return EvalAddr(V->getInit(), refVars, ParentDecl);
7191       }
7192 
7193     return nullptr;
7194   }
7195 
7196   case Stmt::UnaryOperatorClass: {
7197     // The only unary operator that make sense to handle here
7198     // is AddrOf.  All others don't make sense as pointers.
7199     const UnaryOperator *U = cast<UnaryOperator>(E);
7200 
7201     if (U->getOpcode() == UO_AddrOf)
7202       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7203     return nullptr;
7204   }
7205 
7206   case Stmt::BinaryOperatorClass: {
7207     // Handle pointer arithmetic.  All other binary operators are not valid
7208     // in this context.
7209     const BinaryOperator *B = cast<BinaryOperator>(E);
7210     BinaryOperatorKind op = B->getOpcode();
7211 
7212     if (op != BO_Add && op != BO_Sub)
7213       return nullptr;
7214 
7215     const Expr *Base = B->getLHS();
7216 
7217     // Determine which argument is the real pointer base.  It could be
7218     // the RHS argument instead of the LHS.
7219     if (!Base->getType()->isPointerType())
7220       Base = B->getRHS();
7221 
7222     assert(Base->getType()->isPointerType());
7223     return EvalAddr(Base, refVars, ParentDecl);
7224   }
7225 
7226   // For conditional operators we need to see if either the LHS or RHS are
7227   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7228   case Stmt::ConditionalOperatorClass: {
7229     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7230 
7231     // Handle the GNU extension for missing LHS.
7232     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7233     if (const Expr *LHSExpr = C->getLHS()) {
7234       // In C++, we can have a throw-expression, which has 'void' type.
7235       if (!LHSExpr->getType()->isVoidType())
7236         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7237           return LHS;
7238     }
7239 
7240     // In C++, we can have a throw-expression, which has 'void' type.
7241     if (C->getRHS()->getType()->isVoidType())
7242       return nullptr;
7243 
7244     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7245   }
7246 
7247   case Stmt::BlockExprClass:
7248     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7249       return E; // local block.
7250     return nullptr;
7251 
7252   case Stmt::AddrLabelExprClass:
7253     return E; // address of label.
7254 
7255   case Stmt::ExprWithCleanupsClass:
7256     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7257                     ParentDecl);
7258 
7259   // For casts, we need to handle conversions from arrays to
7260   // pointer values, and pointer-to-pointer conversions.
7261   case Stmt::ImplicitCastExprClass:
7262   case Stmt::CStyleCastExprClass:
7263   case Stmt::CXXFunctionalCastExprClass:
7264   case Stmt::ObjCBridgedCastExprClass:
7265   case Stmt::CXXStaticCastExprClass:
7266   case Stmt::CXXDynamicCastExprClass:
7267   case Stmt::CXXConstCastExprClass:
7268   case Stmt::CXXReinterpretCastExprClass: {
7269     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7270     switch (cast<CastExpr>(E)->getCastKind()) {
7271     case CK_LValueToRValue:
7272     case CK_NoOp:
7273     case CK_BaseToDerived:
7274     case CK_DerivedToBase:
7275     case CK_UncheckedDerivedToBase:
7276     case CK_Dynamic:
7277     case CK_CPointerToObjCPointerCast:
7278     case CK_BlockPointerToObjCPointerCast:
7279     case CK_AnyPointerToBlockPointerCast:
7280       return EvalAddr(SubExpr, refVars, ParentDecl);
7281 
7282     case CK_ArrayToPointerDecay:
7283       return EvalVal(SubExpr, refVars, ParentDecl);
7284 
7285     case CK_BitCast:
7286       if (SubExpr->getType()->isAnyPointerType() ||
7287           SubExpr->getType()->isBlockPointerType() ||
7288           SubExpr->getType()->isObjCQualifiedIdType())
7289         return EvalAddr(SubExpr, refVars, ParentDecl);
7290       else
7291         return nullptr;
7292 
7293     default:
7294       return nullptr;
7295     }
7296   }
7297 
7298   case Stmt::MaterializeTemporaryExprClass:
7299     if (const Expr *Result =
7300             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7301                      refVars, ParentDecl))
7302       return Result;
7303     return E;
7304 
7305   // Everything else: we simply don't reason about them.
7306   default:
7307     return nullptr;
7308   }
7309 }
7310 
7311 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7312 ///   See the comments for EvalAddr for more details.
7313 static const Expr *EvalVal(const Expr *E,
7314                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7315                            const Decl *ParentDecl) {
7316   do {
7317     // We should only be called for evaluating non-pointer expressions, or
7318     // expressions with a pointer type that are not used as references but
7319     // instead
7320     // are l-values (e.g., DeclRefExpr with a pointer type).
7321 
7322     // Our "symbolic interpreter" is just a dispatch off the currently
7323     // viewed AST node.  We then recursively traverse the AST by calling
7324     // EvalAddr and EvalVal appropriately.
7325 
7326     E = E->IgnoreParens();
7327     switch (E->getStmtClass()) {
7328     case Stmt::ImplicitCastExprClass: {
7329       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7330       if (IE->getValueKind() == VK_LValue) {
7331         E = IE->getSubExpr();
7332         continue;
7333       }
7334       return nullptr;
7335     }
7336 
7337     case Stmt::ExprWithCleanupsClass:
7338       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7339                      ParentDecl);
7340 
7341     case Stmt::DeclRefExprClass: {
7342       // When we hit a DeclRefExpr we are looking at code that refers to a
7343       // variable's name. If it's not a reference variable we check if it has
7344       // local storage within the function, and if so, return the expression.
7345       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7346 
7347       // If we leave the immediate function, the lifetime isn't about to end.
7348       if (DR->refersToEnclosingVariableOrCapture())
7349         return nullptr;
7350 
7351       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7352         // Check if it refers to itself, e.g. "int& i = i;".
7353         if (V == ParentDecl)
7354           return DR;
7355 
7356         if (V->hasLocalStorage()) {
7357           if (!V->getType()->isReferenceType())
7358             return DR;
7359 
7360           // Reference variable, follow through to the expression that
7361           // it points to.
7362           if (V->hasInit()) {
7363             // Add the reference variable to the "trail".
7364             refVars.push_back(DR);
7365             return EvalVal(V->getInit(), refVars, V);
7366           }
7367         }
7368       }
7369 
7370       return nullptr;
7371     }
7372 
7373     case Stmt::UnaryOperatorClass: {
7374       // The only unary operator that make sense to handle here
7375       // is Deref.  All others don't resolve to a "name."  This includes
7376       // handling all sorts of rvalues passed to a unary operator.
7377       const UnaryOperator *U = cast<UnaryOperator>(E);
7378 
7379       if (U->getOpcode() == UO_Deref)
7380         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7381 
7382       return nullptr;
7383     }
7384 
7385     case Stmt::ArraySubscriptExprClass: {
7386       // Array subscripts are potential references to data on the stack.  We
7387       // retrieve the DeclRefExpr* for the array variable if it indeed
7388       // has local storage.
7389       const auto *ASE = cast<ArraySubscriptExpr>(E);
7390       if (ASE->isTypeDependent())
7391         return nullptr;
7392       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7393     }
7394 
7395     case Stmt::OMPArraySectionExprClass: {
7396       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7397                       ParentDecl);
7398     }
7399 
7400     case Stmt::ConditionalOperatorClass: {
7401       // For conditional operators we need to see if either the LHS or RHS are
7402       // non-NULL Expr's.  If one is non-NULL, we return it.
7403       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7404 
7405       // Handle the GNU extension for missing LHS.
7406       if (const Expr *LHSExpr = C->getLHS()) {
7407         // In C++, we can have a throw-expression, which has 'void' type.
7408         if (!LHSExpr->getType()->isVoidType())
7409           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7410             return LHS;
7411       }
7412 
7413       // In C++, we can have a throw-expression, which has 'void' type.
7414       if (C->getRHS()->getType()->isVoidType())
7415         return nullptr;
7416 
7417       return EvalVal(C->getRHS(), refVars, ParentDecl);
7418     }
7419 
7420     // Accesses to members are potential references to data on the stack.
7421     case Stmt::MemberExprClass: {
7422       const MemberExpr *M = cast<MemberExpr>(E);
7423 
7424       // Check for indirect access.  We only want direct field accesses.
7425       if (M->isArrow())
7426         return nullptr;
7427 
7428       // Check whether the member type is itself a reference, in which case
7429       // we're not going to refer to the member, but to what the member refers
7430       // to.
7431       if (M->getMemberDecl()->getType()->isReferenceType())
7432         return nullptr;
7433 
7434       return EvalVal(M->getBase(), refVars, ParentDecl);
7435     }
7436 
7437     case Stmt::MaterializeTemporaryExprClass:
7438       if (const Expr *Result =
7439               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7440                       refVars, ParentDecl))
7441         return Result;
7442       return E;
7443 
7444     default:
7445       // Check that we don't return or take the address of a reference to a
7446       // temporary. This is only useful in C++.
7447       if (!E->isTypeDependent() && E->isRValue())
7448         return E;
7449 
7450       // Everything else: we simply don't reason about them.
7451       return nullptr;
7452     }
7453   } while (true);
7454 }
7455 
7456 void
7457 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7458                          SourceLocation ReturnLoc,
7459                          bool isObjCMethod,
7460                          const AttrVec *Attrs,
7461                          const FunctionDecl *FD) {
7462   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7463 
7464   // Check if the return value is null but should not be.
7465   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7466        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7467       CheckNonNullExpr(*this, RetValExp))
7468     Diag(ReturnLoc, diag::warn_null_ret)
7469       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7470 
7471   // C++11 [basic.stc.dynamic.allocation]p4:
7472   //   If an allocation function declared with a non-throwing
7473   //   exception-specification fails to allocate storage, it shall return
7474   //   a null pointer. Any other allocation function that fails to allocate
7475   //   storage shall indicate failure only by throwing an exception [...]
7476   if (FD) {
7477     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7478     if (Op == OO_New || Op == OO_Array_New) {
7479       const FunctionProtoType *Proto
7480         = FD->getType()->castAs<FunctionProtoType>();
7481       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7482           CheckNonNullExpr(*this, RetValExp))
7483         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7484           << FD << getLangOpts().CPlusPlus11;
7485     }
7486   }
7487 }
7488 
7489 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7490 
7491 /// Check for comparisons of floating point operands using != and ==.
7492 /// Issue a warning if these are no self-comparisons, as they are not likely
7493 /// to do what the programmer intended.
7494 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7495   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7496   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7497 
7498   // Special case: check for x == x (which is OK).
7499   // Do not emit warnings for such cases.
7500   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7501     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7502       if (DRL->getDecl() == DRR->getDecl())
7503         return;
7504 
7505   // Special case: check for comparisons against literals that can be exactly
7506   //  represented by APFloat.  In such cases, do not emit a warning.  This
7507   //  is a heuristic: often comparison against such literals are used to
7508   //  detect if a value in a variable has not changed.  This clearly can
7509   //  lead to false negatives.
7510   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7511     if (FLL->isExact())
7512       return;
7513   } else
7514     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7515       if (FLR->isExact())
7516         return;
7517 
7518   // Check for comparisons with builtin types.
7519   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7520     if (CL->getBuiltinCallee())
7521       return;
7522 
7523   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7524     if (CR->getBuiltinCallee())
7525       return;
7526 
7527   // Emit the diagnostic.
7528   Diag(Loc, diag::warn_floatingpoint_eq)
7529     << LHS->getSourceRange() << RHS->getSourceRange();
7530 }
7531 
7532 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7533 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7534 
7535 namespace {
7536 
7537 /// Structure recording the 'active' range of an integer-valued
7538 /// expression.
7539 struct IntRange {
7540   /// The number of bits active in the int.
7541   unsigned Width;
7542 
7543   /// True if the int is known not to have negative values.
7544   bool NonNegative;
7545 
7546   IntRange(unsigned Width, bool NonNegative)
7547     : Width(Width), NonNegative(NonNegative)
7548   {}
7549 
7550   /// Returns the range of the bool type.
7551   static IntRange forBoolType() {
7552     return IntRange(1, true);
7553   }
7554 
7555   /// Returns the range of an opaque value of the given integral type.
7556   static IntRange forValueOfType(ASTContext &C, QualType T) {
7557     return forValueOfCanonicalType(C,
7558                           T->getCanonicalTypeInternal().getTypePtr());
7559   }
7560 
7561   /// Returns the range of an opaque value of a canonical integral type.
7562   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7563     assert(T->isCanonicalUnqualified());
7564 
7565     if (const VectorType *VT = dyn_cast<VectorType>(T))
7566       T = VT->getElementType().getTypePtr();
7567     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7568       T = CT->getElementType().getTypePtr();
7569     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7570       T = AT->getValueType().getTypePtr();
7571 
7572     // For enum types, use the known bit width of the enumerators.
7573     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7574       EnumDecl *Enum = ET->getDecl();
7575       if (!Enum->isCompleteDefinition())
7576         return IntRange(C.getIntWidth(QualType(T, 0)), false);
7577 
7578       unsigned NumPositive = Enum->getNumPositiveBits();
7579       unsigned NumNegative = Enum->getNumNegativeBits();
7580 
7581       if (NumNegative == 0)
7582         return IntRange(NumPositive, true/*NonNegative*/);
7583       else
7584         return IntRange(std::max(NumPositive + 1, NumNegative),
7585                         false/*NonNegative*/);
7586     }
7587 
7588     const BuiltinType *BT = cast<BuiltinType>(T);
7589     assert(BT->isInteger());
7590 
7591     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7592   }
7593 
7594   /// Returns the "target" range of a canonical integral type, i.e.
7595   /// the range of values expressible in the type.
7596   ///
7597   /// This matches forValueOfCanonicalType except that enums have the
7598   /// full range of their type, not the range of their enumerators.
7599   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7600     assert(T->isCanonicalUnqualified());
7601 
7602     if (const VectorType *VT = dyn_cast<VectorType>(T))
7603       T = VT->getElementType().getTypePtr();
7604     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7605       T = CT->getElementType().getTypePtr();
7606     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7607       T = AT->getValueType().getTypePtr();
7608     if (const EnumType *ET = dyn_cast<EnumType>(T))
7609       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7610 
7611     const BuiltinType *BT = cast<BuiltinType>(T);
7612     assert(BT->isInteger());
7613 
7614     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7615   }
7616 
7617   /// Returns the supremum of two ranges: i.e. their conservative merge.
7618   static IntRange join(IntRange L, IntRange R) {
7619     return IntRange(std::max(L.Width, R.Width),
7620                     L.NonNegative && R.NonNegative);
7621   }
7622 
7623   /// Returns the infinum of two ranges: i.e. their aggressive merge.
7624   static IntRange meet(IntRange L, IntRange R) {
7625     return IntRange(std::min(L.Width, R.Width),
7626                     L.NonNegative || R.NonNegative);
7627   }
7628 };
7629 
7630 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7631   if (value.isSigned() && value.isNegative())
7632     return IntRange(value.getMinSignedBits(), false);
7633 
7634   if (value.getBitWidth() > MaxWidth)
7635     value = value.trunc(MaxWidth);
7636 
7637   // isNonNegative() just checks the sign bit without considering
7638   // signedness.
7639   return IntRange(value.getActiveBits(), true);
7640 }
7641 
7642 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7643                        unsigned MaxWidth) {
7644   if (result.isInt())
7645     return GetValueRange(C, result.getInt(), MaxWidth);
7646 
7647   if (result.isVector()) {
7648     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7649     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7650       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7651       R = IntRange::join(R, El);
7652     }
7653     return R;
7654   }
7655 
7656   if (result.isComplexInt()) {
7657     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7658     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7659     return IntRange::join(R, I);
7660   }
7661 
7662   // This can happen with lossless casts to intptr_t of "based" lvalues.
7663   // Assume it might use arbitrary bits.
7664   // FIXME: The only reason we need to pass the type in here is to get
7665   // the sign right on this one case.  It would be nice if APValue
7666   // preserved this.
7667   assert(result.isLValue() || result.isAddrLabelDiff());
7668   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7669 }
7670 
7671 QualType GetExprType(const Expr *E) {
7672   QualType Ty = E->getType();
7673   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7674     Ty = AtomicRHS->getValueType();
7675   return Ty;
7676 }
7677 
7678 /// Pseudo-evaluate the given integer expression, estimating the
7679 /// range of values it might take.
7680 ///
7681 /// \param MaxWidth - the width to which the value will be truncated
7682 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7683   E = E->IgnoreParens();
7684 
7685   // Try a full evaluation first.
7686   Expr::EvalResult result;
7687   if (E->EvaluateAsRValue(result, C))
7688     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7689 
7690   // I think we only want to look through implicit casts here; if the
7691   // user has an explicit widening cast, we should treat the value as
7692   // being of the new, wider type.
7693   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7694     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7695       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7696 
7697     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7698 
7699     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7700                          CE->getCastKind() == CK_BooleanToSignedIntegral;
7701 
7702     // Assume that non-integer casts can span the full range of the type.
7703     if (!isIntegerCast)
7704       return OutputTypeRange;
7705 
7706     IntRange SubRange
7707       = GetExprRange(C, CE->getSubExpr(),
7708                      std::min(MaxWidth, OutputTypeRange.Width));
7709 
7710     // Bail out if the subexpr's range is as wide as the cast type.
7711     if (SubRange.Width >= OutputTypeRange.Width)
7712       return OutputTypeRange;
7713 
7714     // Otherwise, we take the smaller width, and we're non-negative if
7715     // either the output type or the subexpr is.
7716     return IntRange(SubRange.Width,
7717                     SubRange.NonNegative || OutputTypeRange.NonNegative);
7718   }
7719 
7720   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7721     // If we can fold the condition, just take that operand.
7722     bool CondResult;
7723     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7724       return GetExprRange(C, CondResult ? CO->getTrueExpr()
7725                                         : CO->getFalseExpr(),
7726                           MaxWidth);
7727 
7728     // Otherwise, conservatively merge.
7729     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7730     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7731     return IntRange::join(L, R);
7732   }
7733 
7734   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7735     switch (BO->getOpcode()) {
7736 
7737     // Boolean-valued operations are single-bit and positive.
7738     case BO_LAnd:
7739     case BO_LOr:
7740     case BO_LT:
7741     case BO_GT:
7742     case BO_LE:
7743     case BO_GE:
7744     case BO_EQ:
7745     case BO_NE:
7746       return IntRange::forBoolType();
7747 
7748     // The type of the assignments is the type of the LHS, so the RHS
7749     // is not necessarily the same type.
7750     case BO_MulAssign:
7751     case BO_DivAssign:
7752     case BO_RemAssign:
7753     case BO_AddAssign:
7754     case BO_SubAssign:
7755     case BO_XorAssign:
7756     case BO_OrAssign:
7757       // TODO: bitfields?
7758       return IntRange::forValueOfType(C, GetExprType(E));
7759 
7760     // Simple assignments just pass through the RHS, which will have
7761     // been coerced to the LHS type.
7762     case BO_Assign:
7763       // TODO: bitfields?
7764       return GetExprRange(C, BO->getRHS(), MaxWidth);
7765 
7766     // Operations with opaque sources are black-listed.
7767     case BO_PtrMemD:
7768     case BO_PtrMemI:
7769       return IntRange::forValueOfType(C, GetExprType(E));
7770 
7771     // Bitwise-and uses the *infinum* of the two source ranges.
7772     case BO_And:
7773     case BO_AndAssign:
7774       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7775                             GetExprRange(C, BO->getRHS(), MaxWidth));
7776 
7777     // Left shift gets black-listed based on a judgement call.
7778     case BO_Shl:
7779       // ...except that we want to treat '1 << (blah)' as logically
7780       // positive.  It's an important idiom.
7781       if (IntegerLiteral *I
7782             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7783         if (I->getValue() == 1) {
7784           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7785           return IntRange(R.Width, /*NonNegative*/ true);
7786         }
7787       }
7788       // fallthrough
7789 
7790     case BO_ShlAssign:
7791       return IntRange::forValueOfType(C, GetExprType(E));
7792 
7793     // Right shift by a constant can narrow its left argument.
7794     case BO_Shr:
7795     case BO_ShrAssign: {
7796       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7797 
7798       // If the shift amount is a positive constant, drop the width by
7799       // that much.
7800       llvm::APSInt shift;
7801       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7802           shift.isNonNegative()) {
7803         unsigned zext = shift.getZExtValue();
7804         if (zext >= L.Width)
7805           L.Width = (L.NonNegative ? 0 : 1);
7806         else
7807           L.Width -= zext;
7808       }
7809 
7810       return L;
7811     }
7812 
7813     // Comma acts as its right operand.
7814     case BO_Comma:
7815       return GetExprRange(C, BO->getRHS(), MaxWidth);
7816 
7817     // Black-list pointer subtractions.
7818     case BO_Sub:
7819       if (BO->getLHS()->getType()->isPointerType())
7820         return IntRange::forValueOfType(C, GetExprType(E));
7821       break;
7822 
7823     // The width of a division result is mostly determined by the size
7824     // of the LHS.
7825     case BO_Div: {
7826       // Don't 'pre-truncate' the operands.
7827       unsigned opWidth = C.getIntWidth(GetExprType(E));
7828       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7829 
7830       // If the divisor is constant, use that.
7831       llvm::APSInt divisor;
7832       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7833         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7834         if (log2 >= L.Width)
7835           L.Width = (L.NonNegative ? 0 : 1);
7836         else
7837           L.Width = std::min(L.Width - log2, MaxWidth);
7838         return L;
7839       }
7840 
7841       // Otherwise, just use the LHS's width.
7842       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7843       return IntRange(L.Width, L.NonNegative && R.NonNegative);
7844     }
7845 
7846     // The result of a remainder can't be larger than the result of
7847     // either side.
7848     case BO_Rem: {
7849       // Don't 'pre-truncate' the operands.
7850       unsigned opWidth = C.getIntWidth(GetExprType(E));
7851       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7852       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7853 
7854       IntRange meet = IntRange::meet(L, R);
7855       meet.Width = std::min(meet.Width, MaxWidth);
7856       return meet;
7857     }
7858 
7859     // The default behavior is okay for these.
7860     case BO_Mul:
7861     case BO_Add:
7862     case BO_Xor:
7863     case BO_Or:
7864       break;
7865     }
7866 
7867     // The default case is to treat the operation as if it were closed
7868     // on the narrowest type that encompasses both operands.
7869     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7870     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7871     return IntRange::join(L, R);
7872   }
7873 
7874   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
7875     switch (UO->getOpcode()) {
7876     // Boolean-valued operations are white-listed.
7877     case UO_LNot:
7878       return IntRange::forBoolType();
7879 
7880     // Operations with opaque sources are black-listed.
7881     case UO_Deref:
7882     case UO_AddrOf: // should be impossible
7883       return IntRange::forValueOfType(C, GetExprType(E));
7884 
7885     default:
7886       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7887     }
7888   }
7889 
7890   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
7891     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7892 
7893   if (const auto *BitField = E->getSourceBitField())
7894     return IntRange(BitField->getBitWidthValue(C),
7895                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
7896 
7897   return IntRange::forValueOfType(C, GetExprType(E));
7898 }
7899 
7900 IntRange GetExprRange(ASTContext &C, const Expr *E) {
7901   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
7902 }
7903 
7904 /// Checks whether the given value, which currently has the given
7905 /// source semantics, has the same value when coerced through the
7906 /// target semantics.
7907 bool IsSameFloatAfterCast(const llvm::APFloat &value,
7908                           const llvm::fltSemantics &Src,
7909                           const llvm::fltSemantics &Tgt) {
7910   llvm::APFloat truncated = value;
7911 
7912   bool ignored;
7913   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7914   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7915 
7916   return truncated.bitwiseIsEqual(value);
7917 }
7918 
7919 /// Checks whether the given value, which currently has the given
7920 /// source semantics, has the same value when coerced through the
7921 /// target semantics.
7922 ///
7923 /// The value might be a vector of floats (or a complex number).
7924 bool IsSameFloatAfterCast(const APValue &value,
7925                           const llvm::fltSemantics &Src,
7926                           const llvm::fltSemantics &Tgt) {
7927   if (value.isFloat())
7928     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7929 
7930   if (value.isVector()) {
7931     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7932       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7933         return false;
7934     return true;
7935   }
7936 
7937   assert(value.isComplexFloat());
7938   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7939           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7940 }
7941 
7942 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
7943 
7944 bool IsZero(Sema &S, Expr *E) {
7945   // Suppress cases where we are comparing against an enum constant.
7946   if (const DeclRefExpr *DR =
7947       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7948     if (isa<EnumConstantDecl>(DR->getDecl()))
7949       return false;
7950 
7951   // Suppress cases where the '0' value is expanded from a macro.
7952   if (E->getLocStart().isMacroID())
7953     return false;
7954 
7955   llvm::APSInt Value;
7956   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7957 }
7958 
7959 bool HasEnumType(Expr *E) {
7960   // Strip off implicit integral promotions.
7961   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7962     if (ICE->getCastKind() != CK_IntegralCast &&
7963         ICE->getCastKind() != CK_NoOp)
7964       break;
7965     E = ICE->getSubExpr();
7966   }
7967 
7968   return E->getType()->isEnumeralType();
7969 }
7970 
7971 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
7972   // Disable warning in template instantiations.
7973   if (!S.ActiveTemplateInstantiations.empty())
7974     return;
7975 
7976   BinaryOperatorKind op = E->getOpcode();
7977   if (E->isValueDependent())
7978     return;
7979 
7980   if (op == BO_LT && IsZero(S, E->getRHS())) {
7981     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7982       << "< 0" << "false" << HasEnumType(E->getLHS())
7983       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7984   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
7985     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7986       << ">= 0" << "true" << HasEnumType(E->getLHS())
7987       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7988   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
7989     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7990       << "0 >" << "false" << HasEnumType(E->getRHS())
7991       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7992   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
7993     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7994       << "0 <=" << "true" << HasEnumType(E->getRHS())
7995       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7996   }
7997 }
7998 
7999 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8000                                   Expr *Other, const llvm::APSInt &Value,
8001                                   bool RhsConstant) {
8002   // Disable warning in template instantiations.
8003   if (!S.ActiveTemplateInstantiations.empty())
8004     return;
8005 
8006   // TODO: Investigate using GetExprRange() to get tighter bounds
8007   // on the bit ranges.
8008   QualType OtherT = Other->getType();
8009   if (const auto *AT = OtherT->getAs<AtomicType>())
8010     OtherT = AT->getValueType();
8011   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8012   unsigned OtherWidth = OtherRange.Width;
8013 
8014   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8015 
8016   // 0 values are handled later by CheckTrivialUnsignedComparison().
8017   if ((Value == 0) && (!OtherIsBooleanType))
8018     return;
8019 
8020   BinaryOperatorKind op = E->getOpcode();
8021   bool IsTrue = true;
8022 
8023   // Used for diagnostic printout.
8024   enum {
8025     LiteralConstant = 0,
8026     CXXBoolLiteralTrue,
8027     CXXBoolLiteralFalse
8028   } LiteralOrBoolConstant = LiteralConstant;
8029 
8030   if (!OtherIsBooleanType) {
8031     QualType ConstantT = Constant->getType();
8032     QualType CommonT = E->getLHS()->getType();
8033 
8034     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8035       return;
8036     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8037            "comparison with non-integer type");
8038 
8039     bool ConstantSigned = ConstantT->isSignedIntegerType();
8040     bool CommonSigned = CommonT->isSignedIntegerType();
8041 
8042     bool EqualityOnly = false;
8043 
8044     if (CommonSigned) {
8045       // The common type is signed, therefore no signed to unsigned conversion.
8046       if (!OtherRange.NonNegative) {
8047         // Check that the constant is representable in type OtherT.
8048         if (ConstantSigned) {
8049           if (OtherWidth >= Value.getMinSignedBits())
8050             return;
8051         } else { // !ConstantSigned
8052           if (OtherWidth >= Value.getActiveBits() + 1)
8053             return;
8054         }
8055       } else { // !OtherSigned
8056                // Check that the constant is representable in type OtherT.
8057         // Negative values are out of range.
8058         if (ConstantSigned) {
8059           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8060             return;
8061         } else { // !ConstantSigned
8062           if (OtherWidth >= Value.getActiveBits())
8063             return;
8064         }
8065       }
8066     } else { // !CommonSigned
8067       if (OtherRange.NonNegative) {
8068         if (OtherWidth >= Value.getActiveBits())
8069           return;
8070       } else { // OtherSigned
8071         assert(!ConstantSigned &&
8072                "Two signed types converted to unsigned types.");
8073         // Check to see if the constant is representable in OtherT.
8074         if (OtherWidth > Value.getActiveBits())
8075           return;
8076         // Check to see if the constant is equivalent to a negative value
8077         // cast to CommonT.
8078         if (S.Context.getIntWidth(ConstantT) ==
8079                 S.Context.getIntWidth(CommonT) &&
8080             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8081           return;
8082         // The constant value rests between values that OtherT can represent
8083         // after conversion.  Relational comparison still works, but equality
8084         // comparisons will be tautological.
8085         EqualityOnly = true;
8086       }
8087     }
8088 
8089     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8090 
8091     if (op == BO_EQ || op == BO_NE) {
8092       IsTrue = op == BO_NE;
8093     } else if (EqualityOnly) {
8094       return;
8095     } else if (RhsConstant) {
8096       if (op == BO_GT || op == BO_GE)
8097         IsTrue = !PositiveConstant;
8098       else // op == BO_LT || op == BO_LE
8099         IsTrue = PositiveConstant;
8100     } else {
8101       if (op == BO_LT || op == BO_LE)
8102         IsTrue = !PositiveConstant;
8103       else // op == BO_GT || op == BO_GE
8104         IsTrue = PositiveConstant;
8105     }
8106   } else {
8107     // Other isKnownToHaveBooleanValue
8108     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8109     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8110     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8111 
8112     static const struct LinkedConditions {
8113       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8114       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8115       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8116       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8117       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8118       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8119 
8120     } TruthTable = {
8121         // Constant on LHS.              | Constant on RHS.              |
8122         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8123         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8124         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8125         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8126         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8127         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8128         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8129       };
8130 
8131     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8132 
8133     enum ConstantValue ConstVal = Zero;
8134     if (Value.isUnsigned() || Value.isNonNegative()) {
8135       if (Value == 0) {
8136         LiteralOrBoolConstant =
8137             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8138         ConstVal = Zero;
8139       } else if (Value == 1) {
8140         LiteralOrBoolConstant =
8141             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8142         ConstVal = One;
8143       } else {
8144         LiteralOrBoolConstant = LiteralConstant;
8145         ConstVal = GT_One;
8146       }
8147     } else {
8148       ConstVal = LT_Zero;
8149     }
8150 
8151     CompareBoolWithConstantResult CmpRes;
8152 
8153     switch (op) {
8154     case BO_LT:
8155       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8156       break;
8157     case BO_GT:
8158       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8159       break;
8160     case BO_LE:
8161       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8162       break;
8163     case BO_GE:
8164       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8165       break;
8166     case BO_EQ:
8167       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8168       break;
8169     case BO_NE:
8170       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8171       break;
8172     default:
8173       CmpRes = Unkwn;
8174       break;
8175     }
8176 
8177     if (CmpRes == AFals) {
8178       IsTrue = false;
8179     } else if (CmpRes == ATrue) {
8180       IsTrue = true;
8181     } else {
8182       return;
8183     }
8184   }
8185 
8186   // If this is a comparison to an enum constant, include that
8187   // constant in the diagnostic.
8188   const EnumConstantDecl *ED = nullptr;
8189   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8190     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8191 
8192   SmallString<64> PrettySourceValue;
8193   llvm::raw_svector_ostream OS(PrettySourceValue);
8194   if (ED)
8195     OS << '\'' << *ED << "' (" << Value << ")";
8196   else
8197     OS << Value;
8198 
8199   S.DiagRuntimeBehavior(
8200     E->getOperatorLoc(), E,
8201     S.PDiag(diag::warn_out_of_range_compare)
8202         << OS.str() << LiteralOrBoolConstant
8203         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8204         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8205 }
8206 
8207 /// Analyze the operands of the given comparison.  Implements the
8208 /// fallback case from AnalyzeComparison.
8209 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8210   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8211   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8212 }
8213 
8214 /// \brief Implements -Wsign-compare.
8215 ///
8216 /// \param E the binary operator to check for warnings
8217 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8218   // The type the comparison is being performed in.
8219   QualType T = E->getLHS()->getType();
8220 
8221   // Only analyze comparison operators where both sides have been converted to
8222   // the same type.
8223   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8224     return AnalyzeImpConvsInComparison(S, E);
8225 
8226   // Don't analyze value-dependent comparisons directly.
8227   if (E->isValueDependent())
8228     return AnalyzeImpConvsInComparison(S, E);
8229 
8230   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8231   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8232 
8233   bool IsComparisonConstant = false;
8234 
8235   // Check whether an integer constant comparison results in a value
8236   // of 'true' or 'false'.
8237   if (T->isIntegralType(S.Context)) {
8238     llvm::APSInt RHSValue;
8239     bool IsRHSIntegralLiteral =
8240       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8241     llvm::APSInt LHSValue;
8242     bool IsLHSIntegralLiteral =
8243       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8244     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8245         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8246     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8247       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8248     else
8249       IsComparisonConstant =
8250         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8251   } else if (!T->hasUnsignedIntegerRepresentation())
8252       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8253 
8254   // We don't do anything special if this isn't an unsigned integral
8255   // comparison:  we're only interested in integral comparisons, and
8256   // signed comparisons only happen in cases we don't care to warn about.
8257   //
8258   // We also don't care about value-dependent expressions or expressions
8259   // whose result is a constant.
8260   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8261     return AnalyzeImpConvsInComparison(S, E);
8262 
8263   // Check to see if one of the (unmodified) operands is of different
8264   // signedness.
8265   Expr *signedOperand, *unsignedOperand;
8266   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8267     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8268            "unsigned comparison between two signed integer expressions?");
8269     signedOperand = LHS;
8270     unsignedOperand = RHS;
8271   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8272     signedOperand = RHS;
8273     unsignedOperand = LHS;
8274   } else {
8275     CheckTrivialUnsignedComparison(S, E);
8276     return AnalyzeImpConvsInComparison(S, E);
8277   }
8278 
8279   // Otherwise, calculate the effective range of the signed operand.
8280   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8281 
8282   // Go ahead and analyze implicit conversions in the operands.  Note
8283   // that we skip the implicit conversions on both sides.
8284   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8285   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8286 
8287   // If the signed range is non-negative, -Wsign-compare won't fire,
8288   // but we should still check for comparisons which are always true
8289   // or false.
8290   if (signedRange.NonNegative)
8291     return CheckTrivialUnsignedComparison(S, E);
8292 
8293   // For (in)equality comparisons, if the unsigned operand is a
8294   // constant which cannot collide with a overflowed signed operand,
8295   // then reinterpreting the signed operand as unsigned will not
8296   // change the result of the comparison.
8297   if (E->isEqualityOp()) {
8298     unsigned comparisonWidth = S.Context.getIntWidth(T);
8299     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8300 
8301     // We should never be unable to prove that the unsigned operand is
8302     // non-negative.
8303     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8304 
8305     if (unsignedRange.Width < comparisonWidth)
8306       return;
8307   }
8308 
8309   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8310     S.PDiag(diag::warn_mixed_sign_comparison)
8311       << LHS->getType() << RHS->getType()
8312       << LHS->getSourceRange() << RHS->getSourceRange());
8313 }
8314 
8315 /// Analyzes an attempt to assign the given value to a bitfield.
8316 ///
8317 /// Returns true if there was something fishy about the attempt.
8318 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8319                                SourceLocation InitLoc) {
8320   assert(Bitfield->isBitField());
8321   if (Bitfield->isInvalidDecl())
8322     return false;
8323 
8324   // White-list bool bitfields.
8325   if (Bitfield->getType()->isBooleanType())
8326     return false;
8327 
8328   // Ignore value- or type-dependent expressions.
8329   if (Bitfield->getBitWidth()->isValueDependent() ||
8330       Bitfield->getBitWidth()->isTypeDependent() ||
8331       Init->isValueDependent() ||
8332       Init->isTypeDependent())
8333     return false;
8334 
8335   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8336 
8337   llvm::APSInt Value;
8338   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8339     return false;
8340 
8341   unsigned OriginalWidth = Value.getBitWidth();
8342   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8343 
8344   if (!Value.isSigned() || Value.isNegative())
8345     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8346       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8347         OriginalWidth = Value.getMinSignedBits();
8348 
8349   if (OriginalWidth <= FieldWidth)
8350     return false;
8351 
8352   // Compute the value which the bitfield will contain.
8353   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8354   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
8355 
8356   // Check whether the stored value is equal to the original value.
8357   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8358   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8359     return false;
8360 
8361   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8362   // therefore don't strictly fit into a signed bitfield of width 1.
8363   if (FieldWidth == 1 && Value == 1)
8364     return false;
8365 
8366   std::string PrettyValue = Value.toString(10);
8367   std::string PrettyTrunc = TruncatedValue.toString(10);
8368 
8369   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8370     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8371     << Init->getSourceRange();
8372 
8373   return true;
8374 }
8375 
8376 /// Analyze the given simple or compound assignment for warning-worthy
8377 /// operations.
8378 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8379   // Just recurse on the LHS.
8380   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8381 
8382   // We want to recurse on the RHS as normal unless we're assigning to
8383   // a bitfield.
8384   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8385     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8386                                   E->getOperatorLoc())) {
8387       // Recurse, ignoring any implicit conversions on the RHS.
8388       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8389                                         E->getOperatorLoc());
8390     }
8391   }
8392 
8393   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8394 }
8395 
8396 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8397 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8398                      SourceLocation CContext, unsigned diag,
8399                      bool pruneControlFlow = false) {
8400   if (pruneControlFlow) {
8401     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8402                           S.PDiag(diag)
8403                             << SourceType << T << E->getSourceRange()
8404                             << SourceRange(CContext));
8405     return;
8406   }
8407   S.Diag(E->getExprLoc(), diag)
8408     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8409 }
8410 
8411 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8412 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8413                      unsigned diag, bool pruneControlFlow = false) {
8414   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8415 }
8416 
8417 
8418 /// Diagnose an implicit cast from a floating point value to an integer value.
8419 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8420 
8421                              SourceLocation CContext) {
8422   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8423   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8424 
8425   Expr *InnerE = E->IgnoreParenImpCasts();
8426   // We also want to warn on, e.g., "int i = -1.234"
8427   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8428     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8429       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8430 
8431   const bool IsLiteral =
8432       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8433 
8434   llvm::APFloat Value(0.0);
8435   bool IsConstant =
8436     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8437   if (!IsConstant) {
8438     return DiagnoseImpCast(S, E, T, CContext,
8439                            diag::warn_impcast_float_integer, PruneWarnings);
8440   }
8441 
8442   bool isExact = false;
8443 
8444   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8445                             T->hasUnsignedIntegerRepresentation());
8446   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8447                              &isExact) == llvm::APFloat::opOK &&
8448       isExact) {
8449     if (IsLiteral) return;
8450     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8451                            PruneWarnings);
8452   }
8453 
8454   unsigned DiagID = 0;
8455   if (IsLiteral) {
8456     // Warn on floating point literal to integer.
8457     DiagID = diag::warn_impcast_literal_float_to_integer;
8458   } else if (IntegerValue == 0) {
8459     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8460       return DiagnoseImpCast(S, E, T, CContext,
8461                              diag::warn_impcast_float_integer, PruneWarnings);
8462     }
8463     // Warn on non-zero to zero conversion.
8464     DiagID = diag::warn_impcast_float_to_integer_zero;
8465   } else {
8466     if (IntegerValue.isUnsigned()) {
8467       if (!IntegerValue.isMaxValue()) {
8468         return DiagnoseImpCast(S, E, T, CContext,
8469                                diag::warn_impcast_float_integer, PruneWarnings);
8470       }
8471     } else {  // IntegerValue.isSigned()
8472       if (!IntegerValue.isMaxSignedValue() &&
8473           !IntegerValue.isMinSignedValue()) {
8474         return DiagnoseImpCast(S, E, T, CContext,
8475                                diag::warn_impcast_float_integer, PruneWarnings);
8476       }
8477     }
8478     // Warn on evaluatable floating point expression to integer conversion.
8479     DiagID = diag::warn_impcast_float_to_integer;
8480   }
8481 
8482   // FIXME: Force the precision of the source value down so we don't print
8483   // digits which are usually useless (we don't really care here if we
8484   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
8485   // would automatically print the shortest representation, but it's a bit
8486   // tricky to implement.
8487   SmallString<16> PrettySourceValue;
8488   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8489   precision = (precision * 59 + 195) / 196;
8490   Value.toString(PrettySourceValue, precision);
8491 
8492   SmallString<16> PrettyTargetValue;
8493   if (IsBool)
8494     PrettyTargetValue = Value.isZero() ? "false" : "true";
8495   else
8496     IntegerValue.toString(PrettyTargetValue);
8497 
8498   if (PruneWarnings) {
8499     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8500                           S.PDiag(DiagID)
8501                               << E->getType() << T.getUnqualifiedType()
8502                               << PrettySourceValue << PrettyTargetValue
8503                               << E->getSourceRange() << SourceRange(CContext));
8504   } else {
8505     S.Diag(E->getExprLoc(), DiagID)
8506         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8507         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8508   }
8509 }
8510 
8511 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8512   if (!Range.Width) return "0";
8513 
8514   llvm::APSInt ValueInRange = Value;
8515   ValueInRange.setIsSigned(!Range.NonNegative);
8516   ValueInRange = ValueInRange.trunc(Range.Width);
8517   return ValueInRange.toString(10);
8518 }
8519 
8520 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8521   if (!isa<ImplicitCastExpr>(Ex))
8522     return false;
8523 
8524   Expr *InnerE = Ex->IgnoreParenImpCasts();
8525   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8526   const Type *Source =
8527     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8528   if (Target->isDependentType())
8529     return false;
8530 
8531   const BuiltinType *FloatCandidateBT =
8532     dyn_cast<BuiltinType>(ToBool ? Source : Target);
8533   const Type *BoolCandidateType = ToBool ? Target : Source;
8534 
8535   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8536           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8537 }
8538 
8539 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8540                                       SourceLocation CC) {
8541   unsigned NumArgs = TheCall->getNumArgs();
8542   for (unsigned i = 0; i < NumArgs; ++i) {
8543     Expr *CurrA = TheCall->getArg(i);
8544     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8545       continue;
8546 
8547     bool IsSwapped = ((i > 0) &&
8548         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8549     IsSwapped |= ((i < (NumArgs - 1)) &&
8550         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8551     if (IsSwapped) {
8552       // Warn on this floating-point to bool conversion.
8553       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8554                       CurrA->getType(), CC,
8555                       diag::warn_impcast_floating_point_to_bool);
8556     }
8557   }
8558 }
8559 
8560 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8561   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8562                         E->getExprLoc()))
8563     return;
8564 
8565   // Don't warn on functions which have return type nullptr_t.
8566   if (isa<CallExpr>(E))
8567     return;
8568 
8569   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8570   const Expr::NullPointerConstantKind NullKind =
8571       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8572   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8573     return;
8574 
8575   // Return if target type is a safe conversion.
8576   if (T->isAnyPointerType() || T->isBlockPointerType() ||
8577       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8578     return;
8579 
8580   SourceLocation Loc = E->getSourceRange().getBegin();
8581 
8582   // Venture through the macro stacks to get to the source of macro arguments.
8583   // The new location is a better location than the complete location that was
8584   // passed in.
8585   while (S.SourceMgr.isMacroArgExpansion(Loc))
8586     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8587 
8588   while (S.SourceMgr.isMacroArgExpansion(CC))
8589     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8590 
8591   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
8592   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8593     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8594         Loc, S.SourceMgr, S.getLangOpts());
8595     if (MacroName == "NULL")
8596       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8597   }
8598 
8599   // Only warn if the null and context location are in the same macro expansion.
8600   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8601     return;
8602 
8603   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8604       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8605       << FixItHint::CreateReplacement(Loc,
8606                                       S.getFixItZeroLiteralForType(T, Loc));
8607 }
8608 
8609 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8610                            ObjCArrayLiteral *ArrayLiteral);
8611 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8612                                 ObjCDictionaryLiteral *DictionaryLiteral);
8613 
8614 /// Check a single element within a collection literal against the
8615 /// target element type.
8616 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8617                                        Expr *Element, unsigned ElementKind) {
8618   // Skip a bitcast to 'id' or qualified 'id'.
8619   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8620     if (ICE->getCastKind() == CK_BitCast &&
8621         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8622       Element = ICE->getSubExpr();
8623   }
8624 
8625   QualType ElementType = Element->getType();
8626   ExprResult ElementResult(Element);
8627   if (ElementType->getAs<ObjCObjectPointerType>() &&
8628       S.CheckSingleAssignmentConstraints(TargetElementType,
8629                                          ElementResult,
8630                                          false, false)
8631         != Sema::Compatible) {
8632     S.Diag(Element->getLocStart(),
8633            diag::warn_objc_collection_literal_element)
8634       << ElementType << ElementKind << TargetElementType
8635       << Element->getSourceRange();
8636   }
8637 
8638   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8639     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8640   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8641     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8642 }
8643 
8644 /// Check an Objective-C array literal being converted to the given
8645 /// target type.
8646 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8647                            ObjCArrayLiteral *ArrayLiteral) {
8648   if (!S.NSArrayDecl)
8649     return;
8650 
8651   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8652   if (!TargetObjCPtr)
8653     return;
8654 
8655   if (TargetObjCPtr->isUnspecialized() ||
8656       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8657         != S.NSArrayDecl->getCanonicalDecl())
8658     return;
8659 
8660   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8661   if (TypeArgs.size() != 1)
8662     return;
8663 
8664   QualType TargetElementType = TypeArgs[0];
8665   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8666     checkObjCCollectionLiteralElement(S, TargetElementType,
8667                                       ArrayLiteral->getElement(I),
8668                                       0);
8669   }
8670 }
8671 
8672 /// Check an Objective-C dictionary literal being converted to the given
8673 /// target type.
8674 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8675                                 ObjCDictionaryLiteral *DictionaryLiteral) {
8676   if (!S.NSDictionaryDecl)
8677     return;
8678 
8679   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8680   if (!TargetObjCPtr)
8681     return;
8682 
8683   if (TargetObjCPtr->isUnspecialized() ||
8684       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8685         != S.NSDictionaryDecl->getCanonicalDecl())
8686     return;
8687 
8688   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8689   if (TypeArgs.size() != 2)
8690     return;
8691 
8692   QualType TargetKeyType = TypeArgs[0];
8693   QualType TargetObjectType = TypeArgs[1];
8694   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8695     auto Element = DictionaryLiteral->getKeyValueElement(I);
8696     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8697     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8698   }
8699 }
8700 
8701 // Helper function to filter out cases for constant width constant conversion.
8702 // Don't warn on char array initialization or for non-decimal values.
8703 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8704                                    SourceLocation CC) {
8705   // If initializing from a constant, and the constant starts with '0',
8706   // then it is a binary, octal, or hexadecimal.  Allow these constants
8707   // to fill all the bits, even if there is a sign change.
8708   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8709     const char FirstLiteralCharacter =
8710         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8711     if (FirstLiteralCharacter == '0')
8712       return false;
8713   }
8714 
8715   // If the CC location points to a '{', and the type is char, then assume
8716   // assume it is an array initialization.
8717   if (CC.isValid() && T->isCharType()) {
8718     const char FirstContextCharacter =
8719         S.getSourceManager().getCharacterData(CC)[0];
8720     if (FirstContextCharacter == '{')
8721       return false;
8722   }
8723 
8724   return true;
8725 }
8726 
8727 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
8728                              SourceLocation CC, bool *ICContext = nullptr) {
8729   if (E->isTypeDependent() || E->isValueDependent()) return;
8730 
8731   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8732   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8733   if (Source == Target) return;
8734   if (Target->isDependentType()) return;
8735 
8736   // If the conversion context location is invalid don't complain. We also
8737   // don't want to emit a warning if the issue occurs from the expansion of
8738   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8739   // delay this check as long as possible. Once we detect we are in that
8740   // scenario, we just return.
8741   if (CC.isInvalid())
8742     return;
8743 
8744   // Diagnose implicit casts to bool.
8745   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8746     if (isa<StringLiteral>(E))
8747       // Warn on string literal to bool.  Checks for string literals in logical
8748       // and expressions, for instance, assert(0 && "error here"), are
8749       // prevented by a check in AnalyzeImplicitConversions().
8750       return DiagnoseImpCast(S, E, T, CC,
8751                              diag::warn_impcast_string_literal_to_bool);
8752     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8753         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8754       // This covers the literal expressions that evaluate to Objective-C
8755       // objects.
8756       return DiagnoseImpCast(S, E, T, CC,
8757                              diag::warn_impcast_objective_c_literal_to_bool);
8758     }
8759     if (Source->isPointerType() || Source->canDecayToPointerType()) {
8760       // Warn on pointer to bool conversion that is always true.
8761       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8762                                      SourceRange(CC));
8763     }
8764   }
8765 
8766   // Check implicit casts from Objective-C collection literals to specialized
8767   // collection types, e.g., NSArray<NSString *> *.
8768   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8769     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8770   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8771     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8772 
8773   // Strip vector types.
8774   if (isa<VectorType>(Source)) {
8775     if (!isa<VectorType>(Target)) {
8776       if (S.SourceMgr.isInSystemMacro(CC))
8777         return;
8778       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8779     }
8780 
8781     // If the vector cast is cast between two vectors of the same size, it is
8782     // a bitcast, not a conversion.
8783     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8784       return;
8785 
8786     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8787     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8788   }
8789   if (auto VecTy = dyn_cast<VectorType>(Target))
8790     Target = VecTy->getElementType().getTypePtr();
8791 
8792   // Strip complex types.
8793   if (isa<ComplexType>(Source)) {
8794     if (!isa<ComplexType>(Target)) {
8795       if (S.SourceMgr.isInSystemMacro(CC))
8796         return;
8797 
8798       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8799     }
8800 
8801     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8802     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8803   }
8804 
8805   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8806   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8807 
8808   // If the source is floating point...
8809   if (SourceBT && SourceBT->isFloatingPoint()) {
8810     // ...and the target is floating point...
8811     if (TargetBT && TargetBT->isFloatingPoint()) {
8812       // ...then warn if we're dropping FP rank.
8813 
8814       // Builtin FP kinds are ordered by increasing FP rank.
8815       if (SourceBT->getKind() > TargetBT->getKind()) {
8816         // Don't warn about float constants that are precisely
8817         // representable in the target type.
8818         Expr::EvalResult result;
8819         if (E->EvaluateAsRValue(result, S.Context)) {
8820           // Value might be a float, a float vector, or a float complex.
8821           if (IsSameFloatAfterCast(result.Val,
8822                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8823                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
8824             return;
8825         }
8826 
8827         if (S.SourceMgr.isInSystemMacro(CC))
8828           return;
8829 
8830         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
8831       }
8832       // ... or possibly if we're increasing rank, too
8833       else if (TargetBT->getKind() > SourceBT->getKind()) {
8834         if (S.SourceMgr.isInSystemMacro(CC))
8835           return;
8836 
8837         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
8838       }
8839       return;
8840     }
8841 
8842     // If the target is integral, always warn.
8843     if (TargetBT && TargetBT->isInteger()) {
8844       if (S.SourceMgr.isInSystemMacro(CC))
8845         return;
8846 
8847       DiagnoseFloatingImpCast(S, E, T, CC);
8848     }
8849 
8850     // Detect the case where a call result is converted from floating-point to
8851     // to bool, and the final argument to the call is converted from bool, to
8852     // discover this typo:
8853     //
8854     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
8855     //
8856     // FIXME: This is an incredibly special case; is there some more general
8857     // way to detect this class of misplaced-parentheses bug?
8858     if (Target->isBooleanType() && isa<CallExpr>(E)) {
8859       // Check last argument of function call to see if it is an
8860       // implicit cast from a type matching the type the result
8861       // is being cast to.
8862       CallExpr *CEx = cast<CallExpr>(E);
8863       if (unsigned NumArgs = CEx->getNumArgs()) {
8864         Expr *LastA = CEx->getArg(NumArgs - 1);
8865         Expr *InnerE = LastA->IgnoreParenImpCasts();
8866         if (isa<ImplicitCastExpr>(LastA) &&
8867             InnerE->getType()->isBooleanType()) {
8868           // Warn on this floating-point to bool conversion
8869           DiagnoseImpCast(S, E, T, CC,
8870                           diag::warn_impcast_floating_point_to_bool);
8871         }
8872       }
8873     }
8874     return;
8875   }
8876 
8877   DiagnoseNullConversion(S, E, T, CC);
8878 
8879   S.DiscardMisalignedMemberAddress(Target, E);
8880 
8881   if (!Source->isIntegerType() || !Target->isIntegerType())
8882     return;
8883 
8884   // TODO: remove this early return once the false positives for constant->bool
8885   // in templates, macros, etc, are reduced or removed.
8886   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8887     return;
8888 
8889   IntRange SourceRange = GetExprRange(S.Context, E);
8890   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
8891 
8892   if (SourceRange.Width > TargetRange.Width) {
8893     // If the source is a constant, use a default-on diagnostic.
8894     // TODO: this should happen for bitfield stores, too.
8895     llvm::APSInt Value(32);
8896     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
8897       if (S.SourceMgr.isInSystemMacro(CC))
8898         return;
8899 
8900       std::string PrettySourceValue = Value.toString(10);
8901       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8902 
8903       S.DiagRuntimeBehavior(E->getExprLoc(), E,
8904         S.PDiag(diag::warn_impcast_integer_precision_constant)
8905             << PrettySourceValue << PrettyTargetValue
8906             << E->getType() << T << E->getSourceRange()
8907             << clang::SourceRange(CC));
8908       return;
8909     }
8910 
8911     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8912     if (S.SourceMgr.isInSystemMacro(CC))
8913       return;
8914 
8915     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
8916       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8917                              /* pruneControlFlow */ true);
8918     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
8919   }
8920 
8921   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8922       SourceRange.NonNegative && Source->isSignedIntegerType()) {
8923     // Warn when doing a signed to signed conversion, warn if the positive
8924     // source value is exactly the width of the target type, which will
8925     // cause a negative value to be stored.
8926 
8927     llvm::APSInt Value;
8928     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8929         !S.SourceMgr.isInSystemMacro(CC)) {
8930       if (isSameWidthConstantConversion(S, E, T, CC)) {
8931         std::string PrettySourceValue = Value.toString(10);
8932         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8933 
8934         S.DiagRuntimeBehavior(
8935             E->getExprLoc(), E,
8936             S.PDiag(diag::warn_impcast_integer_precision_constant)
8937                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8938                 << E->getSourceRange() << clang::SourceRange(CC));
8939         return;
8940       }
8941     }
8942 
8943     // Fall through for non-constants to give a sign conversion warning.
8944   }
8945 
8946   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8947       (!TargetRange.NonNegative && SourceRange.NonNegative &&
8948        SourceRange.Width == TargetRange.Width)) {
8949     if (S.SourceMgr.isInSystemMacro(CC))
8950       return;
8951 
8952     unsigned DiagID = diag::warn_impcast_integer_sign;
8953 
8954     // Traditionally, gcc has warned about this under -Wsign-compare.
8955     // We also want to warn about it in -Wconversion.
8956     // So if -Wconversion is off, use a completely identical diagnostic
8957     // in the sign-compare group.
8958     // The conditional-checking code will
8959     if (ICContext) {
8960       DiagID = diag::warn_impcast_integer_sign_conditional;
8961       *ICContext = true;
8962     }
8963 
8964     return DiagnoseImpCast(S, E, T, CC, DiagID);
8965   }
8966 
8967   // Diagnose conversions between different enumeration types.
8968   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8969   // type, to give us better diagnostics.
8970   QualType SourceType = E->getType();
8971   if (!S.getLangOpts().CPlusPlus) {
8972     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8973       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8974         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8975         SourceType = S.Context.getTypeDeclType(Enum);
8976         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8977       }
8978   }
8979 
8980   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8981     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
8982       if (SourceEnum->getDecl()->hasNameForLinkage() &&
8983           TargetEnum->getDecl()->hasNameForLinkage() &&
8984           SourceEnum != TargetEnum) {
8985         if (S.SourceMgr.isInSystemMacro(CC))
8986           return;
8987 
8988         return DiagnoseImpCast(S, E, SourceType, T, CC,
8989                                diag::warn_impcast_different_enum_types);
8990       }
8991 }
8992 
8993 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8994                               SourceLocation CC, QualType T);
8995 
8996 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
8997                              SourceLocation CC, bool &ICContext) {
8998   E = E->IgnoreParenImpCasts();
8999 
9000   if (isa<ConditionalOperator>(E))
9001     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9002 
9003   AnalyzeImplicitConversions(S, E, CC);
9004   if (E->getType() != T)
9005     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9006 }
9007 
9008 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9009                               SourceLocation CC, QualType T) {
9010   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9011 
9012   bool Suspicious = false;
9013   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9014   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9015 
9016   // If -Wconversion would have warned about either of the candidates
9017   // for a signedness conversion to the context type...
9018   if (!Suspicious) return;
9019 
9020   // ...but it's currently ignored...
9021   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9022     return;
9023 
9024   // ...then check whether it would have warned about either of the
9025   // candidates for a signedness conversion to the condition type.
9026   if (E->getType() == T) return;
9027 
9028   Suspicious = false;
9029   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9030                           E->getType(), CC, &Suspicious);
9031   if (!Suspicious)
9032     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9033                             E->getType(), CC, &Suspicious);
9034 }
9035 
9036 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9037 /// Input argument E is a logical expression.
9038 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9039   if (S.getLangOpts().Bool)
9040     return;
9041   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9042 }
9043 
9044 /// AnalyzeImplicitConversions - Find and report any interesting
9045 /// implicit conversions in the given expression.  There are a couple
9046 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9047 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9048   QualType T = OrigE->getType();
9049   Expr *E = OrigE->IgnoreParenImpCasts();
9050 
9051   if (E->isTypeDependent() || E->isValueDependent())
9052     return;
9053 
9054   // For conditional operators, we analyze the arguments as if they
9055   // were being fed directly into the output.
9056   if (isa<ConditionalOperator>(E)) {
9057     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9058     CheckConditionalOperator(S, CO, CC, T);
9059     return;
9060   }
9061 
9062   // Check implicit argument conversions for function calls.
9063   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9064     CheckImplicitArgumentConversions(S, Call, CC);
9065 
9066   // Go ahead and check any implicit conversions we might have skipped.
9067   // The non-canonical typecheck is just an optimization;
9068   // CheckImplicitConversion will filter out dead implicit conversions.
9069   if (E->getType() != T)
9070     CheckImplicitConversion(S, E, T, CC);
9071 
9072   // Now continue drilling into this expression.
9073 
9074   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9075     // The bound subexpressions in a PseudoObjectExpr are not reachable
9076     // as transitive children.
9077     // FIXME: Use a more uniform representation for this.
9078     for (auto *SE : POE->semantics())
9079       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9080         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9081   }
9082 
9083   // Skip past explicit casts.
9084   if (isa<ExplicitCastExpr>(E)) {
9085     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9086     return AnalyzeImplicitConversions(S, E, CC);
9087   }
9088 
9089   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9090     // Do a somewhat different check with comparison operators.
9091     if (BO->isComparisonOp())
9092       return AnalyzeComparison(S, BO);
9093 
9094     // And with simple assignments.
9095     if (BO->getOpcode() == BO_Assign)
9096       return AnalyzeAssignment(S, BO);
9097   }
9098 
9099   // These break the otherwise-useful invariant below.  Fortunately,
9100   // we don't really need to recurse into them, because any internal
9101   // expressions should have been analyzed already when they were
9102   // built into statements.
9103   if (isa<StmtExpr>(E)) return;
9104 
9105   // Don't descend into unevaluated contexts.
9106   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9107 
9108   // Now just recurse over the expression's children.
9109   CC = E->getExprLoc();
9110   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9111   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9112   for (Stmt *SubStmt : E->children()) {
9113     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9114     if (!ChildExpr)
9115       continue;
9116 
9117     if (IsLogicalAndOperator &&
9118         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9119       // Ignore checking string literals that are in logical and operators.
9120       // This is a common pattern for asserts.
9121       continue;
9122     AnalyzeImplicitConversions(S, ChildExpr, CC);
9123   }
9124 
9125   if (BO && BO->isLogicalOp()) {
9126     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9127     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9128       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9129 
9130     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9131     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9132       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9133   }
9134 
9135   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9136     if (U->getOpcode() == UO_LNot)
9137       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9138 }
9139 
9140 } // end anonymous namespace
9141 
9142 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
9143                                             unsigned Start, unsigned End) {
9144   bool IllegalParams = false;
9145   for (unsigned I = Start; I <= End; ++I) {
9146     QualType Ty = TheCall->getArg(I)->getType();
9147     // Taking into account implicit conversions,
9148     // allow any integer within 32 bits range
9149     if (!Ty->isIntegerType() ||
9150         S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
9151       S.Diag(TheCall->getArg(I)->getLocStart(),
9152              diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9153       IllegalParams = true;
9154     }
9155     // Potentially emit standard warnings for implicit conversions if enabled
9156     // using -Wconversion.
9157     CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
9158                             TheCall->getArg(I)->getLocStart());
9159   }
9160   return IllegalParams;
9161 }
9162 
9163 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9164 // Returns true when emitting a warning about taking the address of a reference.
9165 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9166                               const PartialDiagnostic &PD) {
9167   E = E->IgnoreParenImpCasts();
9168 
9169   const FunctionDecl *FD = nullptr;
9170 
9171   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9172     if (!DRE->getDecl()->getType()->isReferenceType())
9173       return false;
9174   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9175     if (!M->getMemberDecl()->getType()->isReferenceType())
9176       return false;
9177   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9178     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9179       return false;
9180     FD = Call->getDirectCallee();
9181   } else {
9182     return false;
9183   }
9184 
9185   SemaRef.Diag(E->getExprLoc(), PD);
9186 
9187   // If possible, point to location of function.
9188   if (FD) {
9189     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9190   }
9191 
9192   return true;
9193 }
9194 
9195 // Returns true if the SourceLocation is expanded from any macro body.
9196 // Returns false if the SourceLocation is invalid, is from not in a macro
9197 // expansion, or is from expanded from a top-level macro argument.
9198 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9199   if (Loc.isInvalid())
9200     return false;
9201 
9202   while (Loc.isMacroID()) {
9203     if (SM.isMacroBodyExpansion(Loc))
9204       return true;
9205     Loc = SM.getImmediateMacroCallerLoc(Loc);
9206   }
9207 
9208   return false;
9209 }
9210 
9211 /// \brief Diagnose pointers that are always non-null.
9212 /// \param E the expression containing the pointer
9213 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9214 /// compared to a null pointer
9215 /// \param IsEqual True when the comparison is equal to a null pointer
9216 /// \param Range Extra SourceRange to highlight in the diagnostic
9217 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9218                                         Expr::NullPointerConstantKind NullKind,
9219                                         bool IsEqual, SourceRange Range) {
9220   if (!E)
9221     return;
9222 
9223   // Don't warn inside macros.
9224   if (E->getExprLoc().isMacroID()) {
9225     const SourceManager &SM = getSourceManager();
9226     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9227         IsInAnyMacroBody(SM, Range.getBegin()))
9228       return;
9229   }
9230   E = E->IgnoreImpCasts();
9231 
9232   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9233 
9234   if (isa<CXXThisExpr>(E)) {
9235     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9236                                 : diag::warn_this_bool_conversion;
9237     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9238     return;
9239   }
9240 
9241   bool IsAddressOf = false;
9242 
9243   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9244     if (UO->getOpcode() != UO_AddrOf)
9245       return;
9246     IsAddressOf = true;
9247     E = UO->getSubExpr();
9248   }
9249 
9250   if (IsAddressOf) {
9251     unsigned DiagID = IsCompare
9252                           ? diag::warn_address_of_reference_null_compare
9253                           : diag::warn_address_of_reference_bool_conversion;
9254     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9255                                          << IsEqual;
9256     if (CheckForReference(*this, E, PD)) {
9257       return;
9258     }
9259   }
9260 
9261   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9262     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9263     std::string Str;
9264     llvm::raw_string_ostream S(Str);
9265     E->printPretty(S, nullptr, getPrintingPolicy());
9266     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9267                                 : diag::warn_cast_nonnull_to_bool;
9268     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9269       << E->getSourceRange() << Range << IsEqual;
9270     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9271   };
9272 
9273   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9274   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9275     if (auto *Callee = Call->getDirectCallee()) {
9276       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9277         ComplainAboutNonnullParamOrCall(A);
9278         return;
9279       }
9280     }
9281   }
9282 
9283   // Expect to find a single Decl.  Skip anything more complicated.
9284   ValueDecl *D = nullptr;
9285   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9286     D = R->getDecl();
9287   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9288     D = M->getMemberDecl();
9289   }
9290 
9291   // Weak Decls can be null.
9292   if (!D || D->isWeak())
9293     return;
9294 
9295   // Check for parameter decl with nonnull attribute
9296   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9297     if (getCurFunction() &&
9298         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9299       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9300         ComplainAboutNonnullParamOrCall(A);
9301         return;
9302       }
9303 
9304       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9305         auto ParamIter = llvm::find(FD->parameters(), PV);
9306         assert(ParamIter != FD->param_end());
9307         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9308 
9309         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9310           if (!NonNull->args_size()) {
9311               ComplainAboutNonnullParamOrCall(NonNull);
9312               return;
9313           }
9314 
9315           for (unsigned ArgNo : NonNull->args()) {
9316             if (ArgNo == ParamNo) {
9317               ComplainAboutNonnullParamOrCall(NonNull);
9318               return;
9319             }
9320           }
9321         }
9322       }
9323     }
9324   }
9325 
9326   QualType T = D->getType();
9327   const bool IsArray = T->isArrayType();
9328   const bool IsFunction = T->isFunctionType();
9329 
9330   // Address of function is used to silence the function warning.
9331   if (IsAddressOf && IsFunction) {
9332     return;
9333   }
9334 
9335   // Found nothing.
9336   if (!IsAddressOf && !IsFunction && !IsArray)
9337     return;
9338 
9339   // Pretty print the expression for the diagnostic.
9340   std::string Str;
9341   llvm::raw_string_ostream S(Str);
9342   E->printPretty(S, nullptr, getPrintingPolicy());
9343 
9344   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9345                               : diag::warn_impcast_pointer_to_bool;
9346   enum {
9347     AddressOf,
9348     FunctionPointer,
9349     ArrayPointer
9350   } DiagType;
9351   if (IsAddressOf)
9352     DiagType = AddressOf;
9353   else if (IsFunction)
9354     DiagType = FunctionPointer;
9355   else if (IsArray)
9356     DiagType = ArrayPointer;
9357   else
9358     llvm_unreachable("Could not determine diagnostic.");
9359   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9360                                 << Range << IsEqual;
9361 
9362   if (!IsFunction)
9363     return;
9364 
9365   // Suggest '&' to silence the function warning.
9366   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9367       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9368 
9369   // Check to see if '()' fixit should be emitted.
9370   QualType ReturnType;
9371   UnresolvedSet<4> NonTemplateOverloads;
9372   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9373   if (ReturnType.isNull())
9374     return;
9375 
9376   if (IsCompare) {
9377     // There are two cases here.  If there is null constant, the only suggest
9378     // for a pointer return type.  If the null is 0, then suggest if the return
9379     // type is a pointer or an integer type.
9380     if (!ReturnType->isPointerType()) {
9381       if (NullKind == Expr::NPCK_ZeroExpression ||
9382           NullKind == Expr::NPCK_ZeroLiteral) {
9383         if (!ReturnType->isIntegerType())
9384           return;
9385       } else {
9386         return;
9387       }
9388     }
9389   } else { // !IsCompare
9390     // For function to bool, only suggest if the function pointer has bool
9391     // return type.
9392     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9393       return;
9394   }
9395   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9396       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9397 }
9398 
9399 /// Diagnoses "dangerous" implicit conversions within the given
9400 /// expression (which is a full expression).  Implements -Wconversion
9401 /// and -Wsign-compare.
9402 ///
9403 /// \param CC the "context" location of the implicit conversion, i.e.
9404 ///   the most location of the syntactic entity requiring the implicit
9405 ///   conversion
9406 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9407   // Don't diagnose in unevaluated contexts.
9408   if (isUnevaluatedContext())
9409     return;
9410 
9411   // Don't diagnose for value- or type-dependent expressions.
9412   if (E->isTypeDependent() || E->isValueDependent())
9413     return;
9414 
9415   // Check for array bounds violations in cases where the check isn't triggered
9416   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9417   // ArraySubscriptExpr is on the RHS of a variable initialization.
9418   CheckArrayAccess(E);
9419 
9420   // This is not the right CC for (e.g.) a variable initialization.
9421   AnalyzeImplicitConversions(*this, E, CC);
9422 }
9423 
9424 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9425 /// Input argument E is a logical expression.
9426 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9427   ::CheckBoolLikeConversion(*this, E, CC);
9428 }
9429 
9430 /// Diagnose when expression is an integer constant expression and its evaluation
9431 /// results in integer overflow
9432 void Sema::CheckForIntOverflow (Expr *E) {
9433   // Use a work list to deal with nested struct initializers.
9434   SmallVector<Expr *, 2> Exprs(1, E);
9435 
9436   do {
9437     Expr *E = Exprs.pop_back_val();
9438 
9439     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9440       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9441       continue;
9442     }
9443 
9444     if (auto InitList = dyn_cast<InitListExpr>(E))
9445       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9446   } while (!Exprs.empty());
9447 }
9448 
9449 namespace {
9450 /// \brief Visitor for expressions which looks for unsequenced operations on the
9451 /// same object.
9452 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9453   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9454 
9455   /// \brief A tree of sequenced regions within an expression. Two regions are
9456   /// unsequenced if one is an ancestor or a descendent of the other. When we
9457   /// finish processing an expression with sequencing, such as a comma
9458   /// expression, we fold its tree nodes into its parent, since they are
9459   /// unsequenced with respect to nodes we will visit later.
9460   class SequenceTree {
9461     struct Value {
9462       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9463       unsigned Parent : 31;
9464       unsigned Merged : 1;
9465     };
9466     SmallVector<Value, 8> Values;
9467 
9468   public:
9469     /// \brief A region within an expression which may be sequenced with respect
9470     /// to some other region.
9471     class Seq {
9472       explicit Seq(unsigned N) : Index(N) {}
9473       unsigned Index;
9474       friend class SequenceTree;
9475     public:
9476       Seq() : Index(0) {}
9477     };
9478 
9479     SequenceTree() { Values.push_back(Value(0)); }
9480     Seq root() const { return Seq(0); }
9481 
9482     /// \brief Create a new sequence of operations, which is an unsequenced
9483     /// subset of \p Parent. This sequence of operations is sequenced with
9484     /// respect to other children of \p Parent.
9485     Seq allocate(Seq Parent) {
9486       Values.push_back(Value(Parent.Index));
9487       return Seq(Values.size() - 1);
9488     }
9489 
9490     /// \brief Merge a sequence of operations into its parent.
9491     void merge(Seq S) {
9492       Values[S.Index].Merged = true;
9493     }
9494 
9495     /// \brief Determine whether two operations are unsequenced. This operation
9496     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9497     /// should have been merged into its parent as appropriate.
9498     bool isUnsequenced(Seq Cur, Seq Old) {
9499       unsigned C = representative(Cur.Index);
9500       unsigned Target = representative(Old.Index);
9501       while (C >= Target) {
9502         if (C == Target)
9503           return true;
9504         C = Values[C].Parent;
9505       }
9506       return false;
9507     }
9508 
9509   private:
9510     /// \brief Pick a representative for a sequence.
9511     unsigned representative(unsigned K) {
9512       if (Values[K].Merged)
9513         // Perform path compression as we go.
9514         return Values[K].Parent = representative(Values[K].Parent);
9515       return K;
9516     }
9517   };
9518 
9519   /// An object for which we can track unsequenced uses.
9520   typedef NamedDecl *Object;
9521 
9522   /// Different flavors of object usage which we track. We only track the
9523   /// least-sequenced usage of each kind.
9524   enum UsageKind {
9525     /// A read of an object. Multiple unsequenced reads are OK.
9526     UK_Use,
9527     /// A modification of an object which is sequenced before the value
9528     /// computation of the expression, such as ++n in C++.
9529     UK_ModAsValue,
9530     /// A modification of an object which is not sequenced before the value
9531     /// computation of the expression, such as n++.
9532     UK_ModAsSideEffect,
9533 
9534     UK_Count = UK_ModAsSideEffect + 1
9535   };
9536 
9537   struct Usage {
9538     Usage() : Use(nullptr), Seq() {}
9539     Expr *Use;
9540     SequenceTree::Seq Seq;
9541   };
9542 
9543   struct UsageInfo {
9544     UsageInfo() : Diagnosed(false) {}
9545     Usage Uses[UK_Count];
9546     /// Have we issued a diagnostic for this variable already?
9547     bool Diagnosed;
9548   };
9549   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9550 
9551   Sema &SemaRef;
9552   /// Sequenced regions within the expression.
9553   SequenceTree Tree;
9554   /// Declaration modifications and references which we have seen.
9555   UsageInfoMap UsageMap;
9556   /// The region we are currently within.
9557   SequenceTree::Seq Region;
9558   /// Filled in with declarations which were modified as a side-effect
9559   /// (that is, post-increment operations).
9560   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9561   /// Expressions to check later. We defer checking these to reduce
9562   /// stack usage.
9563   SmallVectorImpl<Expr *> &WorkList;
9564 
9565   /// RAII object wrapping the visitation of a sequenced subexpression of an
9566   /// expression. At the end of this process, the side-effects of the evaluation
9567   /// become sequenced with respect to the value computation of the result, so
9568   /// we downgrade any UK_ModAsSideEffect within the evaluation to
9569   /// UK_ModAsValue.
9570   struct SequencedSubexpression {
9571     SequencedSubexpression(SequenceChecker &Self)
9572       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9573       Self.ModAsSideEffect = &ModAsSideEffect;
9574     }
9575     ~SequencedSubexpression() {
9576       for (auto &M : llvm::reverse(ModAsSideEffect)) {
9577         UsageInfo &U = Self.UsageMap[M.first];
9578         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9579         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9580         SideEffectUsage = M.second;
9581       }
9582       Self.ModAsSideEffect = OldModAsSideEffect;
9583     }
9584 
9585     SequenceChecker &Self;
9586     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9587     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9588   };
9589 
9590   /// RAII object wrapping the visitation of a subexpression which we might
9591   /// choose to evaluate as a constant. If any subexpression is evaluated and
9592   /// found to be non-constant, this allows us to suppress the evaluation of
9593   /// the outer expression.
9594   class EvaluationTracker {
9595   public:
9596     EvaluationTracker(SequenceChecker &Self)
9597         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9598       Self.EvalTracker = this;
9599     }
9600     ~EvaluationTracker() {
9601       Self.EvalTracker = Prev;
9602       if (Prev)
9603         Prev->EvalOK &= EvalOK;
9604     }
9605 
9606     bool evaluate(const Expr *E, bool &Result) {
9607       if (!EvalOK || E->isValueDependent())
9608         return false;
9609       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9610       return EvalOK;
9611     }
9612 
9613   private:
9614     SequenceChecker &Self;
9615     EvaluationTracker *Prev;
9616     bool EvalOK;
9617   } *EvalTracker;
9618 
9619   /// \brief Find the object which is produced by the specified expression,
9620   /// if any.
9621   Object getObject(Expr *E, bool Mod) const {
9622     E = E->IgnoreParenCasts();
9623     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9624       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9625         return getObject(UO->getSubExpr(), Mod);
9626     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9627       if (BO->getOpcode() == BO_Comma)
9628         return getObject(BO->getRHS(), Mod);
9629       if (Mod && BO->isAssignmentOp())
9630         return getObject(BO->getLHS(), Mod);
9631     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9632       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9633       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9634         return ME->getMemberDecl();
9635     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9636       // FIXME: If this is a reference, map through to its value.
9637       return DRE->getDecl();
9638     return nullptr;
9639   }
9640 
9641   /// \brief Note that an object was modified or used by an expression.
9642   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9643     Usage &U = UI.Uses[UK];
9644     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9645       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9646         ModAsSideEffect->push_back(std::make_pair(O, U));
9647       U.Use = Ref;
9648       U.Seq = Region;
9649     }
9650   }
9651   /// \brief Check whether a modification or use conflicts with a prior usage.
9652   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9653                   bool IsModMod) {
9654     if (UI.Diagnosed)
9655       return;
9656 
9657     const Usage &U = UI.Uses[OtherKind];
9658     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9659       return;
9660 
9661     Expr *Mod = U.Use;
9662     Expr *ModOrUse = Ref;
9663     if (OtherKind == UK_Use)
9664       std::swap(Mod, ModOrUse);
9665 
9666     SemaRef.Diag(Mod->getExprLoc(),
9667                  IsModMod ? diag::warn_unsequenced_mod_mod
9668                           : diag::warn_unsequenced_mod_use)
9669       << O << SourceRange(ModOrUse->getExprLoc());
9670     UI.Diagnosed = true;
9671   }
9672 
9673   void notePreUse(Object O, Expr *Use) {
9674     UsageInfo &U = UsageMap[O];
9675     // Uses conflict with other modifications.
9676     checkUsage(O, U, Use, UK_ModAsValue, false);
9677   }
9678   void notePostUse(Object O, Expr *Use) {
9679     UsageInfo &U = UsageMap[O];
9680     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9681     addUsage(U, O, Use, UK_Use);
9682   }
9683 
9684   void notePreMod(Object O, Expr *Mod) {
9685     UsageInfo &U = UsageMap[O];
9686     // Modifications conflict with other modifications and with uses.
9687     checkUsage(O, U, Mod, UK_ModAsValue, true);
9688     checkUsage(O, U, Mod, UK_Use, false);
9689   }
9690   void notePostMod(Object O, Expr *Use, UsageKind UK) {
9691     UsageInfo &U = UsageMap[O];
9692     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9693     addUsage(U, O, Use, UK);
9694   }
9695 
9696 public:
9697   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9698       : Base(S.Context), SemaRef(S), Region(Tree.root()),
9699         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9700     Visit(E);
9701   }
9702 
9703   void VisitStmt(Stmt *S) {
9704     // Skip all statements which aren't expressions for now.
9705   }
9706 
9707   void VisitExpr(Expr *E) {
9708     // By default, just recurse to evaluated subexpressions.
9709     Base::VisitStmt(E);
9710   }
9711 
9712   void VisitCastExpr(CastExpr *E) {
9713     Object O = Object();
9714     if (E->getCastKind() == CK_LValueToRValue)
9715       O = getObject(E->getSubExpr(), false);
9716 
9717     if (O)
9718       notePreUse(O, E);
9719     VisitExpr(E);
9720     if (O)
9721       notePostUse(O, E);
9722   }
9723 
9724   void VisitBinComma(BinaryOperator *BO) {
9725     // C++11 [expr.comma]p1:
9726     //   Every value computation and side effect associated with the left
9727     //   expression is sequenced before every value computation and side
9728     //   effect associated with the right expression.
9729     SequenceTree::Seq LHS = Tree.allocate(Region);
9730     SequenceTree::Seq RHS = Tree.allocate(Region);
9731     SequenceTree::Seq OldRegion = Region;
9732 
9733     {
9734       SequencedSubexpression SeqLHS(*this);
9735       Region = LHS;
9736       Visit(BO->getLHS());
9737     }
9738 
9739     Region = RHS;
9740     Visit(BO->getRHS());
9741 
9742     Region = OldRegion;
9743 
9744     // Forget that LHS and RHS are sequenced. They are both unsequenced
9745     // with respect to other stuff.
9746     Tree.merge(LHS);
9747     Tree.merge(RHS);
9748   }
9749 
9750   void VisitBinAssign(BinaryOperator *BO) {
9751     // The modification is sequenced after the value computation of the LHS
9752     // and RHS, so check it before inspecting the operands and update the
9753     // map afterwards.
9754     Object O = getObject(BO->getLHS(), true);
9755     if (!O)
9756       return VisitExpr(BO);
9757 
9758     notePreMod(O, BO);
9759 
9760     // C++11 [expr.ass]p7:
9761     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9762     //   only once.
9763     //
9764     // Therefore, for a compound assignment operator, O is considered used
9765     // everywhere except within the evaluation of E1 itself.
9766     if (isa<CompoundAssignOperator>(BO))
9767       notePreUse(O, BO);
9768 
9769     Visit(BO->getLHS());
9770 
9771     if (isa<CompoundAssignOperator>(BO))
9772       notePostUse(O, BO);
9773 
9774     Visit(BO->getRHS());
9775 
9776     // C++11 [expr.ass]p1:
9777     //   the assignment is sequenced [...] before the value computation of the
9778     //   assignment expression.
9779     // C11 6.5.16/3 has no such rule.
9780     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9781                                                        : UK_ModAsSideEffect);
9782   }
9783 
9784   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9785     VisitBinAssign(CAO);
9786   }
9787 
9788   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9789   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9790   void VisitUnaryPreIncDec(UnaryOperator *UO) {
9791     Object O = getObject(UO->getSubExpr(), true);
9792     if (!O)
9793       return VisitExpr(UO);
9794 
9795     notePreMod(O, UO);
9796     Visit(UO->getSubExpr());
9797     // C++11 [expr.pre.incr]p1:
9798     //   the expression ++x is equivalent to x+=1
9799     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9800                                                        : UK_ModAsSideEffect);
9801   }
9802 
9803   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9804   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9805   void VisitUnaryPostIncDec(UnaryOperator *UO) {
9806     Object O = getObject(UO->getSubExpr(), true);
9807     if (!O)
9808       return VisitExpr(UO);
9809 
9810     notePreMod(O, UO);
9811     Visit(UO->getSubExpr());
9812     notePostMod(O, UO, UK_ModAsSideEffect);
9813   }
9814 
9815   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9816   void VisitBinLOr(BinaryOperator *BO) {
9817     // The side-effects of the LHS of an '&&' are sequenced before the
9818     // value computation of the RHS, and hence before the value computation
9819     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9820     // as if they were unconditionally sequenced.
9821     EvaluationTracker Eval(*this);
9822     {
9823       SequencedSubexpression Sequenced(*this);
9824       Visit(BO->getLHS());
9825     }
9826 
9827     bool Result;
9828     if (Eval.evaluate(BO->getLHS(), Result)) {
9829       if (!Result)
9830         Visit(BO->getRHS());
9831     } else {
9832       // Check for unsequenced operations in the RHS, treating it as an
9833       // entirely separate evaluation.
9834       //
9835       // FIXME: If there are operations in the RHS which are unsequenced
9836       // with respect to operations outside the RHS, and those operations
9837       // are unconditionally evaluated, diagnose them.
9838       WorkList.push_back(BO->getRHS());
9839     }
9840   }
9841   void VisitBinLAnd(BinaryOperator *BO) {
9842     EvaluationTracker Eval(*this);
9843     {
9844       SequencedSubexpression Sequenced(*this);
9845       Visit(BO->getLHS());
9846     }
9847 
9848     bool Result;
9849     if (Eval.evaluate(BO->getLHS(), Result)) {
9850       if (Result)
9851         Visit(BO->getRHS());
9852     } else {
9853       WorkList.push_back(BO->getRHS());
9854     }
9855   }
9856 
9857   // Only visit the condition, unless we can be sure which subexpression will
9858   // be chosen.
9859   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
9860     EvaluationTracker Eval(*this);
9861     {
9862       SequencedSubexpression Sequenced(*this);
9863       Visit(CO->getCond());
9864     }
9865 
9866     bool Result;
9867     if (Eval.evaluate(CO->getCond(), Result))
9868       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
9869     else {
9870       WorkList.push_back(CO->getTrueExpr());
9871       WorkList.push_back(CO->getFalseExpr());
9872     }
9873   }
9874 
9875   void VisitCallExpr(CallExpr *CE) {
9876     // C++11 [intro.execution]p15:
9877     //   When calling a function [...], every value computation and side effect
9878     //   associated with any argument expression, or with the postfix expression
9879     //   designating the called function, is sequenced before execution of every
9880     //   expression or statement in the body of the function [and thus before
9881     //   the value computation of its result].
9882     SequencedSubexpression Sequenced(*this);
9883     Base::VisitCallExpr(CE);
9884 
9885     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9886   }
9887 
9888   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
9889     // This is a call, so all subexpressions are sequenced before the result.
9890     SequencedSubexpression Sequenced(*this);
9891 
9892     if (!CCE->isListInitialization())
9893       return VisitExpr(CCE);
9894 
9895     // In C++11, list initializations are sequenced.
9896     SmallVector<SequenceTree::Seq, 32> Elts;
9897     SequenceTree::Seq Parent = Region;
9898     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9899                                         E = CCE->arg_end();
9900          I != E; ++I) {
9901       Region = Tree.allocate(Parent);
9902       Elts.push_back(Region);
9903       Visit(*I);
9904     }
9905 
9906     // Forget that the initializers are sequenced.
9907     Region = Parent;
9908     for (unsigned I = 0; I < Elts.size(); ++I)
9909       Tree.merge(Elts[I]);
9910   }
9911 
9912   void VisitInitListExpr(InitListExpr *ILE) {
9913     if (!SemaRef.getLangOpts().CPlusPlus11)
9914       return VisitExpr(ILE);
9915 
9916     // In C++11, list initializations are sequenced.
9917     SmallVector<SequenceTree::Seq, 32> Elts;
9918     SequenceTree::Seq Parent = Region;
9919     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9920       Expr *E = ILE->getInit(I);
9921       if (!E) continue;
9922       Region = Tree.allocate(Parent);
9923       Elts.push_back(Region);
9924       Visit(E);
9925     }
9926 
9927     // Forget that the initializers are sequenced.
9928     Region = Parent;
9929     for (unsigned I = 0; I < Elts.size(); ++I)
9930       Tree.merge(Elts[I]);
9931   }
9932 };
9933 } // end anonymous namespace
9934 
9935 void Sema::CheckUnsequencedOperations(Expr *E) {
9936   SmallVector<Expr *, 8> WorkList;
9937   WorkList.push_back(E);
9938   while (!WorkList.empty()) {
9939     Expr *Item = WorkList.pop_back_val();
9940     SequenceChecker(*this, Item, WorkList);
9941   }
9942 }
9943 
9944 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9945                               bool IsConstexpr) {
9946   CheckImplicitConversions(E, CheckLoc);
9947   if (!E->isInstantiationDependent())
9948     CheckUnsequencedOperations(E);
9949   if (!IsConstexpr && !E->isValueDependent())
9950     CheckForIntOverflow(E);
9951   DiagnoseMisalignedMembers();
9952 }
9953 
9954 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9955                                        FieldDecl *BitField,
9956                                        Expr *Init) {
9957   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9958 }
9959 
9960 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9961                                          SourceLocation Loc) {
9962   if (!PType->isVariablyModifiedType())
9963     return;
9964   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9965     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9966     return;
9967   }
9968   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9969     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9970     return;
9971   }
9972   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9973     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9974     return;
9975   }
9976 
9977   const ArrayType *AT = S.Context.getAsArrayType(PType);
9978   if (!AT)
9979     return;
9980 
9981   if (AT->getSizeModifier() != ArrayType::Star) {
9982     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9983     return;
9984   }
9985 
9986   S.Diag(Loc, diag::err_array_star_in_function_definition);
9987 }
9988 
9989 /// CheckParmsForFunctionDef - Check that the parameters of the given
9990 /// function are appropriate for the definition of a function. This
9991 /// takes care of any checks that cannot be performed on the
9992 /// declaration itself, e.g., that the types of each of the function
9993 /// parameters are complete.
9994 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
9995                                     bool CheckParameterNames) {
9996   bool HasInvalidParm = false;
9997   for (ParmVarDecl *Param : Parameters) {
9998     // C99 6.7.5.3p4: the parameters in a parameter type list in a
9999     // function declarator that is part of a function definition of
10000     // that function shall not have incomplete type.
10001     //
10002     // This is also C++ [dcl.fct]p6.
10003     if (!Param->isInvalidDecl() &&
10004         RequireCompleteType(Param->getLocation(), Param->getType(),
10005                             diag::err_typecheck_decl_incomplete_type)) {
10006       Param->setInvalidDecl();
10007       HasInvalidParm = true;
10008     }
10009 
10010     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10011     // declaration of each parameter shall include an identifier.
10012     if (CheckParameterNames &&
10013         Param->getIdentifier() == nullptr &&
10014         !Param->isImplicit() &&
10015         !getLangOpts().CPlusPlus)
10016       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10017 
10018     // C99 6.7.5.3p12:
10019     //   If the function declarator is not part of a definition of that
10020     //   function, parameters may have incomplete type and may use the [*]
10021     //   notation in their sequences of declarator specifiers to specify
10022     //   variable length array types.
10023     QualType PType = Param->getOriginalType();
10024     // FIXME: This diagnostic should point the '[*]' if source-location
10025     // information is added for it.
10026     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10027 
10028     // MSVC destroys objects passed by value in the callee.  Therefore a
10029     // function definition which takes such a parameter must be able to call the
10030     // object's destructor.  However, we don't perform any direct access check
10031     // on the dtor.
10032     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10033                                        .getCXXABI()
10034                                        .areArgsDestroyedLeftToRightInCallee()) {
10035       if (!Param->isInvalidDecl()) {
10036         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10037           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10038           if (!ClassDecl->isInvalidDecl() &&
10039               !ClassDecl->hasIrrelevantDestructor() &&
10040               !ClassDecl->isDependentContext()) {
10041             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10042             MarkFunctionReferenced(Param->getLocation(), Destructor);
10043             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10044           }
10045         }
10046       }
10047     }
10048 
10049     // Parameters with the pass_object_size attribute only need to be marked
10050     // constant at function definitions. Because we lack information about
10051     // whether we're on a declaration or definition when we're instantiating the
10052     // attribute, we need to check for constness here.
10053     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10054       if (!Param->getType().isConstQualified())
10055         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10056             << Attr->getSpelling() << 1;
10057   }
10058 
10059   return HasInvalidParm;
10060 }
10061 
10062 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10063 /// pointer cast increases the alignment requirements.
10064 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10065   // This is actually a lot of work to potentially be doing on every
10066   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10067   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10068     return;
10069 
10070   // Ignore dependent types.
10071   if (T->isDependentType() || Op->getType()->isDependentType())
10072     return;
10073 
10074   // Require that the destination be a pointer type.
10075   const PointerType *DestPtr = T->getAs<PointerType>();
10076   if (!DestPtr) return;
10077 
10078   // If the destination has alignment 1, we're done.
10079   QualType DestPointee = DestPtr->getPointeeType();
10080   if (DestPointee->isIncompleteType()) return;
10081   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10082   if (DestAlign.isOne()) return;
10083 
10084   // Require that the source be a pointer type.
10085   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10086   if (!SrcPtr) return;
10087   QualType SrcPointee = SrcPtr->getPointeeType();
10088 
10089   // Whitelist casts from cv void*.  We already implicitly
10090   // whitelisted casts to cv void*, since they have alignment 1.
10091   // Also whitelist casts involving incomplete types, which implicitly
10092   // includes 'void'.
10093   if (SrcPointee->isIncompleteType()) return;
10094 
10095   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10096   if (SrcAlign >= DestAlign) return;
10097 
10098   Diag(TRange.getBegin(), diag::warn_cast_align)
10099     << Op->getType() << T
10100     << static_cast<unsigned>(SrcAlign.getQuantity())
10101     << static_cast<unsigned>(DestAlign.getQuantity())
10102     << TRange << Op->getSourceRange();
10103 }
10104 
10105 /// \brief Check whether this array fits the idiom of a size-one tail padded
10106 /// array member of a struct.
10107 ///
10108 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10109 /// commonly used to emulate flexible arrays in C89 code.
10110 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10111                                     const NamedDecl *ND) {
10112   if (Size != 1 || !ND) return false;
10113 
10114   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10115   if (!FD) return false;
10116 
10117   // Don't consider sizes resulting from macro expansions or template argument
10118   // substitution to form C89 tail-padded arrays.
10119 
10120   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10121   while (TInfo) {
10122     TypeLoc TL = TInfo->getTypeLoc();
10123     // Look through typedefs.
10124     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10125       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10126       TInfo = TDL->getTypeSourceInfo();
10127       continue;
10128     }
10129     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10130       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10131       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10132         return false;
10133     }
10134     break;
10135   }
10136 
10137   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10138   if (!RD) return false;
10139   if (RD->isUnion()) return false;
10140   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10141     if (!CRD->isStandardLayout()) return false;
10142   }
10143 
10144   // See if this is the last field decl in the record.
10145   const Decl *D = FD;
10146   while ((D = D->getNextDeclInContext()))
10147     if (isa<FieldDecl>(D))
10148       return false;
10149   return true;
10150 }
10151 
10152 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10153                             const ArraySubscriptExpr *ASE,
10154                             bool AllowOnePastEnd, bool IndexNegated) {
10155   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10156   if (IndexExpr->isValueDependent())
10157     return;
10158 
10159   const Type *EffectiveType =
10160       BaseExpr->getType()->getPointeeOrArrayElementType();
10161   BaseExpr = BaseExpr->IgnoreParenCasts();
10162   const ConstantArrayType *ArrayTy =
10163     Context.getAsConstantArrayType(BaseExpr->getType());
10164   if (!ArrayTy)
10165     return;
10166 
10167   llvm::APSInt index;
10168   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10169     return;
10170   if (IndexNegated)
10171     index = -index;
10172 
10173   const NamedDecl *ND = nullptr;
10174   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10175     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10176   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10177     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10178 
10179   if (index.isUnsigned() || !index.isNegative()) {
10180     llvm::APInt size = ArrayTy->getSize();
10181     if (!size.isStrictlyPositive())
10182       return;
10183 
10184     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10185     if (BaseType != EffectiveType) {
10186       // Make sure we're comparing apples to apples when comparing index to size
10187       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10188       uint64_t array_typesize = Context.getTypeSize(BaseType);
10189       // Handle ptrarith_typesize being zero, such as when casting to void*
10190       if (!ptrarith_typesize) ptrarith_typesize = 1;
10191       if (ptrarith_typesize != array_typesize) {
10192         // There's a cast to a different size type involved
10193         uint64_t ratio = array_typesize / ptrarith_typesize;
10194         // TODO: Be smarter about handling cases where array_typesize is not a
10195         // multiple of ptrarith_typesize
10196         if (ptrarith_typesize * ratio == array_typesize)
10197           size *= llvm::APInt(size.getBitWidth(), ratio);
10198       }
10199     }
10200 
10201     if (size.getBitWidth() > index.getBitWidth())
10202       index = index.zext(size.getBitWidth());
10203     else if (size.getBitWidth() < index.getBitWidth())
10204       size = size.zext(index.getBitWidth());
10205 
10206     // For array subscripting the index must be less than size, but for pointer
10207     // arithmetic also allow the index (offset) to be equal to size since
10208     // computing the next address after the end of the array is legal and
10209     // commonly done e.g. in C++ iterators and range-based for loops.
10210     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10211       return;
10212 
10213     // Also don't warn for arrays of size 1 which are members of some
10214     // structure. These are often used to approximate flexible arrays in C89
10215     // code.
10216     if (IsTailPaddedMemberArray(*this, size, ND))
10217       return;
10218 
10219     // Suppress the warning if the subscript expression (as identified by the
10220     // ']' location) and the index expression are both from macro expansions
10221     // within a system header.
10222     if (ASE) {
10223       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10224           ASE->getRBracketLoc());
10225       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10226         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10227             IndexExpr->getLocStart());
10228         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10229           return;
10230       }
10231     }
10232 
10233     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10234     if (ASE)
10235       DiagID = diag::warn_array_index_exceeds_bounds;
10236 
10237     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10238                         PDiag(DiagID) << index.toString(10, true)
10239                           << size.toString(10, true)
10240                           << (unsigned)size.getLimitedValue(~0U)
10241                           << IndexExpr->getSourceRange());
10242   } else {
10243     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10244     if (!ASE) {
10245       DiagID = diag::warn_ptr_arith_precedes_bounds;
10246       if (index.isNegative()) index = -index;
10247     }
10248 
10249     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10250                         PDiag(DiagID) << index.toString(10, true)
10251                           << IndexExpr->getSourceRange());
10252   }
10253 
10254   if (!ND) {
10255     // Try harder to find a NamedDecl to point at in the note.
10256     while (const ArraySubscriptExpr *ASE =
10257            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10258       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10259     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10260       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10261     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10262       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10263   }
10264 
10265   if (ND)
10266     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10267                         PDiag(diag::note_array_index_out_of_bounds)
10268                           << ND->getDeclName());
10269 }
10270 
10271 void Sema::CheckArrayAccess(const Expr *expr) {
10272   int AllowOnePastEnd = 0;
10273   while (expr) {
10274     expr = expr->IgnoreParenImpCasts();
10275     switch (expr->getStmtClass()) {
10276       case Stmt::ArraySubscriptExprClass: {
10277         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10278         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10279                          AllowOnePastEnd > 0);
10280         return;
10281       }
10282       case Stmt::OMPArraySectionExprClass: {
10283         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10284         if (ASE->getLowerBound())
10285           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10286                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
10287         return;
10288       }
10289       case Stmt::UnaryOperatorClass: {
10290         // Only unwrap the * and & unary operators
10291         const UnaryOperator *UO = cast<UnaryOperator>(expr);
10292         expr = UO->getSubExpr();
10293         switch (UO->getOpcode()) {
10294           case UO_AddrOf:
10295             AllowOnePastEnd++;
10296             break;
10297           case UO_Deref:
10298             AllowOnePastEnd--;
10299             break;
10300           default:
10301             return;
10302         }
10303         break;
10304       }
10305       case Stmt::ConditionalOperatorClass: {
10306         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10307         if (const Expr *lhs = cond->getLHS())
10308           CheckArrayAccess(lhs);
10309         if (const Expr *rhs = cond->getRHS())
10310           CheckArrayAccess(rhs);
10311         return;
10312       }
10313       default:
10314         return;
10315     }
10316   }
10317 }
10318 
10319 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10320 
10321 namespace {
10322   struct RetainCycleOwner {
10323     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10324     VarDecl *Variable;
10325     SourceRange Range;
10326     SourceLocation Loc;
10327     bool Indirect;
10328 
10329     void setLocsFrom(Expr *e) {
10330       Loc = e->getExprLoc();
10331       Range = e->getSourceRange();
10332     }
10333   };
10334 } // end anonymous namespace
10335 
10336 /// Consider whether capturing the given variable can possibly lead to
10337 /// a retain cycle.
10338 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10339   // In ARC, it's captured strongly iff the variable has __strong
10340   // lifetime.  In MRR, it's captured strongly if the variable is
10341   // __block and has an appropriate type.
10342   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10343     return false;
10344 
10345   owner.Variable = var;
10346   if (ref)
10347     owner.setLocsFrom(ref);
10348   return true;
10349 }
10350 
10351 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10352   while (true) {
10353     e = e->IgnoreParens();
10354     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10355       switch (cast->getCastKind()) {
10356       case CK_BitCast:
10357       case CK_LValueBitCast:
10358       case CK_LValueToRValue:
10359       case CK_ARCReclaimReturnedObject:
10360         e = cast->getSubExpr();
10361         continue;
10362 
10363       default:
10364         return false;
10365       }
10366     }
10367 
10368     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10369       ObjCIvarDecl *ivar = ref->getDecl();
10370       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10371         return false;
10372 
10373       // Try to find a retain cycle in the base.
10374       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10375         return false;
10376 
10377       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10378       owner.Indirect = true;
10379       return true;
10380     }
10381 
10382     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10383       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10384       if (!var) return false;
10385       return considerVariable(var, ref, owner);
10386     }
10387 
10388     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10389       if (member->isArrow()) return false;
10390 
10391       // Don't count this as an indirect ownership.
10392       e = member->getBase();
10393       continue;
10394     }
10395 
10396     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10397       // Only pay attention to pseudo-objects on property references.
10398       ObjCPropertyRefExpr *pre
10399         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10400                                               ->IgnoreParens());
10401       if (!pre) return false;
10402       if (pre->isImplicitProperty()) return false;
10403       ObjCPropertyDecl *property = pre->getExplicitProperty();
10404       if (!property->isRetaining() &&
10405           !(property->getPropertyIvarDecl() &&
10406             property->getPropertyIvarDecl()->getType()
10407               .getObjCLifetime() == Qualifiers::OCL_Strong))
10408           return false;
10409 
10410       owner.Indirect = true;
10411       if (pre->isSuperReceiver()) {
10412         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10413         if (!owner.Variable)
10414           return false;
10415         owner.Loc = pre->getLocation();
10416         owner.Range = pre->getSourceRange();
10417         return true;
10418       }
10419       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10420                               ->getSourceExpr());
10421       continue;
10422     }
10423 
10424     // Array ivars?
10425 
10426     return false;
10427   }
10428 }
10429 
10430 namespace {
10431   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10432     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10433       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10434         Context(Context), Variable(variable), Capturer(nullptr),
10435         VarWillBeReased(false) {}
10436     ASTContext &Context;
10437     VarDecl *Variable;
10438     Expr *Capturer;
10439     bool VarWillBeReased;
10440 
10441     void VisitDeclRefExpr(DeclRefExpr *ref) {
10442       if (ref->getDecl() == Variable && !Capturer)
10443         Capturer = ref;
10444     }
10445 
10446     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10447       if (Capturer) return;
10448       Visit(ref->getBase());
10449       if (Capturer && ref->isFreeIvar())
10450         Capturer = ref;
10451     }
10452 
10453     void VisitBlockExpr(BlockExpr *block) {
10454       // Look inside nested blocks
10455       if (block->getBlockDecl()->capturesVariable(Variable))
10456         Visit(block->getBlockDecl()->getBody());
10457     }
10458 
10459     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10460       if (Capturer) return;
10461       if (OVE->getSourceExpr())
10462         Visit(OVE->getSourceExpr());
10463     }
10464     void VisitBinaryOperator(BinaryOperator *BinOp) {
10465       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10466         return;
10467       Expr *LHS = BinOp->getLHS();
10468       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10469         if (DRE->getDecl() != Variable)
10470           return;
10471         if (Expr *RHS = BinOp->getRHS()) {
10472           RHS = RHS->IgnoreParenCasts();
10473           llvm::APSInt Value;
10474           VarWillBeReased =
10475             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10476         }
10477       }
10478     }
10479   };
10480 } // end anonymous namespace
10481 
10482 /// Check whether the given argument is a block which captures a
10483 /// variable.
10484 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10485   assert(owner.Variable && owner.Loc.isValid());
10486 
10487   e = e->IgnoreParenCasts();
10488 
10489   // Look through [^{...} copy] and Block_copy(^{...}).
10490   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10491     Selector Cmd = ME->getSelector();
10492     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10493       e = ME->getInstanceReceiver();
10494       if (!e)
10495         return nullptr;
10496       e = e->IgnoreParenCasts();
10497     }
10498   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10499     if (CE->getNumArgs() == 1) {
10500       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10501       if (Fn) {
10502         const IdentifierInfo *FnI = Fn->getIdentifier();
10503         if (FnI && FnI->isStr("_Block_copy")) {
10504           e = CE->getArg(0)->IgnoreParenCasts();
10505         }
10506       }
10507     }
10508   }
10509 
10510   BlockExpr *block = dyn_cast<BlockExpr>(e);
10511   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10512     return nullptr;
10513 
10514   FindCaptureVisitor visitor(S.Context, owner.Variable);
10515   visitor.Visit(block->getBlockDecl()->getBody());
10516   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10517 }
10518 
10519 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10520                                 RetainCycleOwner &owner) {
10521   assert(capturer);
10522   assert(owner.Variable && owner.Loc.isValid());
10523 
10524   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10525     << owner.Variable << capturer->getSourceRange();
10526   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10527     << owner.Indirect << owner.Range;
10528 }
10529 
10530 /// Check for a keyword selector that starts with the word 'add' or
10531 /// 'set'.
10532 static bool isSetterLikeSelector(Selector sel) {
10533   if (sel.isUnarySelector()) return false;
10534 
10535   StringRef str = sel.getNameForSlot(0);
10536   while (!str.empty() && str.front() == '_') str = str.substr(1);
10537   if (str.startswith("set"))
10538     str = str.substr(3);
10539   else if (str.startswith("add")) {
10540     // Specially whitelist 'addOperationWithBlock:'.
10541     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10542       return false;
10543     str = str.substr(3);
10544   }
10545   else
10546     return false;
10547 
10548   if (str.empty()) return true;
10549   return !isLowercase(str.front());
10550 }
10551 
10552 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10553                                                     ObjCMessageExpr *Message) {
10554   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10555                                                 Message->getReceiverInterface(),
10556                                                 NSAPI::ClassId_NSMutableArray);
10557   if (!IsMutableArray) {
10558     return None;
10559   }
10560 
10561   Selector Sel = Message->getSelector();
10562 
10563   Optional<NSAPI::NSArrayMethodKind> MKOpt =
10564     S.NSAPIObj->getNSArrayMethodKind(Sel);
10565   if (!MKOpt) {
10566     return None;
10567   }
10568 
10569   NSAPI::NSArrayMethodKind MK = *MKOpt;
10570 
10571   switch (MK) {
10572     case NSAPI::NSMutableArr_addObject:
10573     case NSAPI::NSMutableArr_insertObjectAtIndex:
10574     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10575       return 0;
10576     case NSAPI::NSMutableArr_replaceObjectAtIndex:
10577       return 1;
10578 
10579     default:
10580       return None;
10581   }
10582 
10583   return None;
10584 }
10585 
10586 static
10587 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10588                                                   ObjCMessageExpr *Message) {
10589   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10590                                             Message->getReceiverInterface(),
10591                                             NSAPI::ClassId_NSMutableDictionary);
10592   if (!IsMutableDictionary) {
10593     return None;
10594   }
10595 
10596   Selector Sel = Message->getSelector();
10597 
10598   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10599     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10600   if (!MKOpt) {
10601     return None;
10602   }
10603 
10604   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10605 
10606   switch (MK) {
10607     case NSAPI::NSMutableDict_setObjectForKey:
10608     case NSAPI::NSMutableDict_setValueForKey:
10609     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10610       return 0;
10611 
10612     default:
10613       return None;
10614   }
10615 
10616   return None;
10617 }
10618 
10619 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10620   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10621                                                 Message->getReceiverInterface(),
10622                                                 NSAPI::ClassId_NSMutableSet);
10623 
10624   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10625                                             Message->getReceiverInterface(),
10626                                             NSAPI::ClassId_NSMutableOrderedSet);
10627   if (!IsMutableSet && !IsMutableOrderedSet) {
10628     return None;
10629   }
10630 
10631   Selector Sel = Message->getSelector();
10632 
10633   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10634   if (!MKOpt) {
10635     return None;
10636   }
10637 
10638   NSAPI::NSSetMethodKind MK = *MKOpt;
10639 
10640   switch (MK) {
10641     case NSAPI::NSMutableSet_addObject:
10642     case NSAPI::NSOrderedSet_setObjectAtIndex:
10643     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10644     case NSAPI::NSOrderedSet_insertObjectAtIndex:
10645       return 0;
10646     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10647       return 1;
10648   }
10649 
10650   return None;
10651 }
10652 
10653 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10654   if (!Message->isInstanceMessage()) {
10655     return;
10656   }
10657 
10658   Optional<int> ArgOpt;
10659 
10660   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10661       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10662       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10663     return;
10664   }
10665 
10666   int ArgIndex = *ArgOpt;
10667 
10668   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10669   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10670     Arg = OE->getSourceExpr()->IgnoreImpCasts();
10671   }
10672 
10673   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10674     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10675       if (ArgRE->isObjCSelfExpr()) {
10676         Diag(Message->getSourceRange().getBegin(),
10677              diag::warn_objc_circular_container)
10678           << ArgRE->getDecl()->getName() << StringRef("super");
10679       }
10680     }
10681   } else {
10682     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10683 
10684     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10685       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10686     }
10687 
10688     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10689       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10690         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10691           ValueDecl *Decl = ReceiverRE->getDecl();
10692           Diag(Message->getSourceRange().getBegin(),
10693                diag::warn_objc_circular_container)
10694             << Decl->getName() << Decl->getName();
10695           if (!ArgRE->isObjCSelfExpr()) {
10696             Diag(Decl->getLocation(),
10697                  diag::note_objc_circular_container_declared_here)
10698               << Decl->getName();
10699           }
10700         }
10701       }
10702     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10703       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10704         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10705           ObjCIvarDecl *Decl = IvarRE->getDecl();
10706           Diag(Message->getSourceRange().getBegin(),
10707                diag::warn_objc_circular_container)
10708             << Decl->getName() << Decl->getName();
10709           Diag(Decl->getLocation(),
10710                diag::note_objc_circular_container_declared_here)
10711             << Decl->getName();
10712         }
10713       }
10714     }
10715   }
10716 }
10717 
10718 /// Check a message send to see if it's likely to cause a retain cycle.
10719 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10720   // Only check instance methods whose selector looks like a setter.
10721   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10722     return;
10723 
10724   // Try to find a variable that the receiver is strongly owned by.
10725   RetainCycleOwner owner;
10726   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
10727     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
10728       return;
10729   } else {
10730     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10731     owner.Variable = getCurMethodDecl()->getSelfDecl();
10732     owner.Loc = msg->getSuperLoc();
10733     owner.Range = msg->getSuperLoc();
10734   }
10735 
10736   // Check whether the receiver is captured by any of the arguments.
10737   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10738     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10739       return diagnoseRetainCycle(*this, capturer, owner);
10740 }
10741 
10742 /// Check a property assign to see if it's likely to cause a retain cycle.
10743 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10744   RetainCycleOwner owner;
10745   if (!findRetainCycleOwner(*this, receiver, owner))
10746     return;
10747 
10748   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10749     diagnoseRetainCycle(*this, capturer, owner);
10750 }
10751 
10752 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10753   RetainCycleOwner Owner;
10754   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
10755     return;
10756 
10757   // Because we don't have an expression for the variable, we have to set the
10758   // location explicitly here.
10759   Owner.Loc = Var->getLocation();
10760   Owner.Range = Var->getSourceRange();
10761 
10762   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10763     diagnoseRetainCycle(*this, Capturer, Owner);
10764 }
10765 
10766 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10767                                      Expr *RHS, bool isProperty) {
10768   // Check if RHS is an Objective-C object literal, which also can get
10769   // immediately zapped in a weak reference.  Note that we explicitly
10770   // allow ObjCStringLiterals, since those are designed to never really die.
10771   RHS = RHS->IgnoreParenImpCasts();
10772 
10773   // This enum needs to match with the 'select' in
10774   // warn_objc_arc_literal_assign (off-by-1).
10775   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10776   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10777     return false;
10778 
10779   S.Diag(Loc, diag::warn_arc_literal_assign)
10780     << (unsigned) Kind
10781     << (isProperty ? 0 : 1)
10782     << RHS->getSourceRange();
10783 
10784   return true;
10785 }
10786 
10787 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10788                                     Qualifiers::ObjCLifetime LT,
10789                                     Expr *RHS, bool isProperty) {
10790   // Strip off any implicit cast added to get to the one ARC-specific.
10791   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10792     if (cast->getCastKind() == CK_ARCConsumeObject) {
10793       S.Diag(Loc, diag::warn_arc_retained_assign)
10794         << (LT == Qualifiers::OCL_ExplicitNone)
10795         << (isProperty ? 0 : 1)
10796         << RHS->getSourceRange();
10797       return true;
10798     }
10799     RHS = cast->getSubExpr();
10800   }
10801 
10802   if (LT == Qualifiers::OCL_Weak &&
10803       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10804     return true;
10805 
10806   return false;
10807 }
10808 
10809 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10810                               QualType LHS, Expr *RHS) {
10811   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10812 
10813   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10814     return false;
10815 
10816   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10817     return true;
10818 
10819   return false;
10820 }
10821 
10822 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10823                               Expr *LHS, Expr *RHS) {
10824   QualType LHSType;
10825   // PropertyRef on LHS type need be directly obtained from
10826   // its declaration as it has a PseudoType.
10827   ObjCPropertyRefExpr *PRE
10828     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10829   if (PRE && !PRE->isImplicitProperty()) {
10830     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10831     if (PD)
10832       LHSType = PD->getType();
10833   }
10834 
10835   if (LHSType.isNull())
10836     LHSType = LHS->getType();
10837 
10838   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10839 
10840   if (LT == Qualifiers::OCL_Weak) {
10841     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
10842       getCurFunction()->markSafeWeakUse(LHS);
10843   }
10844 
10845   if (checkUnsafeAssigns(Loc, LHSType, RHS))
10846     return;
10847 
10848   // FIXME. Check for other life times.
10849   if (LT != Qualifiers::OCL_None)
10850     return;
10851 
10852   if (PRE) {
10853     if (PRE->isImplicitProperty())
10854       return;
10855     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10856     if (!PD)
10857       return;
10858 
10859     unsigned Attributes = PD->getPropertyAttributes();
10860     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
10861       // when 'assign' attribute was not explicitly specified
10862       // by user, ignore it and rely on property type itself
10863       // for lifetime info.
10864       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10865       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10866           LHSType->isObjCRetainableType())
10867         return;
10868 
10869       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10870         if (cast->getCastKind() == CK_ARCConsumeObject) {
10871           Diag(Loc, diag::warn_arc_retained_property_assign)
10872           << RHS->getSourceRange();
10873           return;
10874         }
10875         RHS = cast->getSubExpr();
10876       }
10877     }
10878     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
10879       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10880         return;
10881     }
10882   }
10883 }
10884 
10885 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10886 
10887 namespace {
10888 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10889                                  SourceLocation StmtLoc,
10890                                  const NullStmt *Body) {
10891   // Do not warn if the body is a macro that expands to nothing, e.g:
10892   //
10893   // #define CALL(x)
10894   // if (condition)
10895   //   CALL(0);
10896   //
10897   if (Body->hasLeadingEmptyMacro())
10898     return false;
10899 
10900   // Get line numbers of statement and body.
10901   bool StmtLineInvalid;
10902   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
10903                                                       &StmtLineInvalid);
10904   if (StmtLineInvalid)
10905     return false;
10906 
10907   bool BodyLineInvalid;
10908   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10909                                                       &BodyLineInvalid);
10910   if (BodyLineInvalid)
10911     return false;
10912 
10913   // Warn if null statement and body are on the same line.
10914   if (StmtLine != BodyLine)
10915     return false;
10916 
10917   return true;
10918 }
10919 } // end anonymous namespace
10920 
10921 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10922                                  const Stmt *Body,
10923                                  unsigned DiagID) {
10924   // Since this is a syntactic check, don't emit diagnostic for template
10925   // instantiations, this just adds noise.
10926   if (CurrentInstantiationScope)
10927     return;
10928 
10929   // The body should be a null statement.
10930   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10931   if (!NBody)
10932     return;
10933 
10934   // Do the usual checks.
10935   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10936     return;
10937 
10938   Diag(NBody->getSemiLoc(), DiagID);
10939   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10940 }
10941 
10942 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10943                                  const Stmt *PossibleBody) {
10944   assert(!CurrentInstantiationScope); // Ensured by caller
10945 
10946   SourceLocation StmtLoc;
10947   const Stmt *Body;
10948   unsigned DiagID;
10949   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10950     StmtLoc = FS->getRParenLoc();
10951     Body = FS->getBody();
10952     DiagID = diag::warn_empty_for_body;
10953   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10954     StmtLoc = WS->getCond()->getSourceRange().getEnd();
10955     Body = WS->getBody();
10956     DiagID = diag::warn_empty_while_body;
10957   } else
10958     return; // Neither `for' nor `while'.
10959 
10960   // The body should be a null statement.
10961   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10962   if (!NBody)
10963     return;
10964 
10965   // Skip expensive checks if diagnostic is disabled.
10966   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
10967     return;
10968 
10969   // Do the usual checks.
10970   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10971     return;
10972 
10973   // `for(...);' and `while(...);' are popular idioms, so in order to keep
10974   // noise level low, emit diagnostics only if for/while is followed by a
10975   // CompoundStmt, e.g.:
10976   //    for (int i = 0; i < n; i++);
10977   //    {
10978   //      a(i);
10979   //    }
10980   // or if for/while is followed by a statement with more indentation
10981   // than for/while itself:
10982   //    for (int i = 0; i < n; i++);
10983   //      a(i);
10984   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10985   if (!ProbableTypo) {
10986     bool BodyColInvalid;
10987     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10988                              PossibleBody->getLocStart(),
10989                              &BodyColInvalid);
10990     if (BodyColInvalid)
10991       return;
10992 
10993     bool StmtColInvalid;
10994     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10995                              S->getLocStart(),
10996                              &StmtColInvalid);
10997     if (StmtColInvalid)
10998       return;
10999 
11000     if (BodyCol > StmtCol)
11001       ProbableTypo = true;
11002   }
11003 
11004   if (ProbableTypo) {
11005     Diag(NBody->getSemiLoc(), DiagID);
11006     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11007   }
11008 }
11009 
11010 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11011 
11012 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11013 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11014                              SourceLocation OpLoc) {
11015   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11016     return;
11017 
11018   if (!ActiveTemplateInstantiations.empty())
11019     return;
11020 
11021   // Strip parens and casts away.
11022   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11023   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11024 
11025   // Check for a call expression
11026   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11027   if (!CE || CE->getNumArgs() != 1)
11028     return;
11029 
11030   // Check for a call to std::move
11031   const FunctionDecl *FD = CE->getDirectCallee();
11032   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11033       !FD->getIdentifier()->isStr("move"))
11034     return;
11035 
11036   // Get argument from std::move
11037   RHSExpr = CE->getArg(0);
11038 
11039   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11040   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11041 
11042   // Two DeclRefExpr's, check that the decls are the same.
11043   if (LHSDeclRef && RHSDeclRef) {
11044     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11045       return;
11046     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11047         RHSDeclRef->getDecl()->getCanonicalDecl())
11048       return;
11049 
11050     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11051                                         << LHSExpr->getSourceRange()
11052                                         << RHSExpr->getSourceRange();
11053     return;
11054   }
11055 
11056   // Member variables require a different approach to check for self moves.
11057   // MemberExpr's are the same if every nested MemberExpr refers to the same
11058   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11059   // the base Expr's are CXXThisExpr's.
11060   const Expr *LHSBase = LHSExpr;
11061   const Expr *RHSBase = RHSExpr;
11062   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11063   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11064   if (!LHSME || !RHSME)
11065     return;
11066 
11067   while (LHSME && RHSME) {
11068     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11069         RHSME->getMemberDecl()->getCanonicalDecl())
11070       return;
11071 
11072     LHSBase = LHSME->getBase();
11073     RHSBase = RHSME->getBase();
11074     LHSME = dyn_cast<MemberExpr>(LHSBase);
11075     RHSME = dyn_cast<MemberExpr>(RHSBase);
11076   }
11077 
11078   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11079   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11080   if (LHSDeclRef && RHSDeclRef) {
11081     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11082       return;
11083     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11084         RHSDeclRef->getDecl()->getCanonicalDecl())
11085       return;
11086 
11087     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11088                                         << LHSExpr->getSourceRange()
11089                                         << RHSExpr->getSourceRange();
11090     return;
11091   }
11092 
11093   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11094     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11095                                         << LHSExpr->getSourceRange()
11096                                         << RHSExpr->getSourceRange();
11097 }
11098 
11099 //===--- Layout compatibility ----------------------------------------------//
11100 
11101 namespace {
11102 
11103 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11104 
11105 /// \brief Check if two enumeration types are layout-compatible.
11106 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11107   // C++11 [dcl.enum] p8:
11108   // Two enumeration types are layout-compatible if they have the same
11109   // underlying type.
11110   return ED1->isComplete() && ED2->isComplete() &&
11111          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11112 }
11113 
11114 /// \brief Check if two fields are layout-compatible.
11115 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11116   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11117     return false;
11118 
11119   if (Field1->isBitField() != Field2->isBitField())
11120     return false;
11121 
11122   if (Field1->isBitField()) {
11123     // Make sure that the bit-fields are the same length.
11124     unsigned Bits1 = Field1->getBitWidthValue(C);
11125     unsigned Bits2 = Field2->getBitWidthValue(C);
11126 
11127     if (Bits1 != Bits2)
11128       return false;
11129   }
11130 
11131   return true;
11132 }
11133 
11134 /// \brief Check if two standard-layout structs are layout-compatible.
11135 /// (C++11 [class.mem] p17)
11136 bool isLayoutCompatibleStruct(ASTContext &C,
11137                               RecordDecl *RD1,
11138                               RecordDecl *RD2) {
11139   // If both records are C++ classes, check that base classes match.
11140   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11141     // If one of records is a CXXRecordDecl we are in C++ mode,
11142     // thus the other one is a CXXRecordDecl, too.
11143     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11144     // Check number of base classes.
11145     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11146       return false;
11147 
11148     // Check the base classes.
11149     for (CXXRecordDecl::base_class_const_iterator
11150                Base1 = D1CXX->bases_begin(),
11151            BaseEnd1 = D1CXX->bases_end(),
11152               Base2 = D2CXX->bases_begin();
11153          Base1 != BaseEnd1;
11154          ++Base1, ++Base2) {
11155       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11156         return false;
11157     }
11158   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11159     // If only RD2 is a C++ class, it should have zero base classes.
11160     if (D2CXX->getNumBases() > 0)
11161       return false;
11162   }
11163 
11164   // Check the fields.
11165   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11166                              Field2End = RD2->field_end(),
11167                              Field1 = RD1->field_begin(),
11168                              Field1End = RD1->field_end();
11169   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11170     if (!isLayoutCompatible(C, *Field1, *Field2))
11171       return false;
11172   }
11173   if (Field1 != Field1End || Field2 != Field2End)
11174     return false;
11175 
11176   return true;
11177 }
11178 
11179 /// \brief Check if two standard-layout unions are layout-compatible.
11180 /// (C++11 [class.mem] p18)
11181 bool isLayoutCompatibleUnion(ASTContext &C,
11182                              RecordDecl *RD1,
11183                              RecordDecl *RD2) {
11184   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11185   for (auto *Field2 : RD2->fields())
11186     UnmatchedFields.insert(Field2);
11187 
11188   for (auto *Field1 : RD1->fields()) {
11189     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11190         I = UnmatchedFields.begin(),
11191         E = UnmatchedFields.end();
11192 
11193     for ( ; I != E; ++I) {
11194       if (isLayoutCompatible(C, Field1, *I)) {
11195         bool Result = UnmatchedFields.erase(*I);
11196         (void) Result;
11197         assert(Result);
11198         break;
11199       }
11200     }
11201     if (I == E)
11202       return false;
11203   }
11204 
11205   return UnmatchedFields.empty();
11206 }
11207 
11208 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11209   if (RD1->isUnion() != RD2->isUnion())
11210     return false;
11211 
11212   if (RD1->isUnion())
11213     return isLayoutCompatibleUnion(C, RD1, RD2);
11214   else
11215     return isLayoutCompatibleStruct(C, RD1, RD2);
11216 }
11217 
11218 /// \brief Check if two types are layout-compatible in C++11 sense.
11219 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11220   if (T1.isNull() || T2.isNull())
11221     return false;
11222 
11223   // C++11 [basic.types] p11:
11224   // If two types T1 and T2 are the same type, then T1 and T2 are
11225   // layout-compatible types.
11226   if (C.hasSameType(T1, T2))
11227     return true;
11228 
11229   T1 = T1.getCanonicalType().getUnqualifiedType();
11230   T2 = T2.getCanonicalType().getUnqualifiedType();
11231 
11232   const Type::TypeClass TC1 = T1->getTypeClass();
11233   const Type::TypeClass TC2 = T2->getTypeClass();
11234 
11235   if (TC1 != TC2)
11236     return false;
11237 
11238   if (TC1 == Type::Enum) {
11239     return isLayoutCompatible(C,
11240                               cast<EnumType>(T1)->getDecl(),
11241                               cast<EnumType>(T2)->getDecl());
11242   } else if (TC1 == Type::Record) {
11243     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11244       return false;
11245 
11246     return isLayoutCompatible(C,
11247                               cast<RecordType>(T1)->getDecl(),
11248                               cast<RecordType>(T2)->getDecl());
11249   }
11250 
11251   return false;
11252 }
11253 } // end anonymous namespace
11254 
11255 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11256 
11257 namespace {
11258 /// \brief Given a type tag expression find the type tag itself.
11259 ///
11260 /// \param TypeExpr Type tag expression, as it appears in user's code.
11261 ///
11262 /// \param VD Declaration of an identifier that appears in a type tag.
11263 ///
11264 /// \param MagicValue Type tag magic value.
11265 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11266                      const ValueDecl **VD, uint64_t *MagicValue) {
11267   while(true) {
11268     if (!TypeExpr)
11269       return false;
11270 
11271     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11272 
11273     switch (TypeExpr->getStmtClass()) {
11274     case Stmt::UnaryOperatorClass: {
11275       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11276       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11277         TypeExpr = UO->getSubExpr();
11278         continue;
11279       }
11280       return false;
11281     }
11282 
11283     case Stmt::DeclRefExprClass: {
11284       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11285       *VD = DRE->getDecl();
11286       return true;
11287     }
11288 
11289     case Stmt::IntegerLiteralClass: {
11290       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11291       llvm::APInt MagicValueAPInt = IL->getValue();
11292       if (MagicValueAPInt.getActiveBits() <= 64) {
11293         *MagicValue = MagicValueAPInt.getZExtValue();
11294         return true;
11295       } else
11296         return false;
11297     }
11298 
11299     case Stmt::BinaryConditionalOperatorClass:
11300     case Stmt::ConditionalOperatorClass: {
11301       const AbstractConditionalOperator *ACO =
11302           cast<AbstractConditionalOperator>(TypeExpr);
11303       bool Result;
11304       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11305         if (Result)
11306           TypeExpr = ACO->getTrueExpr();
11307         else
11308           TypeExpr = ACO->getFalseExpr();
11309         continue;
11310       }
11311       return false;
11312     }
11313 
11314     case Stmt::BinaryOperatorClass: {
11315       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11316       if (BO->getOpcode() == BO_Comma) {
11317         TypeExpr = BO->getRHS();
11318         continue;
11319       }
11320       return false;
11321     }
11322 
11323     default:
11324       return false;
11325     }
11326   }
11327 }
11328 
11329 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11330 ///
11331 /// \param TypeExpr Expression that specifies a type tag.
11332 ///
11333 /// \param MagicValues Registered magic values.
11334 ///
11335 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11336 ///        kind.
11337 ///
11338 /// \param TypeInfo Information about the corresponding C type.
11339 ///
11340 /// \returns true if the corresponding C type was found.
11341 bool GetMatchingCType(
11342         const IdentifierInfo *ArgumentKind,
11343         const Expr *TypeExpr, const ASTContext &Ctx,
11344         const llvm::DenseMap<Sema::TypeTagMagicValue,
11345                              Sema::TypeTagData> *MagicValues,
11346         bool &FoundWrongKind,
11347         Sema::TypeTagData &TypeInfo) {
11348   FoundWrongKind = false;
11349 
11350   // Variable declaration that has type_tag_for_datatype attribute.
11351   const ValueDecl *VD = nullptr;
11352 
11353   uint64_t MagicValue;
11354 
11355   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11356     return false;
11357 
11358   if (VD) {
11359     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11360       if (I->getArgumentKind() != ArgumentKind) {
11361         FoundWrongKind = true;
11362         return false;
11363       }
11364       TypeInfo.Type = I->getMatchingCType();
11365       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11366       TypeInfo.MustBeNull = I->getMustBeNull();
11367       return true;
11368     }
11369     return false;
11370   }
11371 
11372   if (!MagicValues)
11373     return false;
11374 
11375   llvm::DenseMap<Sema::TypeTagMagicValue,
11376                  Sema::TypeTagData>::const_iterator I =
11377       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11378   if (I == MagicValues->end())
11379     return false;
11380 
11381   TypeInfo = I->second;
11382   return true;
11383 }
11384 } // end anonymous namespace
11385 
11386 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11387                                       uint64_t MagicValue, QualType Type,
11388                                       bool LayoutCompatible,
11389                                       bool MustBeNull) {
11390   if (!TypeTagForDatatypeMagicValues)
11391     TypeTagForDatatypeMagicValues.reset(
11392         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11393 
11394   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11395   (*TypeTagForDatatypeMagicValues)[Magic] =
11396       TypeTagData(Type, LayoutCompatible, MustBeNull);
11397 }
11398 
11399 namespace {
11400 bool IsSameCharType(QualType T1, QualType T2) {
11401   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11402   if (!BT1)
11403     return false;
11404 
11405   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11406   if (!BT2)
11407     return false;
11408 
11409   BuiltinType::Kind T1Kind = BT1->getKind();
11410   BuiltinType::Kind T2Kind = BT2->getKind();
11411 
11412   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11413          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11414          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11415          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11416 }
11417 } // end anonymous namespace
11418 
11419 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11420                                     const Expr * const *ExprArgs) {
11421   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11422   bool IsPointerAttr = Attr->getIsPointer();
11423 
11424   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11425   bool FoundWrongKind;
11426   TypeTagData TypeInfo;
11427   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11428                         TypeTagForDatatypeMagicValues.get(),
11429                         FoundWrongKind, TypeInfo)) {
11430     if (FoundWrongKind)
11431       Diag(TypeTagExpr->getExprLoc(),
11432            diag::warn_type_tag_for_datatype_wrong_kind)
11433         << TypeTagExpr->getSourceRange();
11434     return;
11435   }
11436 
11437   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11438   if (IsPointerAttr) {
11439     // Skip implicit cast of pointer to `void *' (as a function argument).
11440     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11441       if (ICE->getType()->isVoidPointerType() &&
11442           ICE->getCastKind() == CK_BitCast)
11443         ArgumentExpr = ICE->getSubExpr();
11444   }
11445   QualType ArgumentType = ArgumentExpr->getType();
11446 
11447   // Passing a `void*' pointer shouldn't trigger a warning.
11448   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11449     return;
11450 
11451   if (TypeInfo.MustBeNull) {
11452     // Type tag with matching void type requires a null pointer.
11453     if (!ArgumentExpr->isNullPointerConstant(Context,
11454                                              Expr::NPC_ValueDependentIsNotNull)) {
11455       Diag(ArgumentExpr->getExprLoc(),
11456            diag::warn_type_safety_null_pointer_required)
11457           << ArgumentKind->getName()
11458           << ArgumentExpr->getSourceRange()
11459           << TypeTagExpr->getSourceRange();
11460     }
11461     return;
11462   }
11463 
11464   QualType RequiredType = TypeInfo.Type;
11465   if (IsPointerAttr)
11466     RequiredType = Context.getPointerType(RequiredType);
11467 
11468   bool mismatch = false;
11469   if (!TypeInfo.LayoutCompatible) {
11470     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11471 
11472     // C++11 [basic.fundamental] p1:
11473     // Plain char, signed char, and unsigned char are three distinct types.
11474     //
11475     // But we treat plain `char' as equivalent to `signed char' or `unsigned
11476     // char' depending on the current char signedness mode.
11477     if (mismatch)
11478       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11479                                            RequiredType->getPointeeType())) ||
11480           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11481         mismatch = false;
11482   } else
11483     if (IsPointerAttr)
11484       mismatch = !isLayoutCompatible(Context,
11485                                      ArgumentType->getPointeeType(),
11486                                      RequiredType->getPointeeType());
11487     else
11488       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11489 
11490   if (mismatch)
11491     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11492         << ArgumentType << ArgumentKind
11493         << TypeInfo.LayoutCompatible << RequiredType
11494         << ArgumentExpr->getSourceRange()
11495         << TypeTagExpr->getSourceRange();
11496 }
11497 
11498 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11499                                          CharUnits Alignment) {
11500   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11501 }
11502 
11503 void Sema::DiagnoseMisalignedMembers() {
11504   for (MisalignedMember &m : MisalignedMembers) {
11505     const NamedDecl *ND = m.RD;
11506     if (ND->getName().empty()) {
11507       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11508         ND = TD;
11509     }
11510     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11511         << m.MD << ND << m.E->getSourceRange();
11512   }
11513   MisalignedMembers.clear();
11514 }
11515 
11516 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11517   if (!T->isPointerType())
11518     return;
11519   if (isa<UnaryOperator>(E) &&
11520       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11521     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11522     if (isa<MemberExpr>(Op)) {
11523       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11524                           MisalignedMember(Op));
11525       if (MA != MisalignedMembers.end() &&
11526           Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11527         MisalignedMembers.erase(MA);
11528     }
11529   }
11530 }
11531 
11532 void Sema::RefersToMemberWithReducedAlignment(
11533     Expr *E,
11534     std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11535   const auto *ME = dyn_cast<MemberExpr>(E);
11536   while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11537     QualType BaseType = ME->getBase()->getType();
11538     if (ME->isArrow())
11539       BaseType = BaseType->getPointeeType();
11540     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11541 
11542     ValueDecl *MD = ME->getMemberDecl();
11543     bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11544     if (ByteAligned) // Attribute packed does not have any effect.
11545       break;
11546 
11547     if (!ByteAligned &&
11548         (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11549       CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11550                                      Context.getTypeAlignInChars(BaseType));
11551       // Notify that this expression designates a member with reduced alignment
11552       Action(E, RD, MD, Alignment);
11553       break;
11554     }
11555     ME = dyn_cast<MemberExpr>(ME->getBase());
11556   }
11557 }
11558 
11559 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11560   using namespace std::placeholders;
11561   RefersToMemberWithReducedAlignment(
11562       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11563                      _2, _3, _4));
11564 }
11565 
11566