1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCXXABI.h"
14 #include "CGCleanup.h"
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CGOpenMPRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/Basic/CodeGenOptions.h"
29 #include "clang/Basic/FixedPoint.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/IR/CFG.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GetElementPtrTypeIterator.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/IntrinsicsPowerPC.h"
40 #include "llvm/IR/Module.h"
41 #include <cstdarg>
42 
43 using namespace clang;
44 using namespace CodeGen;
45 using llvm::Value;
46 
47 //===----------------------------------------------------------------------===//
48 //                         Scalar Expression Emitter
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52 
53 /// Determine whether the given binary operation may overflow.
54 /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
55 /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
56 /// the returned overflow check is precise. The returned value is 'true' for
57 /// all other opcodes, to be conservative.
58 bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
59                              BinaryOperator::Opcode Opcode, bool Signed,
60                              llvm::APInt &Result) {
61   // Assume overflow is possible, unless we can prove otherwise.
62   bool Overflow = true;
63   const auto &LHSAP = LHS->getValue();
64   const auto &RHSAP = RHS->getValue();
65   if (Opcode == BO_Add) {
66     if (Signed)
67       Result = LHSAP.sadd_ov(RHSAP, Overflow);
68     else
69       Result = LHSAP.uadd_ov(RHSAP, Overflow);
70   } else if (Opcode == BO_Sub) {
71     if (Signed)
72       Result = LHSAP.ssub_ov(RHSAP, Overflow);
73     else
74       Result = LHSAP.usub_ov(RHSAP, Overflow);
75   } else if (Opcode == BO_Mul) {
76     if (Signed)
77       Result = LHSAP.smul_ov(RHSAP, Overflow);
78     else
79       Result = LHSAP.umul_ov(RHSAP, Overflow);
80   } else if (Opcode == BO_Div || Opcode == BO_Rem) {
81     if (Signed && !RHS->isZero())
82       Result = LHSAP.sdiv_ov(RHSAP, Overflow);
83     else
84       return false;
85   }
86   return Overflow;
87 }
88 
89 struct BinOpInfo {
90   Value *LHS;
91   Value *RHS;
92   QualType Ty;  // Computation Type.
93   BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
94   FPOptions FPFeatures;
95   const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
96 
97   /// Check if the binop can result in integer overflow.
98   bool mayHaveIntegerOverflow() const {
99     // Without constant input, we can't rule out overflow.
100     auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
101     auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
102     if (!LHSCI || !RHSCI)
103       return true;
104 
105     llvm::APInt Result;
106     return ::mayHaveIntegerOverflow(
107         LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
108   }
109 
110   /// Check if the binop computes a division or a remainder.
111   bool isDivremOp() const {
112     return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
113            Opcode == BO_RemAssign;
114   }
115 
116   /// Check if the binop can result in an integer division by zero.
117   bool mayHaveIntegerDivisionByZero() const {
118     if (isDivremOp())
119       if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
120         return CI->isZero();
121     return true;
122   }
123 
124   /// Check if the binop can result in a float division by zero.
125   bool mayHaveFloatDivisionByZero() const {
126     if (isDivremOp())
127       if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
128         return CFP->isZero();
129     return true;
130   }
131 
132   /// Check if at least one operand is a fixed point type. In such cases, this
133   /// operation did not follow usual arithmetic conversion and both operands
134   /// might not be of the same type.
135   bool isFixedPointOp() const {
136     // We cannot simply check the result type since comparison operations return
137     // an int.
138     if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
139       QualType LHSType = BinOp->getLHS()->getType();
140       QualType RHSType = BinOp->getRHS()->getType();
141       return LHSType->isFixedPointType() || RHSType->isFixedPointType();
142     }
143     if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
144       return UnOp->getSubExpr()->getType()->isFixedPointType();
145     return false;
146   }
147 };
148 
149 static bool MustVisitNullValue(const Expr *E) {
150   // If a null pointer expression's type is the C++0x nullptr_t, then
151   // it's not necessarily a simple constant and it must be evaluated
152   // for its potential side effects.
153   return E->getType()->isNullPtrType();
154 }
155 
156 /// If \p E is a widened promoted integer, get its base (unpromoted) type.
157 static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
158                                                         const Expr *E) {
159   const Expr *Base = E->IgnoreImpCasts();
160   if (E == Base)
161     return llvm::None;
162 
163   QualType BaseTy = Base->getType();
164   if (!BaseTy->isPromotableIntegerType() ||
165       Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
166     return llvm::None;
167 
168   return BaseTy;
169 }
170 
171 /// Check if \p E is a widened promoted integer.
172 static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
173   return getUnwidenedIntegerType(Ctx, E).hasValue();
174 }
175 
176 /// Check if we can skip the overflow check for \p Op.
177 static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
178   assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
179          "Expected a unary or binary operator");
180 
181   // If the binop has constant inputs and we can prove there is no overflow,
182   // we can elide the overflow check.
183   if (!Op.mayHaveIntegerOverflow())
184     return true;
185 
186   // If a unary op has a widened operand, the op cannot overflow.
187   if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
188     return !UO->canOverflow();
189 
190   // We usually don't need overflow checks for binops with widened operands.
191   // Multiplication with promoted unsigned operands is a special case.
192   const auto *BO = cast<BinaryOperator>(Op.E);
193   auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
194   if (!OptionalLHSTy)
195     return false;
196 
197   auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
198   if (!OptionalRHSTy)
199     return false;
200 
201   QualType LHSTy = *OptionalLHSTy;
202   QualType RHSTy = *OptionalRHSTy;
203 
204   // This is the simple case: binops without unsigned multiplication, and with
205   // widened operands. No overflow check is needed here.
206   if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
207       !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
208     return true;
209 
210   // For unsigned multiplication the overflow check can be elided if either one
211   // of the unpromoted types are less than half the size of the promoted type.
212   unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
213   return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
214          (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
215 }
216 
217 /// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions.
218 static void updateFastMathFlags(llvm::FastMathFlags &FMF,
219                                 FPOptions FPFeatures) {
220   FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
221 }
222 
223 /// Propagate fast-math flags from \p Op to the instruction in \p V.
224 static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) {
225   if (auto *I = dyn_cast<llvm::Instruction>(V)) {
226     llvm::FastMathFlags FMF = I->getFastMathFlags();
227     updateFastMathFlags(FMF, Op.FPFeatures);
228     I->setFastMathFlags(FMF);
229   }
230   return V;
231 }
232 
233 class ScalarExprEmitter
234   : public StmtVisitor<ScalarExprEmitter, Value*> {
235   CodeGenFunction &CGF;
236   CGBuilderTy &Builder;
237   bool IgnoreResultAssign;
238   llvm::LLVMContext &VMContext;
239 public:
240 
241   ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
242     : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
243       VMContext(cgf.getLLVMContext()) {
244   }
245 
246   //===--------------------------------------------------------------------===//
247   //                               Utilities
248   //===--------------------------------------------------------------------===//
249 
250   bool TestAndClearIgnoreResultAssign() {
251     bool I = IgnoreResultAssign;
252     IgnoreResultAssign = false;
253     return I;
254   }
255 
256   llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
257   LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
258   LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
259     return CGF.EmitCheckedLValue(E, TCK);
260   }
261 
262   void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
263                       const BinOpInfo &Info);
264 
265   Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
266     return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
267   }
268 
269   void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
270     const AlignValueAttr *AVAttr = nullptr;
271     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
272       const ValueDecl *VD = DRE->getDecl();
273 
274       if (VD->getType()->isReferenceType()) {
275         if (const auto *TTy =
276             dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
277           AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
278       } else {
279         // Assumptions for function parameters are emitted at the start of the
280         // function, so there is no need to repeat that here,
281         // unless the alignment-assumption sanitizer is enabled,
282         // then we prefer the assumption over alignment attribute
283         // on IR function param.
284         if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
285           return;
286 
287         AVAttr = VD->getAttr<AlignValueAttr>();
288       }
289     }
290 
291     if (!AVAttr)
292       if (const auto *TTy =
293           dyn_cast<TypedefType>(E->getType()))
294         AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
295 
296     if (!AVAttr)
297       return;
298 
299     Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
300     llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
301     CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
302   }
303 
304   /// EmitLoadOfLValue - Given an expression with complex type that represents a
305   /// value l-value, this method emits the address of the l-value, then loads
306   /// and returns the result.
307   Value *EmitLoadOfLValue(const Expr *E) {
308     Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
309                                 E->getExprLoc());
310 
311     EmitLValueAlignmentAssumption(E, V);
312     return V;
313   }
314 
315   /// EmitConversionToBool - Convert the specified expression value to a
316   /// boolean (i1) truth value.  This is equivalent to "Val != 0".
317   Value *EmitConversionToBool(Value *Src, QualType DstTy);
318 
319   /// Emit a check that a conversion from a floating-point type does not
320   /// overflow.
321   void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
322                                 Value *Src, QualType SrcType, QualType DstType,
323                                 llvm::Type *DstTy, SourceLocation Loc);
324 
325   /// Known implicit conversion check kinds.
326   /// Keep in sync with the enum of the same name in ubsan_handlers.h
327   enum ImplicitConversionCheckKind : unsigned char {
328     ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
329     ICCK_UnsignedIntegerTruncation = 1,
330     ICCK_SignedIntegerTruncation = 2,
331     ICCK_IntegerSignChange = 3,
332     ICCK_SignedIntegerTruncationOrSignChange = 4,
333   };
334 
335   /// Emit a check that an [implicit] truncation of an integer  does not
336   /// discard any bits. It is not UB, so we use the value after truncation.
337   void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
338                                   QualType DstType, SourceLocation Loc);
339 
340   /// Emit a check that an [implicit] conversion of an integer does not change
341   /// the sign of the value. It is not UB, so we use the value after conversion.
342   /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
343   void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
344                                   QualType DstType, SourceLocation Loc);
345 
346   /// Emit a conversion from the specified type to the specified destination
347   /// type, both of which are LLVM scalar types.
348   struct ScalarConversionOpts {
349     bool TreatBooleanAsSigned;
350     bool EmitImplicitIntegerTruncationChecks;
351     bool EmitImplicitIntegerSignChangeChecks;
352 
353     ScalarConversionOpts()
354         : TreatBooleanAsSigned(false),
355           EmitImplicitIntegerTruncationChecks(false),
356           EmitImplicitIntegerSignChangeChecks(false) {}
357 
358     ScalarConversionOpts(clang::SanitizerSet SanOpts)
359         : TreatBooleanAsSigned(false),
360           EmitImplicitIntegerTruncationChecks(
361               SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
362           EmitImplicitIntegerSignChangeChecks(
363               SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
364   };
365   Value *
366   EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
367                        SourceLocation Loc,
368                        ScalarConversionOpts Opts = ScalarConversionOpts());
369 
370   /// Convert between either a fixed point and other fixed point or fixed point
371   /// and an integer.
372   Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
373                                   SourceLocation Loc);
374   Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema,
375                                   FixedPointSemantics &DstFixedSema,
376                                   SourceLocation Loc,
377                                   bool DstIsInteger = false);
378 
379   /// Emit a conversion from the specified complex type to the specified
380   /// destination type, where the destination type is an LLVM scalar type.
381   Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
382                                        QualType SrcTy, QualType DstTy,
383                                        SourceLocation Loc);
384 
385   /// EmitNullValue - Emit a value that corresponds to null for the given type.
386   Value *EmitNullValue(QualType Ty);
387 
388   /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
389   Value *EmitFloatToBoolConversion(Value *V) {
390     // Compare against 0.0 for fp scalars.
391     llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
392     return Builder.CreateFCmpUNE(V, Zero, "tobool");
393   }
394 
395   /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
396   Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
397     Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
398 
399     return Builder.CreateICmpNE(V, Zero, "tobool");
400   }
401 
402   Value *EmitIntToBoolConversion(Value *V) {
403     // Because of the type rules of C, we often end up computing a
404     // logical value, then zero extending it to int, then wanting it
405     // as a logical value again.  Optimize this common case.
406     if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
407       if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
408         Value *Result = ZI->getOperand(0);
409         // If there aren't any more uses, zap the instruction to save space.
410         // Note that there can be more uses, for example if this
411         // is the result of an assignment.
412         if (ZI->use_empty())
413           ZI->eraseFromParent();
414         return Result;
415       }
416     }
417 
418     return Builder.CreateIsNotNull(V, "tobool");
419   }
420 
421   //===--------------------------------------------------------------------===//
422   //                            Visitor Methods
423   //===--------------------------------------------------------------------===//
424 
425   Value *Visit(Expr *E) {
426     ApplyDebugLocation DL(CGF, E);
427     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
428   }
429 
430   Value *VisitStmt(Stmt *S) {
431     S->dump(CGF.getContext().getSourceManager());
432     llvm_unreachable("Stmt can't have complex result type!");
433   }
434   Value *VisitExpr(Expr *S);
435 
436   Value *VisitConstantExpr(ConstantExpr *E) {
437     return Visit(E->getSubExpr());
438   }
439   Value *VisitParenExpr(ParenExpr *PE) {
440     return Visit(PE->getSubExpr());
441   }
442   Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
443     return Visit(E->getReplacement());
444   }
445   Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
446     return Visit(GE->getResultExpr());
447   }
448   Value *VisitCoawaitExpr(CoawaitExpr *S) {
449     return CGF.EmitCoawaitExpr(*S).getScalarVal();
450   }
451   Value *VisitCoyieldExpr(CoyieldExpr *S) {
452     return CGF.EmitCoyieldExpr(*S).getScalarVal();
453   }
454   Value *VisitUnaryCoawait(const UnaryOperator *E) {
455     return Visit(E->getSubExpr());
456   }
457 
458   // Leaves.
459   Value *VisitIntegerLiteral(const IntegerLiteral *E) {
460     return Builder.getInt(E->getValue());
461   }
462   Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
463     return Builder.getInt(E->getValue());
464   }
465   Value *VisitFloatingLiteral(const FloatingLiteral *E) {
466     return llvm::ConstantFP::get(VMContext, E->getValue());
467   }
468   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
469     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
470   }
471   Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
472     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
473   }
474   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
475     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
476   }
477   Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
478     return EmitNullValue(E->getType());
479   }
480   Value *VisitGNUNullExpr(const GNUNullExpr *E) {
481     return EmitNullValue(E->getType());
482   }
483   Value *VisitOffsetOfExpr(OffsetOfExpr *E);
484   Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
485   Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
486     llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
487     return Builder.CreateBitCast(V, ConvertType(E->getType()));
488   }
489 
490   Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
491     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
492   }
493 
494   Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
495     return CGF.EmitPseudoObjectRValue(E).getScalarVal();
496   }
497 
498   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
499     if (E->isGLValue())
500       return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
501                               E->getExprLoc());
502 
503     // Otherwise, assume the mapping is the scalar directly.
504     return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
505   }
506 
507   // l-values.
508   Value *VisitDeclRefExpr(DeclRefExpr *E) {
509     if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
510       return CGF.emitScalarConstant(Constant, E);
511     return EmitLoadOfLValue(E);
512   }
513 
514   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
515     return CGF.EmitObjCSelectorExpr(E);
516   }
517   Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
518     return CGF.EmitObjCProtocolExpr(E);
519   }
520   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
521     return EmitLoadOfLValue(E);
522   }
523   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
524     if (E->getMethodDecl() &&
525         E->getMethodDecl()->getReturnType()->isReferenceType())
526       return EmitLoadOfLValue(E);
527     return CGF.EmitObjCMessageExpr(E).getScalarVal();
528   }
529 
530   Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
531     LValue LV = CGF.EmitObjCIsaExpr(E);
532     Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
533     return V;
534   }
535 
536   Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
537     VersionTuple Version = E->getVersion();
538 
539     // If we're checking for a platform older than our minimum deployment
540     // target, we can fold the check away.
541     if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
542       return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
543 
544     Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
545     llvm::Value *Args[] = {
546         llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
547         llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
548         llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
549     };
550 
551     return CGF.EmitBuiltinAvailable(Args);
552   }
553 
554   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
555   Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
556   Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
557   Value *VisitMemberExpr(MemberExpr *E);
558   Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
559   Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
560     // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
561     // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
562     // literals aren't l-values in C++. We do so simply because that's the
563     // cleanest way to handle compound literals in C++.
564     // See the discussion here: https://reviews.llvm.org/D64464
565     return EmitLoadOfLValue(E);
566   }
567 
568   Value *VisitInitListExpr(InitListExpr *E);
569 
570   Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
571     assert(CGF.getArrayInitIndex() &&
572            "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
573     return CGF.getArrayInitIndex();
574   }
575 
576   Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
577     return EmitNullValue(E->getType());
578   }
579   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
580     CGF.CGM.EmitExplicitCastExprType(E, &CGF);
581     return VisitCastExpr(E);
582   }
583   Value *VisitCastExpr(CastExpr *E);
584 
585   Value *VisitCallExpr(const CallExpr *E) {
586     if (E->getCallReturnType(CGF.getContext())->isReferenceType())
587       return EmitLoadOfLValue(E);
588 
589     Value *V = CGF.EmitCallExpr(E).getScalarVal();
590 
591     EmitLValueAlignmentAssumption(E, V);
592     return V;
593   }
594 
595   Value *VisitStmtExpr(const StmtExpr *E);
596 
597   // Unary Operators.
598   Value *VisitUnaryPostDec(const UnaryOperator *E) {
599     LValue LV = EmitLValue(E->getSubExpr());
600     return EmitScalarPrePostIncDec(E, LV, false, false);
601   }
602   Value *VisitUnaryPostInc(const UnaryOperator *E) {
603     LValue LV = EmitLValue(E->getSubExpr());
604     return EmitScalarPrePostIncDec(E, LV, true, false);
605   }
606   Value *VisitUnaryPreDec(const UnaryOperator *E) {
607     LValue LV = EmitLValue(E->getSubExpr());
608     return EmitScalarPrePostIncDec(E, LV, false, true);
609   }
610   Value *VisitUnaryPreInc(const UnaryOperator *E) {
611     LValue LV = EmitLValue(E->getSubExpr());
612     return EmitScalarPrePostIncDec(E, LV, true, true);
613   }
614 
615   llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
616                                                   llvm::Value *InVal,
617                                                   bool IsInc);
618 
619   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
620                                        bool isInc, bool isPre);
621 
622 
623   Value *VisitUnaryAddrOf(const UnaryOperator *E) {
624     if (isa<MemberPointerType>(E->getType())) // never sugared
625       return CGF.CGM.getMemberPointerConstant(E);
626 
627     return EmitLValue(E->getSubExpr()).getPointer(CGF);
628   }
629   Value *VisitUnaryDeref(const UnaryOperator *E) {
630     if (E->getType()->isVoidType())
631       return Visit(E->getSubExpr()); // the actual value should be unused
632     return EmitLoadOfLValue(E);
633   }
634   Value *VisitUnaryPlus(const UnaryOperator *E) {
635     // This differs from gcc, though, most likely due to a bug in gcc.
636     TestAndClearIgnoreResultAssign();
637     return Visit(E->getSubExpr());
638   }
639   Value *VisitUnaryMinus    (const UnaryOperator *E);
640   Value *VisitUnaryNot      (const UnaryOperator *E);
641   Value *VisitUnaryLNot     (const UnaryOperator *E);
642   Value *VisitUnaryReal     (const UnaryOperator *E);
643   Value *VisitUnaryImag     (const UnaryOperator *E);
644   Value *VisitUnaryExtension(const UnaryOperator *E) {
645     return Visit(E->getSubExpr());
646   }
647 
648   // C++
649   Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
650     return EmitLoadOfLValue(E);
651   }
652   Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
653     auto &Ctx = CGF.getContext();
654     APValue Evaluated =
655         SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
656     return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated,
657                                              SLE->getType());
658   }
659 
660   Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
661     CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
662     return Visit(DAE->getExpr());
663   }
664   Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
665     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
666     return Visit(DIE->getExpr());
667   }
668   Value *VisitCXXThisExpr(CXXThisExpr *TE) {
669     return CGF.LoadCXXThis();
670   }
671 
672   Value *VisitExprWithCleanups(ExprWithCleanups *E);
673   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
674     return CGF.EmitCXXNewExpr(E);
675   }
676   Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
677     CGF.EmitCXXDeleteExpr(E);
678     return nullptr;
679   }
680 
681   Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
682     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
683   }
684 
685   Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
686     return Builder.getInt1(E->isSatisfied());
687   }
688 
689   Value *VisitRequiresExpr(const RequiresExpr *E) {
690     return Builder.getInt1(E->isSatisfied());
691   }
692 
693   Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
694     return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
695   }
696 
697   Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
698     return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
699   }
700 
701   Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
702     // C++ [expr.pseudo]p1:
703     //   The result shall only be used as the operand for the function call
704     //   operator (), and the result of such a call has type void. The only
705     //   effect is the evaluation of the postfix-expression before the dot or
706     //   arrow.
707     CGF.EmitScalarExpr(E->getBase());
708     return nullptr;
709   }
710 
711   Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
712     return EmitNullValue(E->getType());
713   }
714 
715   Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
716     CGF.EmitCXXThrowExpr(E);
717     return nullptr;
718   }
719 
720   Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
721     return Builder.getInt1(E->getValue());
722   }
723 
724   // Binary Operators.
725   Value *EmitMul(const BinOpInfo &Ops) {
726     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
727       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
728       case LangOptions::SOB_Defined:
729         return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
730       case LangOptions::SOB_Undefined:
731         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
732           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
733         LLVM_FALLTHROUGH;
734       case LangOptions::SOB_Trapping:
735         if (CanElideOverflowCheck(CGF.getContext(), Ops))
736           return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
737         return EmitOverflowCheckedBinOp(Ops);
738       }
739     }
740 
741     if (Ops.Ty->isUnsignedIntegerType() &&
742         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
743         !CanElideOverflowCheck(CGF.getContext(), Ops))
744       return EmitOverflowCheckedBinOp(Ops);
745 
746     if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
747       Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
748       return propagateFMFlags(V, Ops);
749     }
750     if (Ops.isFixedPointOp())
751       return EmitFixedPointBinOp(Ops);
752     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
753   }
754   /// Create a binary op that checks for overflow.
755   /// Currently only supports +, - and *.
756   Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
757 
758   // Check for undefined division and modulus behaviors.
759   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
760                                                   llvm::Value *Zero,bool isDiv);
761   // Common helper for getting how wide LHS of shift is.
762   static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
763   Value *EmitDiv(const BinOpInfo &Ops);
764   Value *EmitRem(const BinOpInfo &Ops);
765   Value *EmitAdd(const BinOpInfo &Ops);
766   Value *EmitSub(const BinOpInfo &Ops);
767   Value *EmitShl(const BinOpInfo &Ops);
768   Value *EmitShr(const BinOpInfo &Ops);
769   Value *EmitAnd(const BinOpInfo &Ops) {
770     return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
771   }
772   Value *EmitXor(const BinOpInfo &Ops) {
773     return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
774   }
775   Value *EmitOr (const BinOpInfo &Ops) {
776     return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
777   }
778 
779   // Helper functions for fixed point binary operations.
780   Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
781 
782   BinOpInfo EmitBinOps(const BinaryOperator *E);
783   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
784                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
785                                   Value *&Result);
786 
787   Value *EmitCompoundAssign(const CompoundAssignOperator *E,
788                             Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
789 
790   // Binary operators and binary compound assignment operators.
791 #define HANDLEBINOP(OP) \
792   Value *VisitBin ## OP(const BinaryOperator *E) {                         \
793     return Emit ## OP(EmitBinOps(E));                                      \
794   }                                                                        \
795   Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
796     return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
797   }
798   HANDLEBINOP(Mul)
799   HANDLEBINOP(Div)
800   HANDLEBINOP(Rem)
801   HANDLEBINOP(Add)
802   HANDLEBINOP(Sub)
803   HANDLEBINOP(Shl)
804   HANDLEBINOP(Shr)
805   HANDLEBINOP(And)
806   HANDLEBINOP(Xor)
807   HANDLEBINOP(Or)
808 #undef HANDLEBINOP
809 
810   // Comparisons.
811   Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
812                      llvm::CmpInst::Predicate SICmpOpc,
813                      llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
814 #define VISITCOMP(CODE, UI, SI, FP, SIG) \
815     Value *VisitBin##CODE(const BinaryOperator *E) { \
816       return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
817                          llvm::FCmpInst::FP, SIG); }
818   VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
819   VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
820   VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
821   VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
822   VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
823   VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
824 #undef VISITCOMP
825 
826   Value *VisitBinAssign     (const BinaryOperator *E);
827 
828   Value *VisitBinLAnd       (const BinaryOperator *E);
829   Value *VisitBinLOr        (const BinaryOperator *E);
830   Value *VisitBinComma      (const BinaryOperator *E);
831 
832   Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
833   Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
834 
835   Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
836     return Visit(E->getSemanticForm());
837   }
838 
839   // Other Operators.
840   Value *VisitBlockExpr(const BlockExpr *BE);
841   Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
842   Value *VisitChooseExpr(ChooseExpr *CE);
843   Value *VisitVAArgExpr(VAArgExpr *VE);
844   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
845     return CGF.EmitObjCStringLiteral(E);
846   }
847   Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
848     return CGF.EmitObjCBoxedExpr(E);
849   }
850   Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
851     return CGF.EmitObjCArrayLiteral(E);
852   }
853   Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
854     return CGF.EmitObjCDictionaryLiteral(E);
855   }
856   Value *VisitAsTypeExpr(AsTypeExpr *CE);
857   Value *VisitAtomicExpr(AtomicExpr *AE);
858 };
859 }  // end anonymous namespace.
860 
861 //===----------------------------------------------------------------------===//
862 //                                Utilities
863 //===----------------------------------------------------------------------===//
864 
865 /// EmitConversionToBool - Convert the specified expression value to a
866 /// boolean (i1) truth value.  This is equivalent to "Val != 0".
867 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
868   assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
869 
870   if (SrcType->isRealFloatingType())
871     return EmitFloatToBoolConversion(Src);
872 
873   if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
874     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
875 
876   assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
877          "Unknown scalar type to convert");
878 
879   if (isa<llvm::IntegerType>(Src->getType()))
880     return EmitIntToBoolConversion(Src);
881 
882   assert(isa<llvm::PointerType>(Src->getType()));
883   return EmitPointerToBoolConversion(Src, SrcType);
884 }
885 
886 void ScalarExprEmitter::EmitFloatConversionCheck(
887     Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
888     QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
889   assert(SrcType->isFloatingType() && "not a conversion from floating point");
890   if (!isa<llvm::IntegerType>(DstTy))
891     return;
892 
893   CodeGenFunction::SanitizerScope SanScope(&CGF);
894   using llvm::APFloat;
895   using llvm::APSInt;
896 
897   llvm::Value *Check = nullptr;
898   const llvm::fltSemantics &SrcSema =
899     CGF.getContext().getFloatTypeSemantics(OrigSrcType);
900 
901   // Floating-point to integer. This has undefined behavior if the source is
902   // +-Inf, NaN, or doesn't fit into the destination type (after truncation
903   // to an integer).
904   unsigned Width = CGF.getContext().getIntWidth(DstType);
905   bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
906 
907   APSInt Min = APSInt::getMinValue(Width, Unsigned);
908   APFloat MinSrc(SrcSema, APFloat::uninitialized);
909   if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
910       APFloat::opOverflow)
911     // Don't need an overflow check for lower bound. Just check for
912     // -Inf/NaN.
913     MinSrc = APFloat::getInf(SrcSema, true);
914   else
915     // Find the largest value which is too small to represent (before
916     // truncation toward zero).
917     MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
918 
919   APSInt Max = APSInt::getMaxValue(Width, Unsigned);
920   APFloat MaxSrc(SrcSema, APFloat::uninitialized);
921   if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
922       APFloat::opOverflow)
923     // Don't need an overflow check for upper bound. Just check for
924     // +Inf/NaN.
925     MaxSrc = APFloat::getInf(SrcSema, false);
926   else
927     // Find the smallest value which is too large to represent (before
928     // truncation toward zero).
929     MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
930 
931   // If we're converting from __half, convert the range to float to match
932   // the type of src.
933   if (OrigSrcType->isHalfType()) {
934     const llvm::fltSemantics &Sema =
935       CGF.getContext().getFloatTypeSemantics(SrcType);
936     bool IsInexact;
937     MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
938     MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
939   }
940 
941   llvm::Value *GE =
942     Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
943   llvm::Value *LE =
944     Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
945   Check = Builder.CreateAnd(GE, LE);
946 
947   llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
948                                   CGF.EmitCheckTypeDescriptor(OrigSrcType),
949                                   CGF.EmitCheckTypeDescriptor(DstType)};
950   CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
951                 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
952 }
953 
954 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
955 // Returns 'i1 false' when the truncation Src -> Dst was lossy.
956 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
957                  std::pair<llvm::Value *, SanitizerMask>>
958 EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
959                                  QualType DstType, CGBuilderTy &Builder) {
960   llvm::Type *SrcTy = Src->getType();
961   llvm::Type *DstTy = Dst->getType();
962   (void)DstTy; // Only used in assert()
963 
964   // This should be truncation of integral types.
965   assert(Src != Dst);
966   assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
967   assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
968          "non-integer llvm type");
969 
970   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
971   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
972 
973   // If both (src and dst) types are unsigned, then it's an unsigned truncation.
974   // Else, it is a signed truncation.
975   ScalarExprEmitter::ImplicitConversionCheckKind Kind;
976   SanitizerMask Mask;
977   if (!SrcSigned && !DstSigned) {
978     Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
979     Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
980   } else {
981     Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
982     Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
983   }
984 
985   llvm::Value *Check = nullptr;
986   // 1. Extend the truncated value back to the same width as the Src.
987   Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
988   // 2. Equality-compare with the original source value
989   Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
990   // If the comparison result is 'i1 false', then the truncation was lossy.
991   return std::make_pair(Kind, std::make_pair(Check, Mask));
992 }
993 
994 static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
995     QualType SrcType, QualType DstType) {
996   return SrcType->isIntegerType() && DstType->isIntegerType();
997 }
998 
999 void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1000                                                    Value *Dst, QualType DstType,
1001                                                    SourceLocation Loc) {
1002   if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
1003     return;
1004 
1005   // We only care about int->int conversions here.
1006   // We ignore conversions to/from pointer and/or bool.
1007   if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1008                                                                        DstType))
1009     return;
1010 
1011   unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1012   unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1013   // This must be truncation. Else we do not care.
1014   if (SrcBits <= DstBits)
1015     return;
1016 
1017   assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1018 
1019   // If the integer sign change sanitizer is enabled,
1020   // and we are truncating from larger unsigned type to smaller signed type,
1021   // let that next sanitizer deal with it.
1022   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1023   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1024   if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1025       (!SrcSigned && DstSigned))
1026     return;
1027 
1028   CodeGenFunction::SanitizerScope SanScope(&CGF);
1029 
1030   std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1031             std::pair<llvm::Value *, SanitizerMask>>
1032       Check =
1033           EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1034   // If the comparison result is 'i1 false', then the truncation was lossy.
1035 
1036   // Do we care about this type of truncation?
1037   if (!CGF.SanOpts.has(Check.second.second))
1038     return;
1039 
1040   llvm::Constant *StaticArgs[] = {
1041       CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1042       CGF.EmitCheckTypeDescriptor(DstType),
1043       llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
1044   CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1045                 {Src, Dst});
1046 }
1047 
1048 // Should be called within CodeGenFunction::SanitizerScope RAII scope.
1049 // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1050 static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1051                  std::pair<llvm::Value *, SanitizerMask>>
1052 EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1053                                  QualType DstType, CGBuilderTy &Builder) {
1054   llvm::Type *SrcTy = Src->getType();
1055   llvm::Type *DstTy = Dst->getType();
1056 
1057   assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1058          "non-integer llvm type");
1059 
1060   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1061   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1062   (void)SrcSigned; // Only used in assert()
1063   (void)DstSigned; // Only used in assert()
1064   unsigned SrcBits = SrcTy->getScalarSizeInBits();
1065   unsigned DstBits = DstTy->getScalarSizeInBits();
1066   (void)SrcBits; // Only used in assert()
1067   (void)DstBits; // Only used in assert()
1068 
1069   assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1070          "either the widths should be different, or the signednesses.");
1071 
1072   // NOTE: zero value is considered to be non-negative.
1073   auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
1074                                        const char *Name) -> Value * {
1075     // Is this value a signed type?
1076     bool VSigned = VType->isSignedIntegerOrEnumerationType();
1077     llvm::Type *VTy = V->getType();
1078     if (!VSigned) {
1079       // If the value is unsigned, then it is never negative.
1080       // FIXME: can we encounter non-scalar VTy here?
1081       return llvm::ConstantInt::getFalse(VTy->getContext());
1082     }
1083     // Get the zero of the same type with which we will be comparing.
1084     llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1085     // %V.isnegative = icmp slt %V, 0
1086     // I.e is %V *strictly* less than zero, does it have negative value?
1087     return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1088                               llvm::Twine(Name) + "." + V->getName() +
1089                                   ".negativitycheck");
1090   };
1091 
1092   // 1. Was the old Value negative?
1093   llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
1094   // 2. Is the new Value negative?
1095   llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
1096   // 3. Now, was the 'negativity status' preserved during the conversion?
1097   //    NOTE: conversion from negative to zero is considered to change the sign.
1098   //    (We want to get 'false' when the conversion changed the sign)
1099   //    So we should just equality-compare the negativity statuses.
1100   llvm::Value *Check = nullptr;
1101   Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1102   // If the comparison result is 'false', then the conversion changed the sign.
1103   return std::make_pair(
1104       ScalarExprEmitter::ICCK_IntegerSignChange,
1105       std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1106 }
1107 
1108 void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1109                                                    Value *Dst, QualType DstType,
1110                                                    SourceLocation Loc) {
1111   if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1112     return;
1113 
1114   llvm::Type *SrcTy = Src->getType();
1115   llvm::Type *DstTy = Dst->getType();
1116 
1117   // We only care about int->int conversions here.
1118   // We ignore conversions to/from pointer and/or bool.
1119   if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1120                                                                        DstType))
1121     return;
1122 
1123   bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1124   bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1125   unsigned SrcBits = SrcTy->getScalarSizeInBits();
1126   unsigned DstBits = DstTy->getScalarSizeInBits();
1127 
1128   // Now, we do not need to emit the check in *all* of the cases.
1129   // We can avoid emitting it in some obvious cases where it would have been
1130   // dropped by the opt passes (instcombine) always anyways.
1131   // If it's a cast between effectively the same type, no check.
1132   // NOTE: this is *not* equivalent to checking the canonical types.
1133   if (SrcSigned == DstSigned && SrcBits == DstBits)
1134     return;
1135   // At least one of the values needs to have signed type.
1136   // If both are unsigned, then obviously, neither of them can be negative.
1137   if (!SrcSigned && !DstSigned)
1138     return;
1139   // If the conversion is to *larger* *signed* type, then no check is needed.
1140   // Because either sign-extension happens (so the sign will remain),
1141   // or zero-extension will happen (the sign bit will be zero.)
1142   if ((DstBits > SrcBits) && DstSigned)
1143     return;
1144   if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1145       (SrcBits > DstBits) && SrcSigned) {
1146     // If the signed integer truncation sanitizer is enabled,
1147     // and this is a truncation from signed type, then no check is needed.
1148     // Because here sign change check is interchangeable with truncation check.
1149     return;
1150   }
1151   // That's it. We can't rule out any more cases with the data we have.
1152 
1153   CodeGenFunction::SanitizerScope SanScope(&CGF);
1154 
1155   std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1156             std::pair<llvm::Value *, SanitizerMask>>
1157       Check;
1158 
1159   // Each of these checks needs to return 'false' when an issue was detected.
1160   ImplicitConversionCheckKind CheckKind;
1161   llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1162   // So we can 'and' all the checks together, and still get 'false',
1163   // if at least one of the checks detected an issue.
1164 
1165   Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1166   CheckKind = Check.first;
1167   Checks.emplace_back(Check.second);
1168 
1169   if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1170       (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1171     // If the signed integer truncation sanitizer was enabled,
1172     // and we are truncating from larger unsigned type to smaller signed type,
1173     // let's handle the case we skipped in that check.
1174     Check =
1175         EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1176     CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1177     Checks.emplace_back(Check.second);
1178     // If the comparison result is 'i1 false', then the truncation was lossy.
1179   }
1180 
1181   llvm::Constant *StaticArgs[] = {
1182       CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1183       CGF.EmitCheckTypeDescriptor(DstType),
1184       llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
1185   // EmitCheck() will 'and' all the checks together.
1186   CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1187                 {Src, Dst});
1188 }
1189 
1190 /// Emit a conversion from the specified type to the specified destination type,
1191 /// both of which are LLVM scalar types.
1192 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1193                                                QualType DstType,
1194                                                SourceLocation Loc,
1195                                                ScalarConversionOpts Opts) {
1196   // All conversions involving fixed point types should be handled by the
1197   // EmitFixedPoint family functions. This is done to prevent bloating up this
1198   // function more, and although fixed point numbers are represented by
1199   // integers, we do not want to follow any logic that assumes they should be
1200   // treated as integers.
1201   // TODO(leonardchan): When necessary, add another if statement checking for
1202   // conversions to fixed point types from other types.
1203   if (SrcType->isFixedPointType()) {
1204     if (DstType->isBooleanType())
1205       // It is important that we check this before checking if the dest type is
1206       // an integer because booleans are technically integer types.
1207       // We do not need to check the padding bit on unsigned types if unsigned
1208       // padding is enabled because overflow into this bit is undefined
1209       // behavior.
1210       return Builder.CreateIsNotNull(Src, "tobool");
1211     if (DstType->isFixedPointType() || DstType->isIntegerType())
1212       return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1213 
1214     llvm_unreachable(
1215         "Unhandled scalar conversion from a fixed point type to another type.");
1216   } else if (DstType->isFixedPointType()) {
1217     if (SrcType->isIntegerType())
1218       // This also includes converting booleans and enums to fixed point types.
1219       return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1220 
1221     llvm_unreachable(
1222         "Unhandled scalar conversion to a fixed point type from another type.");
1223   }
1224 
1225   QualType NoncanonicalSrcType = SrcType;
1226   QualType NoncanonicalDstType = DstType;
1227 
1228   SrcType = CGF.getContext().getCanonicalType(SrcType);
1229   DstType = CGF.getContext().getCanonicalType(DstType);
1230   if (SrcType == DstType) return Src;
1231 
1232   if (DstType->isVoidType()) return nullptr;
1233 
1234   llvm::Value *OrigSrc = Src;
1235   QualType OrigSrcType = SrcType;
1236   llvm::Type *SrcTy = Src->getType();
1237 
1238   // Handle conversions to bool first, they are special: comparisons against 0.
1239   if (DstType->isBooleanType())
1240     return EmitConversionToBool(Src, SrcType);
1241 
1242   llvm::Type *DstTy = ConvertType(DstType);
1243 
1244   // Cast from half through float if half isn't a native type.
1245   if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1246     // Cast to FP using the intrinsic if the half type itself isn't supported.
1247     if (DstTy->isFloatingPointTy()) {
1248       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1249         return Builder.CreateCall(
1250             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1251             Src);
1252     } else {
1253       // Cast to other types through float, using either the intrinsic or FPExt,
1254       // depending on whether the half type itself is supported
1255       // (as opposed to operations on half, available with NativeHalfType).
1256       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1257         Src = Builder.CreateCall(
1258             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1259                                  CGF.CGM.FloatTy),
1260             Src);
1261       } else {
1262         Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1263       }
1264       SrcType = CGF.getContext().FloatTy;
1265       SrcTy = CGF.FloatTy;
1266     }
1267   }
1268 
1269   // Ignore conversions like int -> uint.
1270   if (SrcTy == DstTy) {
1271     if (Opts.EmitImplicitIntegerSignChangeChecks)
1272       EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1273                                  NoncanonicalDstType, Loc);
1274 
1275     return Src;
1276   }
1277 
1278   // Handle pointer conversions next: pointers can only be converted to/from
1279   // other pointers and integers. Check for pointer types in terms of LLVM, as
1280   // some native types (like Obj-C id) may map to a pointer type.
1281   if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
1282     // The source value may be an integer, or a pointer.
1283     if (isa<llvm::PointerType>(SrcTy))
1284       return Builder.CreateBitCast(Src, DstTy, "conv");
1285 
1286     assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1287     // First, convert to the correct width so that we control the kind of
1288     // extension.
1289     llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1290     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1291     llvm::Value* IntResult =
1292         Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1293     // Then, cast to pointer.
1294     return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
1295   }
1296 
1297   if (isa<llvm::PointerType>(SrcTy)) {
1298     // Must be an ptr to int cast.
1299     assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1300     return Builder.CreatePtrToInt(Src, DstTy, "conv");
1301   }
1302 
1303   // A scalar can be splatted to an extended vector of the same element type
1304   if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
1305     // Sema should add casts to make sure that the source expression's type is
1306     // the same as the vector's element type (sans qualifiers)
1307     assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1308                SrcType.getTypePtr() &&
1309            "Splatted expr doesn't match with vector element type?");
1310 
1311     // Splat the element across to all elements
1312     unsigned NumElements = DstTy->getVectorNumElements();
1313     return Builder.CreateVectorSplat(NumElements, Src, "splat");
1314   }
1315 
1316   if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
1317     // Allow bitcast from vector to integer/fp of the same size.
1318     unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1319     unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1320     if (SrcSize == DstSize)
1321       return Builder.CreateBitCast(Src, DstTy, "conv");
1322 
1323     // Conversions between vectors of different sizes are not allowed except
1324     // when vectors of half are involved. Operations on storage-only half
1325     // vectors require promoting half vector operands to float vectors and
1326     // truncating the result, which is either an int or float vector, to a
1327     // short or half vector.
1328 
1329     // Source and destination are both expected to be vectors.
1330     llvm::Type *SrcElementTy = SrcTy->getVectorElementType();
1331     llvm::Type *DstElementTy = DstTy->getVectorElementType();
1332     (void)DstElementTy;
1333 
1334     assert(((SrcElementTy->isIntegerTy() &&
1335              DstElementTy->isIntegerTy()) ||
1336             (SrcElementTy->isFloatingPointTy() &&
1337              DstElementTy->isFloatingPointTy())) &&
1338            "unexpected conversion between a floating-point vector and an "
1339            "integer vector");
1340 
1341     // Truncate an i32 vector to an i16 vector.
1342     if (SrcElementTy->isIntegerTy())
1343       return Builder.CreateIntCast(Src, DstTy, false, "conv");
1344 
1345     // Truncate a float vector to a half vector.
1346     if (SrcSize > DstSize)
1347       return Builder.CreateFPTrunc(Src, DstTy, "conv");
1348 
1349     // Promote a half vector to a float vector.
1350     return Builder.CreateFPExt(Src, DstTy, "conv");
1351   }
1352 
1353   // Finally, we have the arithmetic types: real int/float.
1354   Value *Res = nullptr;
1355   llvm::Type *ResTy = DstTy;
1356 
1357   // An overflowing conversion has undefined behavior if either the source type
1358   // or the destination type is a floating-point type. However, we consider the
1359   // range of representable values for all floating-point types to be
1360   // [-inf,+inf], so no overflow can ever happen when the destination type is a
1361   // floating-point type.
1362   if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
1363       OrigSrcType->isFloatingType())
1364     EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1365                              Loc);
1366 
1367   // Cast to half through float if half isn't a native type.
1368   if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1369     // Make sure we cast in a single step if from another FP type.
1370     if (SrcTy->isFloatingPointTy()) {
1371       // Use the intrinsic if the half type itself isn't supported
1372       // (as opposed to operations on half, available with NativeHalfType).
1373       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1374         return Builder.CreateCall(
1375             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1376       // If the half type is supported, just use an fptrunc.
1377       return Builder.CreateFPTrunc(Src, DstTy);
1378     }
1379     DstTy = CGF.FloatTy;
1380   }
1381 
1382   if (isa<llvm::IntegerType>(SrcTy)) {
1383     bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1384     if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
1385       InputSigned = true;
1386     }
1387     if (isa<llvm::IntegerType>(DstTy))
1388       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1389     else if (InputSigned)
1390       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1391     else
1392       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1393   } else if (isa<llvm::IntegerType>(DstTy)) {
1394     assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
1395     if (DstType->isSignedIntegerOrEnumerationType())
1396       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1397     else
1398       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1399   } else {
1400     assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
1401            "Unknown real conversion");
1402     if (DstTy->getTypeID() < SrcTy->getTypeID())
1403       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1404     else
1405       Res = Builder.CreateFPExt(Src, DstTy, "conv");
1406   }
1407 
1408   if (DstTy != ResTy) {
1409     if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1410       assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1411       Res = Builder.CreateCall(
1412         CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1413         Res);
1414     } else {
1415       Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1416     }
1417   }
1418 
1419   if (Opts.EmitImplicitIntegerTruncationChecks)
1420     EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1421                                NoncanonicalDstType, Loc);
1422 
1423   if (Opts.EmitImplicitIntegerSignChangeChecks)
1424     EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1425                                NoncanonicalDstType, Loc);
1426 
1427   return Res;
1428 }
1429 
1430 Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1431                                                    QualType DstTy,
1432                                                    SourceLocation Loc) {
1433   FixedPointSemantics SrcFPSema =
1434       CGF.getContext().getFixedPointSemantics(SrcTy);
1435   FixedPointSemantics DstFPSema =
1436       CGF.getContext().getFixedPointSemantics(DstTy);
1437   return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc,
1438                                   DstTy->isIntegerType());
1439 }
1440 
1441 Value *ScalarExprEmitter::EmitFixedPointConversion(
1442     Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema,
1443     SourceLocation Loc, bool DstIsInteger) {
1444   using llvm::APInt;
1445   using llvm::ConstantInt;
1446   using llvm::Value;
1447 
1448   unsigned SrcWidth = SrcFPSema.getWidth();
1449   unsigned DstWidth = DstFPSema.getWidth();
1450   unsigned SrcScale = SrcFPSema.getScale();
1451   unsigned DstScale = DstFPSema.getScale();
1452   bool SrcIsSigned = SrcFPSema.isSigned();
1453   bool DstIsSigned = DstFPSema.isSigned();
1454 
1455   llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth);
1456 
1457   Value *Result = Src;
1458   unsigned ResultWidth = SrcWidth;
1459 
1460   // Downscale.
1461   if (DstScale < SrcScale) {
1462     // When converting to integers, we round towards zero. For negative numbers,
1463     // right shifting rounds towards negative infinity. In this case, we can
1464     // just round up before shifting.
1465     if (DstIsInteger && SrcIsSigned) {
1466       Value *Zero = llvm::Constant::getNullValue(Result->getType());
1467       Value *IsNegative = Builder.CreateICmpSLT(Result, Zero);
1468       Value *LowBits = ConstantInt::get(
1469           CGF.getLLVMContext(), APInt::getLowBitsSet(ResultWidth, SrcScale));
1470       Value *Rounded = Builder.CreateAdd(Result, LowBits);
1471       Result = Builder.CreateSelect(IsNegative, Rounded, Result);
1472     }
1473 
1474     Result = SrcIsSigned
1475                  ? Builder.CreateAShr(Result, SrcScale - DstScale, "downscale")
1476                  : Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
1477   }
1478 
1479   if (!DstFPSema.isSaturated()) {
1480     // Resize.
1481     Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
1482 
1483     // Upscale.
1484     if (DstScale > SrcScale)
1485       Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
1486   } else {
1487     // Adjust the number of fractional bits.
1488     if (DstScale > SrcScale) {
1489       // Compare to DstWidth to prevent resizing twice.
1490       ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
1491       llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth);
1492       Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
1493       Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
1494     }
1495 
1496     // Handle saturation.
1497     bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits();
1498     if (LessIntBits) {
1499       Value *Max = ConstantInt::get(
1500           CGF.getLLVMContext(),
1501           APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth));
1502       Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max)
1503                                    : Builder.CreateICmpUGT(Result, Max);
1504       Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax");
1505     }
1506     // Cannot overflow min to dest type if src is unsigned since all fixed
1507     // point types can cover the unsigned min of 0.
1508     if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
1509       Value *Min = ConstantInt::get(
1510           CGF.getLLVMContext(),
1511           APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth));
1512       Value *TooLow = Builder.CreateICmpSLT(Result, Min);
1513       Result = Builder.CreateSelect(TooLow, Min, Result, "satmin");
1514     }
1515 
1516     // Resize the integer part to get the final destination size.
1517     if (ResultWidth != DstWidth)
1518       Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
1519   }
1520   return Result;
1521 }
1522 
1523 /// Emit a conversion from the specified complex type to the specified
1524 /// destination type, where the destination type is an LLVM scalar type.
1525 Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1526     CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1527     SourceLocation Loc) {
1528   // Get the source element type.
1529   SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1530 
1531   // Handle conversions to bool first, they are special: comparisons against 0.
1532   if (DstTy->isBooleanType()) {
1533     //  Complex != 0  -> (Real != 0) | (Imag != 0)
1534     Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1535     Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
1536     return Builder.CreateOr(Src.first, Src.second, "tobool");
1537   }
1538 
1539   // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1540   // the imaginary part of the complex value is discarded and the value of the
1541   // real part is converted according to the conversion rules for the
1542   // corresponding real type.
1543   return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1544 }
1545 
1546 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1547   return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
1548 }
1549 
1550 /// Emit a sanitization check for the given "binary" operation (which
1551 /// might actually be a unary increment which has been lowered to a binary
1552 /// operation). The check passes if all values in \p Checks (which are \c i1),
1553 /// are \c true.
1554 void ScalarExprEmitter::EmitBinOpCheck(
1555     ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
1556   assert(CGF.IsSanitizerScope);
1557   SanitizerHandler Check;
1558   SmallVector<llvm::Constant *, 4> StaticData;
1559   SmallVector<llvm::Value *, 2> DynamicData;
1560 
1561   BinaryOperatorKind Opcode = Info.Opcode;
1562   if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1563     Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1564 
1565   StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1566   const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1567   if (UO && UO->getOpcode() == UO_Minus) {
1568     Check = SanitizerHandler::NegateOverflow;
1569     StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1570     DynamicData.push_back(Info.RHS);
1571   } else {
1572     if (BinaryOperator::isShiftOp(Opcode)) {
1573       // Shift LHS negative or too large, or RHS out of bounds.
1574       Check = SanitizerHandler::ShiftOutOfBounds;
1575       const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1576       StaticData.push_back(
1577         CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1578       StaticData.push_back(
1579         CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1580     } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1581       // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1582       Check = SanitizerHandler::DivremOverflow;
1583       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1584     } else {
1585       // Arithmetic overflow (+, -, *).
1586       switch (Opcode) {
1587       case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1588       case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1589       case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
1590       default: llvm_unreachable("unexpected opcode for bin op check");
1591       }
1592       StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
1593     }
1594     DynamicData.push_back(Info.LHS);
1595     DynamicData.push_back(Info.RHS);
1596   }
1597 
1598   CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
1599 }
1600 
1601 //===----------------------------------------------------------------------===//
1602 //                            Visitor Methods
1603 //===----------------------------------------------------------------------===//
1604 
1605 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1606   CGF.ErrorUnsupported(E, "scalar expression");
1607   if (E->getType()->isVoidType())
1608     return nullptr;
1609   return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1610 }
1611 
1612 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
1613   // Vector Mask Case
1614   if (E->getNumSubExprs() == 2) {
1615     Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1616     Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1617     Value *Mask;
1618 
1619     llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
1620     unsigned LHSElts = LTy->getNumElements();
1621 
1622     Mask = RHS;
1623 
1624     llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
1625 
1626     // Mask off the high bits of each shuffle index.
1627     Value *MaskBits =
1628         llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
1629     Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
1630 
1631     // newv = undef
1632     // mask = mask & maskbits
1633     // for each elt
1634     //   n = extract mask i
1635     //   x = extract val n
1636     //   newv = insert newv, x, i
1637     llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
1638                                                   MTy->getNumElements());
1639     Value* NewV = llvm::UndefValue::get(RTy);
1640     for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
1641       Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
1642       Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
1643 
1644       Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
1645       NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
1646     }
1647     return NewV;
1648   }
1649 
1650   Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1651   Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
1652 
1653   SmallVector<llvm::Constant*, 32> indices;
1654   for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
1655     llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1656     // Check for -1 and output it as undef in the IR.
1657     if (Idx.isSigned() && Idx.isAllOnesValue())
1658       indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1659     else
1660       indices.push_back(Builder.getInt32(Idx.getZExtValue()));
1661   }
1662 
1663   Value *SV = llvm::ConstantVector::get(indices);
1664   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1665 }
1666 
1667 Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1668   QualType SrcType = E->getSrcExpr()->getType(),
1669            DstType = E->getType();
1670 
1671   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
1672 
1673   SrcType = CGF.getContext().getCanonicalType(SrcType);
1674   DstType = CGF.getContext().getCanonicalType(DstType);
1675   if (SrcType == DstType) return Src;
1676 
1677   assert(SrcType->isVectorType() &&
1678          "ConvertVector source type must be a vector");
1679   assert(DstType->isVectorType() &&
1680          "ConvertVector destination type must be a vector");
1681 
1682   llvm::Type *SrcTy = Src->getType();
1683   llvm::Type *DstTy = ConvertType(DstType);
1684 
1685   // Ignore conversions like int -> uint.
1686   if (SrcTy == DstTy)
1687     return Src;
1688 
1689   QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
1690            DstEltType = DstType->castAs<VectorType>()->getElementType();
1691 
1692   assert(SrcTy->isVectorTy() &&
1693          "ConvertVector source IR type must be a vector");
1694   assert(DstTy->isVectorTy() &&
1695          "ConvertVector destination IR type must be a vector");
1696 
1697   llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1698              *DstEltTy = DstTy->getVectorElementType();
1699 
1700   if (DstEltType->isBooleanType()) {
1701     assert((SrcEltTy->isFloatingPointTy() ||
1702             isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1703 
1704     llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1705     if (SrcEltTy->isFloatingPointTy()) {
1706       return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1707     } else {
1708       return Builder.CreateICmpNE(Src, Zero, "tobool");
1709     }
1710   }
1711 
1712   // We have the arithmetic types: real int/float.
1713   Value *Res = nullptr;
1714 
1715   if (isa<llvm::IntegerType>(SrcEltTy)) {
1716     bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1717     if (isa<llvm::IntegerType>(DstEltTy))
1718       Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1719     else if (InputSigned)
1720       Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1721     else
1722       Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1723   } else if (isa<llvm::IntegerType>(DstEltTy)) {
1724     assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1725     if (DstEltType->isSignedIntegerOrEnumerationType())
1726       Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1727     else
1728       Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1729   } else {
1730     assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1731            "Unknown real conversion");
1732     if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1733       Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1734     else
1735       Res = Builder.CreateFPExt(Src, DstTy, "conv");
1736   }
1737 
1738   return Res;
1739 }
1740 
1741 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
1742   if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1743     CGF.EmitIgnoredExpr(E->getBase());
1744     return CGF.emitScalarConstant(Constant, E);
1745   } else {
1746     Expr::EvalResult Result;
1747     if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1748       llvm::APSInt Value = Result.Val.getInt();
1749       CGF.EmitIgnoredExpr(E->getBase());
1750       return Builder.getInt(Value);
1751     }
1752   }
1753 
1754   return EmitLoadOfLValue(E);
1755 }
1756 
1757 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1758   TestAndClearIgnoreResultAssign();
1759 
1760   // Emit subscript expressions in rvalue context's.  For most cases, this just
1761   // loads the lvalue formed by the subscript expr.  However, we have to be
1762   // careful, because the base of a vector subscript is occasionally an rvalue,
1763   // so we can't get it as an lvalue.
1764   if (!E->getBase()->getType()->isVectorType())
1765     return EmitLoadOfLValue(E);
1766 
1767   // Handle the vector case.  The base must be a vector, the index must be an
1768   // integer value.
1769   Value *Base = Visit(E->getBase());
1770   Value *Idx  = Visit(E->getIdx());
1771   QualType IdxTy = E->getIdx()->getType();
1772 
1773   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
1774     CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1775 
1776   return Builder.CreateExtractElement(Base, Idx, "vecext");
1777 }
1778 
1779 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1780                                   unsigned Off, llvm::Type *I32Ty) {
1781   int MV = SVI->getMaskValue(Idx);
1782   if (MV == -1)
1783     return llvm::UndefValue::get(I32Ty);
1784   return llvm::ConstantInt::get(I32Ty, Off+MV);
1785 }
1786 
1787 static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1788   if (C->getBitWidth() != 32) {
1789       assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1790                                                     C->getZExtValue()) &&
1791              "Index operand too large for shufflevector mask!");
1792       return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1793   }
1794   return C;
1795 }
1796 
1797 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1798   bool Ignore = TestAndClearIgnoreResultAssign();
1799   (void)Ignore;
1800   assert (Ignore == false && "init list ignored");
1801   unsigned NumInitElements = E->getNumInits();
1802 
1803   if (E->hadArrayRangeDesignator())
1804     CGF.ErrorUnsupported(E, "GNU array range designator extension");
1805 
1806   llvm::VectorType *VType =
1807     dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1808 
1809   if (!VType) {
1810     if (NumInitElements == 0) {
1811       // C++11 value-initialization for the scalar.
1812       return EmitNullValue(E->getType());
1813     }
1814     // We have a scalar in braces. Just use the first element.
1815     return Visit(E->getInit(0));
1816   }
1817 
1818   unsigned ResElts = VType->getNumElements();
1819 
1820   // Loop over initializers collecting the Value for each, and remembering
1821   // whether the source was swizzle (ExtVectorElementExpr).  This will allow
1822   // us to fold the shuffle for the swizzle into the shuffle for the vector
1823   // initializer, since LLVM optimizers generally do not want to touch
1824   // shuffles.
1825   unsigned CurIdx = 0;
1826   bool VIsUndefShuffle = false;
1827   llvm::Value *V = llvm::UndefValue::get(VType);
1828   for (unsigned i = 0; i != NumInitElements; ++i) {
1829     Expr *IE = E->getInit(i);
1830     Value *Init = Visit(IE);
1831     SmallVector<llvm::Constant*, 16> Args;
1832 
1833     llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1834 
1835     // Handle scalar elements.  If the scalar initializer is actually one
1836     // element of a different vector of the same width, use shuffle instead of
1837     // extract+insert.
1838     if (!VVT) {
1839       if (isa<ExtVectorElementExpr>(IE)) {
1840         llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1841 
1842         if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1843           llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1844           Value *LHS = nullptr, *RHS = nullptr;
1845           if (CurIdx == 0) {
1846             // insert into undef -> shuffle (src, undef)
1847             // shufflemask must use an i32
1848             Args.push_back(getAsInt32(C, CGF.Int32Ty));
1849             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1850 
1851             LHS = EI->getVectorOperand();
1852             RHS = V;
1853             VIsUndefShuffle = true;
1854           } else if (VIsUndefShuffle) {
1855             // insert into undefshuffle && size match -> shuffle (v, src)
1856             llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1857             for (unsigned j = 0; j != CurIdx; ++j)
1858               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
1859             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
1860             Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1861 
1862             LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1863             RHS = EI->getVectorOperand();
1864             VIsUndefShuffle = false;
1865           }
1866           if (!Args.empty()) {
1867             llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1868             V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1869             ++CurIdx;
1870             continue;
1871           }
1872         }
1873       }
1874       V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1875                                       "vecinit");
1876       VIsUndefShuffle = false;
1877       ++CurIdx;
1878       continue;
1879     }
1880 
1881     unsigned InitElts = VVT->getNumElements();
1882 
1883     // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1884     // input is the same width as the vector being constructed, generate an
1885     // optimized shuffle of the swizzle input into the result.
1886     unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1887     if (isa<ExtVectorElementExpr>(IE)) {
1888       llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1889       Value *SVOp = SVI->getOperand(0);
1890       llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
1891 
1892       if (OpTy->getNumElements() == ResElts) {
1893         for (unsigned j = 0; j != CurIdx; ++j) {
1894           // If the current vector initializer is a shuffle with undef, merge
1895           // this shuffle directly into it.
1896           if (VIsUndefShuffle) {
1897             Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
1898                                       CGF.Int32Ty));
1899           } else {
1900             Args.push_back(Builder.getInt32(j));
1901           }
1902         }
1903         for (unsigned j = 0, je = InitElts; j != je; ++j)
1904           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
1905         Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1906 
1907         if (VIsUndefShuffle)
1908           V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1909 
1910         Init = SVOp;
1911       }
1912     }
1913 
1914     // Extend init to result vector length, and then shuffle its contribution
1915     // to the vector initializer into V.
1916     if (Args.empty()) {
1917       for (unsigned j = 0; j != InitElts; ++j)
1918         Args.push_back(Builder.getInt32(j));
1919       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1920       llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1921       Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1922                                          Mask, "vext");
1923 
1924       Args.clear();
1925       for (unsigned j = 0; j != CurIdx; ++j)
1926         Args.push_back(Builder.getInt32(j));
1927       for (unsigned j = 0; j != InitElts; ++j)
1928         Args.push_back(Builder.getInt32(j+Offset));
1929       Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1930     }
1931 
1932     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1933     // merging subsequent shuffles into this one.
1934     if (CurIdx == 0)
1935       std::swap(V, Init);
1936     llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1937     V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1938     VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1939     CurIdx += InitElts;
1940   }
1941 
1942   // FIXME: evaluate codegen vs. shuffling against constant null vector.
1943   // Emit remaining default initializers.
1944   llvm::Type *EltTy = VType->getElementType();
1945 
1946   // Emit remaining default initializers
1947   for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1948     Value *Idx = Builder.getInt32(CurIdx);
1949     llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1950     V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1951   }
1952   return V;
1953 }
1954 
1955 bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
1956   const Expr *E = CE->getSubExpr();
1957 
1958   if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1959     return false;
1960 
1961   if (isa<CXXThisExpr>(E->IgnoreParens())) {
1962     // We always assume that 'this' is never null.
1963     return false;
1964   }
1965 
1966   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1967     // And that glvalue casts are never null.
1968     if (ICE->getValueKind() != VK_RValue)
1969       return false;
1970   }
1971 
1972   return true;
1973 }
1974 
1975 // VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
1976 // have to handle a more broad range of conversions than explicit casts, as they
1977 // handle things like function to ptr-to-function decay etc.
1978 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1979   Expr *E = CE->getSubExpr();
1980   QualType DestTy = CE->getType();
1981   CastKind Kind = CE->getCastKind();
1982 
1983   // These cases are generally not written to ignore the result of
1984   // evaluating their sub-expressions, so we clear this now.
1985   bool Ignored = TestAndClearIgnoreResultAssign();
1986 
1987   // Since almost all cast kinds apply to scalars, this switch doesn't have
1988   // a default case, so the compiler will warn on a missing case.  The cases
1989   // are in the same order as in the CastKind enum.
1990   switch (Kind) {
1991   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1992   case CK_BuiltinFnToFnPtr:
1993     llvm_unreachable("builtin functions are handled elsewhere");
1994 
1995   case CK_LValueBitCast:
1996   case CK_ObjCObjectLValueCast: {
1997     Address Addr = EmitLValue(E).getAddress(CGF);
1998     Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
1999     LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
2000     return EmitLoadOfLValue(LV, CE->getExprLoc());
2001   }
2002 
2003   case CK_LValueToRValueBitCast: {
2004     LValue SourceLVal = CGF.EmitLValue(E);
2005     Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
2006                                                 CGF.ConvertTypeForMem(DestTy));
2007     LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2008     DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2009     return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2010   }
2011 
2012   case CK_CPointerToObjCPointerCast:
2013   case CK_BlockPointerToObjCPointerCast:
2014   case CK_AnyPointerToBlockPointerCast:
2015   case CK_BitCast: {
2016     Value *Src = Visit(const_cast<Expr*>(E));
2017     llvm::Type *SrcTy = Src->getType();
2018     llvm::Type *DstTy = ConvertType(DestTy);
2019     if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
2020         SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
2021       llvm_unreachable("wrong cast for pointers in different address spaces"
2022                        "(must be an address space cast)!");
2023     }
2024 
2025     if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2026       if (auto PT = DestTy->getAs<PointerType>())
2027         CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
2028                                       /*MayBeNull=*/true,
2029                                       CodeGenFunction::CFITCK_UnrelatedCast,
2030                                       CE->getBeginLoc());
2031     }
2032 
2033     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2034       const QualType SrcType = E->getType();
2035 
2036       if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2037         // Casting to pointer that could carry dynamic information (provided by
2038         // invariant.group) requires launder.
2039         Src = Builder.CreateLaunderInvariantGroup(Src);
2040       } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2041         // Casting to pointer that does not carry dynamic information (provided
2042         // by invariant.group) requires stripping it.  Note that we don't do it
2043         // if the source could not be dynamic type and destination could be
2044         // dynamic because dynamic information is already laundered.  It is
2045         // because launder(strip(src)) == launder(src), so there is no need to
2046         // add extra strip before launder.
2047         Src = Builder.CreateStripInvariantGroup(Src);
2048       }
2049     }
2050 
2051     // Update heapallocsite metadata when there is an explicit cast.
2052     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(Src))
2053       if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE))
2054           CGF.getDebugInfo()->
2055               addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
2056 
2057     return Builder.CreateBitCast(Src, DstTy);
2058   }
2059   case CK_AddressSpaceConversion: {
2060     Expr::EvalResult Result;
2061     if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2062         Result.Val.isNullPointer()) {
2063       // If E has side effect, it is emitted even if its final result is a
2064       // null pointer. In that case, a DCE pass should be able to
2065       // eliminate the useless instructions emitted during translating E.
2066       if (Result.HasSideEffects)
2067         Visit(E);
2068       return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2069           ConvertType(DestTy)), DestTy);
2070     }
2071     // Since target may map different address spaces in AST to the same address
2072     // space, an address space conversion may end up as a bitcast.
2073     return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2074         CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2075         DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
2076   }
2077   case CK_AtomicToNonAtomic:
2078   case CK_NonAtomicToAtomic:
2079   case CK_NoOp:
2080   case CK_UserDefinedConversion:
2081     return Visit(const_cast<Expr*>(E));
2082 
2083   case CK_BaseToDerived: {
2084     const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2085     assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2086 
2087     Address Base = CGF.EmitPointerWithAlignment(E);
2088     Address Derived =
2089       CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
2090                                    CE->path_begin(), CE->path_end(),
2091                                    CGF.ShouldNullCheckClassCastValue(CE));
2092 
2093     // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2094     // performed and the object is not of the derived type.
2095     if (CGF.sanitizePerformTypeCheck())
2096       CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
2097                         Derived.getPointer(), DestTy->getPointeeType());
2098 
2099     if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
2100       CGF.EmitVTablePtrCheckForCast(
2101           DestTy->getPointeeType(), Derived.getPointer(),
2102           /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2103           CE->getBeginLoc());
2104 
2105     return Derived.getPointer();
2106   }
2107   case CK_UncheckedDerivedToBase:
2108   case CK_DerivedToBase: {
2109     // The EmitPointerWithAlignment path does this fine; just discard
2110     // the alignment.
2111     return CGF.EmitPointerWithAlignment(CE).getPointer();
2112   }
2113 
2114   case CK_Dynamic: {
2115     Address V = CGF.EmitPointerWithAlignment(E);
2116     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2117     return CGF.EmitDynamicCast(V, DCE);
2118   }
2119 
2120   case CK_ArrayToPointerDecay:
2121     return CGF.EmitArrayToPointerDecay(E).getPointer();
2122   case CK_FunctionToPointerDecay:
2123     return EmitLValue(E).getPointer(CGF);
2124 
2125   case CK_NullToPointer:
2126     if (MustVisitNullValue(E))
2127       CGF.EmitIgnoredExpr(E);
2128 
2129     return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2130                               DestTy);
2131 
2132   case CK_NullToMemberPointer: {
2133     if (MustVisitNullValue(E))
2134       CGF.EmitIgnoredExpr(E);
2135 
2136     const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2137     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2138   }
2139 
2140   case CK_ReinterpretMemberPointer:
2141   case CK_BaseToDerivedMemberPointer:
2142   case CK_DerivedToBaseMemberPointer: {
2143     Value *Src = Visit(E);
2144 
2145     // Note that the AST doesn't distinguish between checked and
2146     // unchecked member pointer conversions, so we always have to
2147     // implement checked conversions here.  This is inefficient when
2148     // actual control flow may be required in order to perform the
2149     // check, which it is for data member pointers (but not member
2150     // function pointers on Itanium and ARM).
2151     return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
2152   }
2153 
2154   case CK_ARCProduceObject:
2155     return CGF.EmitARCRetainScalarExpr(E);
2156   case CK_ARCConsumeObject:
2157     return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
2158   case CK_ARCReclaimReturnedObject:
2159     return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
2160   case CK_ARCExtendBlockObject:
2161     return CGF.EmitARCExtendBlockObject(E);
2162 
2163   case CK_CopyAndAutoreleaseBlockObject:
2164     return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
2165 
2166   case CK_FloatingRealToComplex:
2167   case CK_FloatingComplexCast:
2168   case CK_IntegralRealToComplex:
2169   case CK_IntegralComplexCast:
2170   case CK_IntegralComplexToFloatingComplex:
2171   case CK_FloatingComplexToIntegralComplex:
2172   case CK_ConstructorConversion:
2173   case CK_ToUnion:
2174     llvm_unreachable("scalar cast to non-scalar value");
2175 
2176   case CK_LValueToRValue:
2177     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2178     assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2179     return Visit(const_cast<Expr*>(E));
2180 
2181   case CK_IntegralToPointer: {
2182     Value *Src = Visit(const_cast<Expr*>(E));
2183 
2184     // First, convert to the correct width so that we control the kind of
2185     // extension.
2186     auto DestLLVMTy = ConvertType(DestTy);
2187     llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2188     bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2189     llvm::Value* IntResult =
2190       Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
2191 
2192     auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
2193 
2194     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2195       // Going from integer to pointer that could be dynamic requires reloading
2196       // dynamic information from invariant.group.
2197       if (DestTy.mayBeDynamicClass())
2198         IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2199     }
2200     return IntToPtr;
2201   }
2202   case CK_PointerToIntegral: {
2203     assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2204     auto *PtrExpr = Visit(E);
2205 
2206     if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2207       const QualType SrcType = E->getType();
2208 
2209       // Casting to integer requires stripping dynamic information as it does
2210       // not carries it.
2211       if (SrcType.mayBeDynamicClass())
2212         PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2213     }
2214 
2215     return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2216   }
2217   case CK_ToVoid: {
2218     CGF.EmitIgnoredExpr(E);
2219     return nullptr;
2220   }
2221   case CK_VectorSplat: {
2222     llvm::Type *DstTy = ConvertType(DestTy);
2223     Value *Elt = Visit(const_cast<Expr*>(E));
2224     // Splat the element across to all elements
2225     unsigned NumElements = DstTy->getVectorNumElements();
2226     return Builder.CreateVectorSplat(NumElements, Elt, "splat");
2227   }
2228 
2229   case CK_FixedPointCast:
2230     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2231                                 CE->getExprLoc());
2232 
2233   case CK_FixedPointToBoolean:
2234     assert(E->getType()->isFixedPointType() &&
2235            "Expected src type to be fixed point type");
2236     assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2237     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2238                                 CE->getExprLoc());
2239 
2240   case CK_FixedPointToIntegral:
2241     assert(E->getType()->isFixedPointType() &&
2242            "Expected src type to be fixed point type");
2243     assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2244     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2245                                 CE->getExprLoc());
2246 
2247   case CK_IntegralToFixedPoint:
2248     assert(E->getType()->isIntegerType() &&
2249            "Expected src type to be an integer");
2250     assert(DestTy->isFixedPointType() &&
2251            "Expected dest type to be fixed point type");
2252     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2253                                 CE->getExprLoc());
2254 
2255   case CK_IntegralCast: {
2256     ScalarConversionOpts Opts;
2257     if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
2258       if (!ICE->isPartOfExplicitCast())
2259         Opts = ScalarConversionOpts(CGF.SanOpts);
2260     }
2261     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2262                                 CE->getExprLoc(), Opts);
2263   }
2264   case CK_IntegralToFloating:
2265   case CK_FloatingToIntegral:
2266   case CK_FloatingCast:
2267     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2268                                 CE->getExprLoc());
2269   case CK_BooleanToSignedIntegral: {
2270     ScalarConversionOpts Opts;
2271     Opts.TreatBooleanAsSigned = true;
2272     return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2273                                 CE->getExprLoc(), Opts);
2274   }
2275   case CK_IntegralToBoolean:
2276     return EmitIntToBoolConversion(Visit(E));
2277   case CK_PointerToBoolean:
2278     return EmitPointerToBoolConversion(Visit(E), E->getType());
2279   case CK_FloatingToBoolean:
2280     return EmitFloatToBoolConversion(Visit(E));
2281   case CK_MemberPointerToBoolean: {
2282     llvm::Value *MemPtr = Visit(E);
2283     const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2284     return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
2285   }
2286 
2287   case CK_FloatingComplexToReal:
2288   case CK_IntegralComplexToReal:
2289     return CGF.EmitComplexExpr(E, false, true).first;
2290 
2291   case CK_FloatingComplexToBoolean:
2292   case CK_IntegralComplexToBoolean: {
2293     CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
2294 
2295     // TODO: kill this function off, inline appropriate case here
2296     return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2297                                          CE->getExprLoc());
2298   }
2299 
2300   case CK_ZeroToOCLOpaqueType: {
2301     assert((DestTy->isEventT() || DestTy->isQueueT() ||
2302             DestTy->isOCLIntelSubgroupAVCType()) &&
2303            "CK_ZeroToOCLEvent cast on non-event type");
2304     return llvm::Constant::getNullValue(ConvertType(DestTy));
2305   }
2306 
2307   case CK_IntToOCLSampler:
2308     return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
2309 
2310   } // end of switch
2311 
2312   llvm_unreachable("unknown scalar cast");
2313 }
2314 
2315 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
2316   CodeGenFunction::StmtExprEvaluation eval(CGF);
2317   Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2318                                            !E->getType()->isVoidType());
2319   if (!RetAlloca.isValid())
2320     return nullptr;
2321   return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2322                               E->getExprLoc());
2323 }
2324 
2325 Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2326   CGF.enterFullExpression(E);
2327   CodeGenFunction::RunCleanupsScope Scope(CGF);
2328   Value *V = Visit(E->getSubExpr());
2329   // Defend against dominance problems caused by jumps out of expression
2330   // evaluation through the shared cleanup block.
2331   Scope.ForceCleanup({&V});
2332   return V;
2333 }
2334 
2335 //===----------------------------------------------------------------------===//
2336 //                             Unary Operators
2337 //===----------------------------------------------------------------------===//
2338 
2339 static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2340                                            llvm::Value *InVal, bool IsInc) {
2341   BinOpInfo BinOp;
2342   BinOp.LHS = InVal;
2343   BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2344   BinOp.Ty = E->getType();
2345   BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
2346   // FIXME: once UnaryOperator carries FPFeatures, copy it here.
2347   BinOp.E = E;
2348   return BinOp;
2349 }
2350 
2351 llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2352     const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2353   llvm::Value *Amount =
2354       llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2355   StringRef Name = IsInc ? "inc" : "dec";
2356   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2357   case LangOptions::SOB_Defined:
2358     return Builder.CreateAdd(InVal, Amount, Name);
2359   case LangOptions::SOB_Undefined:
2360     if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
2361       return Builder.CreateNSWAdd(InVal, Amount, Name);
2362     LLVM_FALLTHROUGH;
2363   case LangOptions::SOB_Trapping:
2364     if (!E->canOverflow())
2365       return Builder.CreateNSWAdd(InVal, Amount, Name);
2366     return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
2367   }
2368   llvm_unreachable("Unknown SignedOverflowBehaviorTy");
2369 }
2370 
2371 namespace {
2372 /// Handles check and update for lastprivate conditional variables.
2373 class OMPLastprivateConditionalUpdateRAII {
2374 private:
2375   CodeGenFunction &CGF;
2376   const UnaryOperator *E;
2377 
2378 public:
2379   OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
2380                                       const UnaryOperator *E)
2381       : CGF(CGF), E(E) {}
2382   ~OMPLastprivateConditionalUpdateRAII() {
2383     if (CGF.getLangOpts().OpenMP)
2384       CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
2385           CGF, E->getSubExpr());
2386   }
2387 };
2388 } // namespace
2389 
2390 llvm::Value *
2391 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2392                                            bool isInc, bool isPre) {
2393   OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
2394   QualType type = E->getSubExpr()->getType();
2395   llvm::PHINode *atomicPHI = nullptr;
2396   llvm::Value *value;
2397   llvm::Value *input;
2398 
2399   int amount = (isInc ? 1 : -1);
2400   bool isSubtraction = !isInc;
2401 
2402   if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
2403     type = atomicTy->getValueType();
2404     if (isInc && type->isBooleanType()) {
2405       llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2406       if (isPre) {
2407         Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
2408             ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
2409         return Builder.getTrue();
2410       }
2411       // For atomic bool increment, we just store true and return it for
2412       // preincrement, do an atomic swap with true for postincrement
2413       return Builder.CreateAtomicRMW(
2414           llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
2415           llvm::AtomicOrdering::SequentiallyConsistent);
2416     }
2417     // Special case for atomic increment / decrement on integers, emit
2418     // atomicrmw instructions.  We skip this if we want to be doing overflow
2419     // checking, and fall into the slow path with the atomic cmpxchg loop.
2420     if (!type->isBooleanType() && type->isIntegerType() &&
2421         !(type->isUnsignedIntegerType() &&
2422           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2423         CGF.getLangOpts().getSignedOverflowBehavior() !=
2424             LangOptions::SOB_Trapping) {
2425       llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2426         llvm::AtomicRMWInst::Sub;
2427       llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2428         llvm::Instruction::Sub;
2429       llvm::Value *amt = CGF.EmitToMemory(
2430           llvm::ConstantInt::get(ConvertType(type), 1, true), type);
2431       llvm::Value *old =
2432           Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
2433                                   llvm::AtomicOrdering::SequentiallyConsistent);
2434       return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2435     }
2436     value = EmitLoadOfLValue(LV, E->getExprLoc());
2437     input = value;
2438     // For every other atomic operation, we need to emit a load-op-cmpxchg loop
2439     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2440     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
2441     value = CGF.EmitToMemory(value, type);
2442     Builder.CreateBr(opBB);
2443     Builder.SetInsertPoint(opBB);
2444     atomicPHI = Builder.CreatePHI(value->getType(), 2);
2445     atomicPHI->addIncoming(value, startBB);
2446     value = atomicPHI;
2447   } else {
2448     value = EmitLoadOfLValue(LV, E->getExprLoc());
2449     input = value;
2450   }
2451 
2452   // Special case of integer increment that we have to check first: bool++.
2453   // Due to promotion rules, we get:
2454   //   bool++ -> bool = bool + 1
2455   //          -> bool = (int)bool + 1
2456   //          -> bool = ((int)bool + 1 != 0)
2457   // An interesting aspect of this is that increment is always true.
2458   // Decrement does not have this property.
2459   if (isInc && type->isBooleanType()) {
2460     value = Builder.getTrue();
2461 
2462   // Most common case by far: integer increment.
2463   } else if (type->isIntegerType()) {
2464     QualType promotedType;
2465     bool canPerformLossyDemotionCheck = false;
2466     if (type->isPromotableIntegerType()) {
2467       promotedType = CGF.getContext().getPromotedIntegerType(type);
2468       assert(promotedType != type && "Shouldn't promote to the same type.");
2469       canPerformLossyDemotionCheck = true;
2470       canPerformLossyDemotionCheck &=
2471           CGF.getContext().getCanonicalType(type) !=
2472           CGF.getContext().getCanonicalType(promotedType);
2473       canPerformLossyDemotionCheck &=
2474           PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
2475               type, promotedType);
2476       assert((!canPerformLossyDemotionCheck ||
2477               type->isSignedIntegerOrEnumerationType() ||
2478               promotedType->isSignedIntegerOrEnumerationType() ||
2479               ConvertType(type)->getScalarSizeInBits() ==
2480                   ConvertType(promotedType)->getScalarSizeInBits()) &&
2481              "The following check expects that if we do promotion to different "
2482              "underlying canonical type, at least one of the types (either "
2483              "base or promoted) will be signed, or the bitwidths will match.");
2484     }
2485     if (CGF.SanOpts.hasOneOf(
2486             SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
2487         canPerformLossyDemotionCheck) {
2488       // While `x += 1` (for `x` with width less than int) is modeled as
2489       // promotion+arithmetics+demotion, and we can catch lossy demotion with
2490       // ease; inc/dec with width less than int can't overflow because of
2491       // promotion rules, so we omit promotion+demotion, which means that we can
2492       // not catch lossy "demotion". Because we still want to catch these cases
2493       // when the sanitizer is enabled, we perform the promotion, then perform
2494       // the increment/decrement in the wider type, and finally
2495       // perform the demotion. This will catch lossy demotions.
2496 
2497       value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
2498       Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2499       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2500       // Do pass non-default ScalarConversionOpts so that sanitizer check is
2501       // emitted.
2502       value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
2503                                    ScalarConversionOpts(CGF.SanOpts));
2504 
2505       // Note that signed integer inc/dec with width less than int can't
2506       // overflow because of promotion rules; we're just eliding a few steps
2507       // here.
2508     } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
2509       value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2510     } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2511                CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
2512       value =
2513           EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
2514     } else {
2515       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2516       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2517     }
2518 
2519   // Next most common: pointer increment.
2520   } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2521     QualType type = ptr->getPointeeType();
2522 
2523     // VLA types don't have constant size.
2524     if (const VariableArrayType *vla
2525           = CGF.getContext().getAsVariableArrayType(type)) {
2526       llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
2527       if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
2528       if (CGF.getLangOpts().isSignedOverflowDefined())
2529         value = Builder.CreateGEP(value, numElts, "vla.inc");
2530       else
2531         value = CGF.EmitCheckedInBoundsGEP(
2532             value, numElts, /*SignedIndices=*/false, isSubtraction,
2533             E->getExprLoc(), "vla.inc");
2534 
2535     // Arithmetic on function pointers (!) is just +-1.
2536     } else if (type->isFunctionType()) {
2537       llvm::Value *amt = Builder.getInt32(amount);
2538 
2539       value = CGF.EmitCastToVoidPtr(value);
2540       if (CGF.getLangOpts().isSignedOverflowDefined())
2541         value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2542       else
2543         value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2544                                            isSubtraction, E->getExprLoc(),
2545                                            "incdec.funcptr");
2546       value = Builder.CreateBitCast(value, input->getType());
2547 
2548     // For everything else, we can just do a simple increment.
2549     } else {
2550       llvm::Value *amt = Builder.getInt32(amount);
2551       if (CGF.getLangOpts().isSignedOverflowDefined())
2552         value = Builder.CreateGEP(value, amt, "incdec.ptr");
2553       else
2554         value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2555                                            isSubtraction, E->getExprLoc(),
2556                                            "incdec.ptr");
2557     }
2558 
2559   // Vector increment/decrement.
2560   } else if (type->isVectorType()) {
2561     if (type->hasIntegerRepresentation()) {
2562       llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2563 
2564       value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2565     } else {
2566       value = Builder.CreateFAdd(
2567                   value,
2568                   llvm::ConstantFP::get(value->getType(), amount),
2569                   isInc ? "inc" : "dec");
2570     }
2571 
2572   // Floating point.
2573   } else if (type->isRealFloatingType()) {
2574     // Add the inc/dec to the real part.
2575     llvm::Value *amt;
2576 
2577     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2578       // Another special case: half FP increment should be done via float
2579       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2580         value = Builder.CreateCall(
2581             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2582                                  CGF.CGM.FloatTy),
2583             input, "incdec.conv");
2584       } else {
2585         value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2586       }
2587     }
2588 
2589     if (value->getType()->isFloatTy())
2590       amt = llvm::ConstantFP::get(VMContext,
2591                                   llvm::APFloat(static_cast<float>(amount)));
2592     else if (value->getType()->isDoubleTy())
2593       amt = llvm::ConstantFP::get(VMContext,
2594                                   llvm::APFloat(static_cast<double>(amount)));
2595     else {
2596       // Remaining types are Half, LongDouble or __float128. Convert from float.
2597       llvm::APFloat F(static_cast<float>(amount));
2598       bool ignored;
2599       const llvm::fltSemantics *FS;
2600       // Don't use getFloatTypeSemantics because Half isn't
2601       // necessarily represented using the "half" LLVM type.
2602       if (value->getType()->isFP128Ty())
2603         FS = &CGF.getTarget().getFloat128Format();
2604       else if (value->getType()->isHalfTy())
2605         FS = &CGF.getTarget().getHalfFormat();
2606       else
2607         FS = &CGF.getTarget().getLongDoubleFormat();
2608       F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
2609       amt = llvm::ConstantFP::get(VMContext, F);
2610     }
2611     value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2612 
2613     if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
2614       if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
2615         value = Builder.CreateCall(
2616             CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2617                                  CGF.CGM.FloatTy),
2618             value, "incdec.conv");
2619       } else {
2620         value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2621       }
2622     }
2623 
2624   // Fixed-point types.
2625   } else if (type->isFixedPointType()) {
2626     // Fixed-point types are tricky. In some cases, it isn't possible to
2627     // represent a 1 or a -1 in the type at all. Piggyback off of
2628     // EmitFixedPointBinOp to avoid having to reimplement saturation.
2629     BinOpInfo Info;
2630     Info.E = E;
2631     Info.Ty = E->getType();
2632     Info.Opcode = isInc ? BO_Add : BO_Sub;
2633     Info.LHS = value;
2634     Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
2635     // If the type is signed, it's better to represent this as +(-1) or -(-1),
2636     // since -1 is guaranteed to be representable.
2637     if (type->isSignedFixedPointType()) {
2638       Info.Opcode = isInc ? BO_Sub : BO_Add;
2639       Info.RHS = Builder.CreateNeg(Info.RHS);
2640     }
2641     // Now, convert from our invented integer literal to the type of the unary
2642     // op. This will upscale and saturate if necessary. This value can become
2643     // undef in some cases.
2644     FixedPointSemantics SrcSema =
2645         FixedPointSemantics::GetIntegerSemantics(value->getType()
2646                                                       ->getScalarSizeInBits(),
2647                                                  /*IsSigned=*/true);
2648     FixedPointSemantics DstSema =
2649         CGF.getContext().getFixedPointSemantics(Info.Ty);
2650     Info.RHS = EmitFixedPointConversion(Info.RHS, SrcSema, DstSema,
2651                                         E->getExprLoc());
2652     value = EmitFixedPointBinOp(Info);
2653 
2654   // Objective-C pointer types.
2655   } else {
2656     const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2657     value = CGF.EmitCastToVoidPtr(value);
2658 
2659     CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2660     if (!isInc) size = -size;
2661     llvm::Value *sizeValue =
2662       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2663 
2664     if (CGF.getLangOpts().isSignedOverflowDefined())
2665       value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2666     else
2667       value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2668                                          /*SignedIndices=*/false, isSubtraction,
2669                                          E->getExprLoc(), "incdec.objptr");
2670     value = Builder.CreateBitCast(value, input->getType());
2671   }
2672 
2673   if (atomicPHI) {
2674     llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
2675     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2676     auto Pair = CGF.EmitAtomicCompareExchange(
2677         LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2678     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2679     llvm::Value *success = Pair.second;
2680     atomicPHI->addIncoming(old, curBlock);
2681     Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
2682     Builder.SetInsertPoint(contBB);
2683     return isPre ? value : input;
2684   }
2685 
2686   // Store the updated result through the lvalue.
2687   if (LV.isBitField())
2688     CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
2689   else
2690     CGF.EmitStoreThroughLValue(RValue::get(value), LV);
2691 
2692   // If this is a postinc, return the value read from memory, otherwise use the
2693   // updated value.
2694   return isPre ? value : input;
2695 }
2696 
2697 
2698 
2699 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
2700   TestAndClearIgnoreResultAssign();
2701   Value *Op = Visit(E->getSubExpr());
2702 
2703   // Generate a unary FNeg for FP ops.
2704   if (Op->getType()->isFPOrFPVectorTy())
2705     return Builder.CreateFNeg(Op, "fneg");
2706 
2707   // Emit unary minus with EmitSub so we handle overflow cases etc.
2708   BinOpInfo BinOp;
2709   BinOp.RHS = Op;
2710   BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
2711   BinOp.Ty = E->getType();
2712   BinOp.Opcode = BO_Sub;
2713   // FIXME: once UnaryOperator carries FPFeatures, copy it here.
2714   BinOp.E = E;
2715   return EmitSub(BinOp);
2716 }
2717 
2718 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
2719   TestAndClearIgnoreResultAssign();
2720   Value *Op = Visit(E->getSubExpr());
2721   return Builder.CreateNot(Op, "neg");
2722 }
2723 
2724 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
2725   // Perform vector logical not on comparison with zero vector.
2726   if (E->getType()->isExtVectorType()) {
2727     Value *Oper = Visit(E->getSubExpr());
2728     Value *Zero = llvm::Constant::getNullValue(Oper->getType());
2729     Value *Result;
2730     if (Oper->getType()->isFPOrFPVectorTy())
2731       Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2732     else
2733       Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
2734     return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2735   }
2736 
2737   // Compare operand to zero.
2738   Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
2739 
2740   // Invert value.
2741   // TODO: Could dynamically modify easy computations here.  For example, if
2742   // the operand is an icmp ne, turn into icmp eq.
2743   BoolVal = Builder.CreateNot(BoolVal, "lnot");
2744 
2745   // ZExt result to the expr type.
2746   return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
2747 }
2748 
2749 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2750   // Try folding the offsetof to a constant.
2751   Expr::EvalResult EVResult;
2752   if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2753     llvm::APSInt Value = EVResult.Val.getInt();
2754     return Builder.getInt(Value);
2755   }
2756 
2757   // Loop over the components of the offsetof to compute the value.
2758   unsigned n = E->getNumComponents();
2759   llvm::Type* ResultType = ConvertType(E->getType());
2760   llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2761   QualType CurrentType = E->getTypeSourceInfo()->getType();
2762   for (unsigned i = 0; i != n; ++i) {
2763     OffsetOfNode ON = E->getComponent(i);
2764     llvm::Value *Offset = nullptr;
2765     switch (ON.getKind()) {
2766     case OffsetOfNode::Array: {
2767       // Compute the index
2768       Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2769       llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
2770       bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
2771       Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2772 
2773       // Save the element type
2774       CurrentType =
2775           CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2776 
2777       // Compute the element size
2778       llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2779           CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2780 
2781       // Multiply out to compute the result
2782       Offset = Builder.CreateMul(Idx, ElemSize);
2783       break;
2784     }
2785 
2786     case OffsetOfNode::Field: {
2787       FieldDecl *MemberDecl = ON.getField();
2788       RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2789       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2790 
2791       // Compute the index of the field in its parent.
2792       unsigned i = 0;
2793       // FIXME: It would be nice if we didn't have to loop here!
2794       for (RecordDecl::field_iterator Field = RD->field_begin(),
2795                                       FieldEnd = RD->field_end();
2796            Field != FieldEnd; ++Field, ++i) {
2797         if (*Field == MemberDecl)
2798           break;
2799       }
2800       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2801 
2802       // Compute the offset to the field
2803       int64_t OffsetInt = RL.getFieldOffset(i) /
2804                           CGF.getContext().getCharWidth();
2805       Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2806 
2807       // Save the element type.
2808       CurrentType = MemberDecl->getType();
2809       break;
2810     }
2811 
2812     case OffsetOfNode::Identifier:
2813       llvm_unreachable("dependent __builtin_offsetof");
2814 
2815     case OffsetOfNode::Base: {
2816       if (ON.getBase()->isVirtual()) {
2817         CGF.ErrorUnsupported(E, "virtual base in offsetof");
2818         continue;
2819       }
2820 
2821       RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
2822       const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2823 
2824       // Save the element type.
2825       CurrentType = ON.getBase()->getType();
2826 
2827       // Compute the offset to the base.
2828       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2829       CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
2830       CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2831       Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
2832       break;
2833     }
2834     }
2835     Result = Builder.CreateAdd(Result, Offset);
2836   }
2837   return Result;
2838 }
2839 
2840 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
2841 /// argument of the sizeof expression as an integer.
2842 Value *
2843 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2844                               const UnaryExprOrTypeTraitExpr *E) {
2845   QualType TypeToSize = E->getTypeOfArgument();
2846   if (E->getKind() == UETT_SizeOf) {
2847     if (const VariableArrayType *VAT =
2848           CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2849       if (E->isArgumentType()) {
2850         // sizeof(type) - make sure to emit the VLA size.
2851         CGF.EmitVariablyModifiedType(TypeToSize);
2852       } else {
2853         // C99 6.5.3.4p2: If the argument is an expression of type
2854         // VLA, it is evaluated.
2855         CGF.EmitIgnoredExpr(E->getArgumentExpr());
2856       }
2857 
2858       auto VlaSize = CGF.getVLASize(VAT);
2859       llvm::Value *size = VlaSize.NumElts;
2860 
2861       // Scale the number of non-VLA elements by the non-VLA element size.
2862       CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
2863       if (!eltSize.isOne())
2864         size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
2865 
2866       return size;
2867     }
2868   } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2869     auto Alignment =
2870         CGF.getContext()
2871             .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2872                 E->getTypeOfArgument()->getPointeeType()))
2873             .getQuantity();
2874     return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
2875   }
2876 
2877   // If this isn't sizeof(vla), the result must be constant; use the constant
2878   // folding logic so we don't have to duplicate it here.
2879   return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
2880 }
2881 
2882 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2883   Expr *Op = E->getSubExpr();
2884   if (Op->getType()->isAnyComplexType()) {
2885     // If it's an l-value, load through the appropriate subobject l-value.
2886     // Note that we have to ask E because Op might be an l-value that
2887     // this won't work for, e.g. an Obj-C property.
2888     if (E->isGLValue())
2889       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2890                                   E->getExprLoc()).getScalarVal();
2891 
2892     // Otherwise, calculate and project.
2893     return CGF.EmitComplexExpr(Op, false, true).first;
2894   }
2895 
2896   return Visit(Op);
2897 }
2898 
2899 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2900   Expr *Op = E->getSubExpr();
2901   if (Op->getType()->isAnyComplexType()) {
2902     // If it's an l-value, load through the appropriate subobject l-value.
2903     // Note that we have to ask E because Op might be an l-value that
2904     // this won't work for, e.g. an Obj-C property.
2905     if (Op->isGLValue())
2906       return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2907                                   E->getExprLoc()).getScalarVal();
2908 
2909     // Otherwise, calculate and project.
2910     return CGF.EmitComplexExpr(Op, true, false).second;
2911   }
2912 
2913   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
2914   // effects are evaluated, but not the actual value.
2915   if (Op->isGLValue())
2916     CGF.EmitLValue(Op);
2917   else
2918     CGF.EmitScalarExpr(Op, true);
2919   return llvm::Constant::getNullValue(ConvertType(E->getType()));
2920 }
2921 
2922 //===----------------------------------------------------------------------===//
2923 //                           Binary Operators
2924 //===----------------------------------------------------------------------===//
2925 
2926 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
2927   TestAndClearIgnoreResultAssign();
2928   BinOpInfo Result;
2929   Result.LHS = Visit(E->getLHS());
2930   Result.RHS = Visit(E->getRHS());
2931   Result.Ty  = E->getType();
2932   Result.Opcode = E->getOpcode();
2933   Result.FPFeatures = E->getFPFeatures();
2934   Result.E = E;
2935   return Result;
2936 }
2937 
2938 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2939                                               const CompoundAssignOperator *E,
2940                         Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
2941                                                    Value *&Result) {
2942   QualType LHSTy = E->getLHS()->getType();
2943   BinOpInfo OpInfo;
2944 
2945   if (E->getComputationResultType()->isAnyComplexType())
2946     return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
2947 
2948   // Emit the RHS first.  __block variables need to have the rhs evaluated
2949   // first, plus this should improve codegen a little.
2950   OpInfo.RHS = Visit(E->getRHS());
2951   OpInfo.Ty = E->getComputationResultType();
2952   OpInfo.Opcode = E->getOpcode();
2953   OpInfo.FPFeatures = E->getFPFeatures();
2954   OpInfo.E = E;
2955   // Load/convert the LHS.
2956   LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2957 
2958   llvm::PHINode *atomicPHI = nullptr;
2959   if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2960     QualType type = atomicTy->getValueType();
2961     if (!type->isBooleanType() && type->isIntegerType() &&
2962         !(type->isUnsignedIntegerType() &&
2963           CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2964         CGF.getLangOpts().getSignedOverflowBehavior() !=
2965             LangOptions::SOB_Trapping) {
2966       llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
2967       llvm::Instruction::BinaryOps Op;
2968       switch (OpInfo.Opcode) {
2969         // We don't have atomicrmw operands for *, %, /, <<, >>
2970         case BO_MulAssign: case BO_DivAssign:
2971         case BO_RemAssign:
2972         case BO_ShlAssign:
2973         case BO_ShrAssign:
2974           break;
2975         case BO_AddAssign:
2976           AtomicOp = llvm::AtomicRMWInst::Add;
2977           Op = llvm::Instruction::Add;
2978           break;
2979         case BO_SubAssign:
2980           AtomicOp = llvm::AtomicRMWInst::Sub;
2981           Op = llvm::Instruction::Sub;
2982           break;
2983         case BO_AndAssign:
2984           AtomicOp = llvm::AtomicRMWInst::And;
2985           Op = llvm::Instruction::And;
2986           break;
2987         case BO_XorAssign:
2988           AtomicOp = llvm::AtomicRMWInst::Xor;
2989           Op = llvm::Instruction::Xor;
2990           break;
2991         case BO_OrAssign:
2992           AtomicOp = llvm::AtomicRMWInst::Or;
2993           Op = llvm::Instruction::Or;
2994           break;
2995         default:
2996           llvm_unreachable("Invalid compound assignment type");
2997       }
2998       if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
2999         llvm::Value *Amt = CGF.EmitToMemory(
3000             EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
3001                                  E->getExprLoc()),
3002             LHSTy);
3003         Value *OldVal = Builder.CreateAtomicRMW(
3004             AtomicOp, LHSLV.getPointer(CGF), Amt,
3005             llvm::AtomicOrdering::SequentiallyConsistent);
3006 
3007         // Since operation is atomic, the result type is guaranteed to be the
3008         // same as the input in LLVM terms.
3009         Result = Builder.CreateBinOp(Op, OldVal, Amt);
3010         return LHSLV;
3011       }
3012     }
3013     // FIXME: For floating point types, we should be saving and restoring the
3014     // floating point environment in the loop.
3015     llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3016     llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
3017     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3018     OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
3019     Builder.CreateBr(opBB);
3020     Builder.SetInsertPoint(opBB);
3021     atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
3022     atomicPHI->addIncoming(OpInfo.LHS, startBB);
3023     OpInfo.LHS = atomicPHI;
3024   }
3025   else
3026     OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
3027 
3028   SourceLocation Loc = E->getExprLoc();
3029   OpInfo.LHS =
3030       EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
3031 
3032   // Expand the binary operator.
3033   Result = (this->*Func)(OpInfo);
3034 
3035   // Convert the result back to the LHS type,
3036   // potentially with Implicit Conversion sanitizer check.
3037   Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
3038                                 Loc, ScalarConversionOpts(CGF.SanOpts));
3039 
3040   if (atomicPHI) {
3041     llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3042     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
3043     auto Pair = CGF.EmitAtomicCompareExchange(
3044         LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3045     llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3046     llvm::Value *success = Pair.second;
3047     atomicPHI->addIncoming(old, curBlock);
3048     Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
3049     Builder.SetInsertPoint(contBB);
3050     return LHSLV;
3051   }
3052 
3053   // Store the result value into the LHS lvalue. Bit-fields are handled
3054   // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3055   // 'An assignment expression has the value of the left operand after the
3056   // assignment...'.
3057   if (LHSLV.isBitField())
3058     CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
3059   else
3060     CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
3061 
3062   if (CGF.getLangOpts().OpenMP)
3063     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3064                                                                   E->getLHS());
3065   return LHSLV;
3066 }
3067 
3068 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3069                       Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3070   bool Ignore = TestAndClearIgnoreResultAssign();
3071   Value *RHS = nullptr;
3072   LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3073 
3074   // If the result is clearly ignored, return now.
3075   if (Ignore)
3076     return nullptr;
3077 
3078   // The result of an assignment in C is the assigned r-value.
3079   if (!CGF.getLangOpts().CPlusPlus)
3080     return RHS;
3081 
3082   // If the lvalue is non-volatile, return the computed value of the assignment.
3083   if (!LHS.isVolatileQualified())
3084     return RHS;
3085 
3086   // Otherwise, reload the value.
3087   return EmitLoadOfLValue(LHS, E->getExprLoc());
3088 }
3089 
3090 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
3091     const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
3092   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
3093 
3094   if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
3095     Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3096                                     SanitizerKind::IntegerDivideByZero));
3097   }
3098 
3099   const auto *BO = cast<BinaryOperator>(Ops.E);
3100   if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
3101       Ops.Ty->hasSignedIntegerRepresentation() &&
3102       !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3103       Ops.mayHaveIntegerOverflow()) {
3104     llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3105 
3106     llvm::Value *IntMin =
3107       Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
3108     llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
3109 
3110     llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3111     llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
3112     llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3113     Checks.push_back(
3114         std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
3115   }
3116 
3117   if (Checks.size() > 0)
3118     EmitBinOpCheck(Checks, Ops);
3119 }
3120 
3121 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
3122   {
3123     CodeGenFunction::SanitizerScope SanScope(&CGF);
3124     if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3125          CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3126         Ops.Ty->isIntegerType() &&
3127         (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3128       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3129       EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
3130     } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
3131                Ops.Ty->isRealFloatingType() &&
3132                Ops.mayHaveFloatDivisionByZero()) {
3133       llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3134       llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3135       EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3136                      Ops);
3137     }
3138   }
3139 
3140   if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3141     llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
3142     if (CGF.getLangOpts().OpenCL &&
3143         !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3144       // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3145       // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3146       // build option allows an application to specify that single precision
3147       // floating-point divide (x/y and 1/x) and sqrt used in the program
3148       // source are correctly rounded.
3149       llvm::Type *ValTy = Val->getType();
3150       if (ValTy->isFloatTy() ||
3151           (isa<llvm::VectorType>(ValTy) &&
3152            cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
3153         CGF.SetFPAccuracy(Val, 2.5);
3154     }
3155     return Val;
3156   }
3157   else if (Ops.isFixedPointOp())
3158     return EmitFixedPointBinOp(Ops);
3159   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
3160     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3161   else
3162     return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3163 }
3164 
3165 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3166   // Rem in C can't be a floating point type: C99 6.5.5p2.
3167   if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3168        CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
3169       Ops.Ty->isIntegerType() &&
3170       (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3171     CodeGenFunction::SanitizerScope SanScope(&CGF);
3172     llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3173     EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
3174   }
3175 
3176   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3177     return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3178   else
3179     return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3180 }
3181 
3182 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3183   unsigned IID;
3184   unsigned OpID = 0;
3185 
3186   bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
3187   switch (Ops.Opcode) {
3188   case BO_Add:
3189   case BO_AddAssign:
3190     OpID = 1;
3191     IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3192                      llvm::Intrinsic::uadd_with_overflow;
3193     break;
3194   case BO_Sub:
3195   case BO_SubAssign:
3196     OpID = 2;
3197     IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3198                      llvm::Intrinsic::usub_with_overflow;
3199     break;
3200   case BO_Mul:
3201   case BO_MulAssign:
3202     OpID = 3;
3203     IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3204                      llvm::Intrinsic::umul_with_overflow;
3205     break;
3206   default:
3207     llvm_unreachable("Unsupported operation for overflow detection");
3208   }
3209   OpID <<= 1;
3210   if (isSigned)
3211     OpID |= 1;
3212 
3213   CodeGenFunction::SanitizerScope SanScope(&CGF);
3214   llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
3215 
3216   llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
3217 
3218   Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
3219   Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3220   Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3221 
3222   // Handle overflow with llvm.trap if no custom handler has been specified.
3223   const std::string *handlerName =
3224     &CGF.getLangOpts().OverflowHandler;
3225   if (handlerName->empty()) {
3226     // If the signed-integer-overflow sanitizer is enabled, emit a call to its
3227     // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
3228     if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
3229       llvm::Value *NotOverflow = Builder.CreateNot(overflow);
3230       SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
3231                               : SanitizerKind::UnsignedIntegerOverflow;
3232       EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
3233     } else
3234       CGF.EmitTrapCheck(Builder.CreateNot(overflow));
3235     return result;
3236   }
3237 
3238   // Branch in case of overflow.
3239   llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
3240   llvm::BasicBlock *continueBB =
3241       CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
3242   llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
3243 
3244   Builder.CreateCondBr(overflow, overflowBB, continueBB);
3245 
3246   // If an overflow handler is set, then we want to call it and then use its
3247   // result, if it returns.
3248   Builder.SetInsertPoint(overflowBB);
3249 
3250   // Get the overflow handler.
3251   llvm::Type *Int8Ty = CGF.Int8Ty;
3252   llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
3253   llvm::FunctionType *handlerTy =
3254       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3255   llvm::FunctionCallee handler =
3256       CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3257 
3258   // Sign extend the args to 64-bit, so that we can use the same handler for
3259   // all types of overflow.
3260   llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3261   llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3262 
3263   // Call the handler with the two arguments, the operation, and the size of
3264   // the result.
3265   llvm::Value *handlerArgs[] = {
3266     lhs,
3267     rhs,
3268     Builder.getInt8(OpID),
3269     Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3270   };
3271   llvm::Value *handlerResult =
3272     CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
3273 
3274   // Truncate the result back to the desired size.
3275   handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3276   Builder.CreateBr(continueBB);
3277 
3278   Builder.SetInsertPoint(continueBB);
3279   llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
3280   phi->addIncoming(result, initialBB);
3281   phi->addIncoming(handlerResult, overflowBB);
3282 
3283   return phi;
3284 }
3285 
3286 /// Emit pointer + index arithmetic.
3287 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3288                                     const BinOpInfo &op,
3289                                     bool isSubtraction) {
3290   // Must have binary (not unary) expr here.  Unary pointer
3291   // increment/decrement doesn't use this path.
3292   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3293 
3294   Value *pointer = op.LHS;
3295   Expr *pointerOperand = expr->getLHS();
3296   Value *index = op.RHS;
3297   Expr *indexOperand = expr->getRHS();
3298 
3299   // In a subtraction, the LHS is always the pointer.
3300   if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3301     std::swap(pointer, index);
3302     std::swap(pointerOperand, indexOperand);
3303   }
3304 
3305   bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
3306 
3307   unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
3308   auto &DL = CGF.CGM.getDataLayout();
3309   auto PtrTy = cast<llvm::PointerType>(pointer->getType());
3310 
3311   // Some versions of glibc and gcc use idioms (particularly in their malloc
3312   // routines) that add a pointer-sized integer (known to be a pointer value)
3313   // to a null pointer in order to cast the value back to an integer or as
3314   // part of a pointer alignment algorithm.  This is undefined behavior, but
3315   // we'd like to be able to compile programs that use it.
3316   //
3317   // Normally, we'd generate a GEP with a null-pointer base here in response
3318   // to that code, but it's also UB to dereference a pointer created that
3319   // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
3320   // generate a direct cast of the integer value to a pointer.
3321   //
3322   // The idiom (p = nullptr + N) is not met if any of the following are true:
3323   //
3324   //   The operation is subtraction.
3325   //   The index is not pointer-sized.
3326   //   The pointer type is not byte-sized.
3327   //
3328   if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3329                                                        op.Opcode,
3330                                                        expr->getLHS(),
3331                                                        expr->getRHS()))
3332     return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3333 
3334   if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
3335     // Zero-extend or sign-extend the pointer value according to
3336     // whether the index is signed or not.
3337     index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
3338                                       "idx.ext");
3339   }
3340 
3341   // If this is subtraction, negate the index.
3342   if (isSubtraction)
3343     index = CGF.Builder.CreateNeg(index, "idx.neg");
3344 
3345   if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
3346     CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3347                         /*Accessed*/ false);
3348 
3349   const PointerType *pointerType
3350     = pointerOperand->getType()->getAs<PointerType>();
3351   if (!pointerType) {
3352     QualType objectType = pointerOperand->getType()
3353                                         ->castAs<ObjCObjectPointerType>()
3354                                         ->getPointeeType();
3355     llvm::Value *objectSize
3356       = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3357 
3358     index = CGF.Builder.CreateMul(index, objectSize);
3359 
3360     Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3361     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3362     return CGF.Builder.CreateBitCast(result, pointer->getType());
3363   }
3364 
3365   QualType elementType = pointerType->getPointeeType();
3366   if (const VariableArrayType *vla
3367         = CGF.getContext().getAsVariableArrayType(elementType)) {
3368     // The element count here is the total number of non-VLA elements.
3369     llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
3370 
3371     // Effectively, the multiply by the VLA size is part of the GEP.
3372     // GEP indexes are signed, and scaling an index isn't permitted to
3373     // signed-overflow, so we use the same semantics for our explicit
3374     // multiply.  We suppress this if overflow is not undefined behavior.
3375     if (CGF.getLangOpts().isSignedOverflowDefined()) {
3376       index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3377       pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3378     } else {
3379       index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
3380       pointer =
3381           CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3382                                      op.E->getExprLoc(), "add.ptr");
3383     }
3384     return pointer;
3385   }
3386 
3387   // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3388   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3389   // future proof.
3390   if (elementType->isVoidType() || elementType->isFunctionType()) {
3391     Value *result = CGF.EmitCastToVoidPtr(pointer);
3392     result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3393     return CGF.Builder.CreateBitCast(result, pointer->getType());
3394   }
3395 
3396   if (CGF.getLangOpts().isSignedOverflowDefined())
3397     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3398 
3399   return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
3400                                     op.E->getExprLoc(), "add.ptr");
3401 }
3402 
3403 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3404 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
3405 // the add operand respectively. This allows fmuladd to represent a*b-c, or
3406 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3407 // efficient operations.
3408 static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
3409                            const CodeGenFunction &CGF, CGBuilderTy &Builder,
3410                            bool negMul, bool negAdd) {
3411   assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
3412 
3413   Value *MulOp0 = MulOp->getOperand(0);
3414   Value *MulOp1 = MulOp->getOperand(1);
3415   if (negMul)
3416     MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
3417   if (negAdd)
3418     Addend = Builder.CreateFNeg(Addend, "neg");
3419 
3420   Value *FMulAdd = nullptr;
3421   if (Builder.getIsFPConstrained()) {
3422     assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
3423            "Only constrained operation should be created when Builder is in FP "
3424            "constrained mode");
3425     FMulAdd = Builder.CreateConstrainedFPCall(
3426         CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
3427                              Addend->getType()),
3428         {MulOp0, MulOp1, Addend});
3429   } else {
3430     FMulAdd = Builder.CreateCall(
3431         CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3432         {MulOp0, MulOp1, Addend});
3433   }
3434   MulOp->eraseFromParent();
3435 
3436   return FMulAdd;
3437 }
3438 
3439 // Check whether it would be legal to emit an fmuladd intrinsic call to
3440 // represent op and if so, build the fmuladd.
3441 //
3442 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3443 // Does NOT check the type of the operation - it's assumed that this function
3444 // will be called from contexts where it's known that the type is contractable.
3445 static Value* tryEmitFMulAdd(const BinOpInfo &op,
3446                          const CodeGenFunction &CGF, CGBuilderTy &Builder,
3447                          bool isSub=false) {
3448 
3449   assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3450           op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3451          "Only fadd/fsub can be the root of an fmuladd.");
3452 
3453   // Check whether this op is marked as fusable.
3454   if (!op.FPFeatures.allowFPContractWithinStatement())
3455     return nullptr;
3456 
3457   // We have a potentially fusable op. Look for a mul on one of the operands.
3458   // Also, make sure that the mul result isn't used directly. In that case,
3459   // there's no point creating a muladd operation.
3460   if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3461     if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3462         LHSBinOp->use_empty())
3463       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3464   }
3465   if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3466     if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3467         RHSBinOp->use_empty())
3468       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3469   }
3470 
3471   if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
3472     if (LHSBinOp->getIntrinsicID() ==
3473             llvm::Intrinsic::experimental_constrained_fmul &&
3474         LHSBinOp->use_empty())
3475       return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3476   }
3477   if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
3478     if (RHSBinOp->getIntrinsicID() ==
3479             llvm::Intrinsic::experimental_constrained_fmul &&
3480         RHSBinOp->use_empty())
3481       return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3482   }
3483 
3484   return nullptr;
3485 }
3486 
3487 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3488   if (op.LHS->getType()->isPointerTy() ||
3489       op.RHS->getType()->isPointerTy())
3490     return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
3491 
3492   if (op.Ty->isSignedIntegerOrEnumerationType()) {
3493     switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3494     case LangOptions::SOB_Defined:
3495       return Builder.CreateAdd(op.LHS, op.RHS, "add");
3496     case LangOptions::SOB_Undefined:
3497       if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3498         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3499       LLVM_FALLTHROUGH;
3500     case LangOptions::SOB_Trapping:
3501       if (CanElideOverflowCheck(CGF.getContext(), op))
3502         return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
3503       return EmitOverflowCheckedBinOp(op);
3504     }
3505   }
3506 
3507   if (op.Ty->isUnsignedIntegerType() &&
3508       CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3509       !CanElideOverflowCheck(CGF.getContext(), op))
3510     return EmitOverflowCheckedBinOp(op);
3511 
3512   if (op.LHS->getType()->isFPOrFPVectorTy()) {
3513     // Try to form an fmuladd.
3514     if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3515       return FMulAdd;
3516 
3517     Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
3518     return propagateFMFlags(V, op);
3519   }
3520 
3521   if (op.isFixedPointOp())
3522     return EmitFixedPointBinOp(op);
3523 
3524   return Builder.CreateAdd(op.LHS, op.RHS, "add");
3525 }
3526 
3527 /// The resulting value must be calculated with exact precision, so the operands
3528 /// may not be the same type.
3529 Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
3530   using llvm::APSInt;
3531   using llvm::ConstantInt;
3532 
3533   // This is either a binary operation where at least one of the operands is
3534   // a fixed-point type, or a unary operation where the operand is a fixed-point
3535   // type. The result type of a binary operation is determined by
3536   // Sema::handleFixedPointConversions().
3537   QualType ResultTy = op.Ty;
3538   QualType LHSTy, RHSTy;
3539   if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
3540     RHSTy = BinOp->getRHS()->getType();
3541     if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
3542       // For compound assignment, the effective type of the LHS at this point
3543       // is the computation LHS type, not the actual LHS type, and the final
3544       // result type is not the type of the expression but rather the
3545       // computation result type.
3546       LHSTy = CAO->getComputationLHSType();
3547       ResultTy = CAO->getComputationResultType();
3548     } else
3549       LHSTy = BinOp->getLHS()->getType();
3550   } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
3551     LHSTy = UnOp->getSubExpr()->getType();
3552     RHSTy = UnOp->getSubExpr()->getType();
3553   }
3554   ASTContext &Ctx = CGF.getContext();
3555   Value *LHS = op.LHS;
3556   Value *RHS = op.RHS;
3557 
3558   auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3559   auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3560   auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3561   auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3562 
3563   // Convert the operands to the full precision type.
3564   Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
3565                                             op.E->getExprLoc());
3566   Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
3567                                             op.E->getExprLoc());
3568 
3569   // Perform the actual operation.
3570   Value *Result;
3571   switch (op.Opcode) {
3572   case BO_AddAssign:
3573   case BO_Add: {
3574     if (ResultFixedSema.isSaturated()) {
3575       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3576                                     ? llvm::Intrinsic::sadd_sat
3577                                     : llvm::Intrinsic::uadd_sat;
3578       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3579     } else {
3580       Result = Builder.CreateAdd(FullLHS, FullRHS);
3581     }
3582     break;
3583   }
3584   case BO_SubAssign:
3585   case BO_Sub: {
3586     if (ResultFixedSema.isSaturated()) {
3587       llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3588                                     ? llvm::Intrinsic::ssub_sat
3589                                     : llvm::Intrinsic::usub_sat;
3590       Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3591     } else {
3592       Result = Builder.CreateSub(FullLHS, FullRHS);
3593     }
3594     break;
3595   }
3596   case BO_MulAssign:
3597   case BO_Mul: {
3598     llvm::Intrinsic::ID IID;
3599     if (ResultFixedSema.isSaturated())
3600       IID = ResultFixedSema.isSigned()
3601                 ? llvm::Intrinsic::smul_fix_sat
3602                 : llvm::Intrinsic::umul_fix_sat;
3603     else
3604       IID = ResultFixedSema.isSigned()
3605                 ? llvm::Intrinsic::smul_fix
3606                 : llvm::Intrinsic::umul_fix;
3607     Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3608         {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3609     break;
3610   }
3611   case BO_DivAssign:
3612   case BO_Div: {
3613     llvm::Intrinsic::ID IID;
3614     if (ResultFixedSema.isSaturated())
3615       IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat
3616                                        : llvm::Intrinsic::udiv_fix_sat;
3617     else
3618       IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix
3619                                        : llvm::Intrinsic::udiv_fix;
3620     Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3621         {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3622     break;
3623   }
3624   case BO_LT:
3625     return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
3626                                       : Builder.CreateICmpULT(FullLHS, FullRHS);
3627   case BO_GT:
3628     return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
3629                                       : Builder.CreateICmpUGT(FullLHS, FullRHS);
3630   case BO_LE:
3631     return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
3632                                       : Builder.CreateICmpULE(FullLHS, FullRHS);
3633   case BO_GE:
3634     return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
3635                                       : Builder.CreateICmpUGE(FullLHS, FullRHS);
3636   case BO_EQ:
3637     // For equality operations, we assume any padding bits on unsigned types are
3638     // zero'd out. They could be overwritten through non-saturating operations
3639     // that cause overflow, but this leads to undefined behavior.
3640     return Builder.CreateICmpEQ(FullLHS, FullRHS);
3641   case BO_NE:
3642     return Builder.CreateICmpNE(FullLHS, FullRHS);
3643   case BO_Shl:
3644   case BO_Shr:
3645   case BO_Cmp:
3646   case BO_LAnd:
3647   case BO_LOr:
3648   case BO_ShlAssign:
3649   case BO_ShrAssign:
3650     llvm_unreachable("Found unimplemented fixed point binary operation");
3651   case BO_PtrMemD:
3652   case BO_PtrMemI:
3653   case BO_Rem:
3654   case BO_Xor:
3655   case BO_And:
3656   case BO_Or:
3657   case BO_Assign:
3658   case BO_RemAssign:
3659   case BO_AndAssign:
3660   case BO_XorAssign:
3661   case BO_OrAssign:
3662   case BO_Comma:
3663     llvm_unreachable("Found unsupported binary operation for fixed point types.");
3664   }
3665 
3666   // Convert to the result type.
3667   return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
3668                                   op.E->getExprLoc());
3669 }
3670 
3671 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3672   // The LHS is always a pointer if either side is.
3673   if (!op.LHS->getType()->isPointerTy()) {
3674     if (op.Ty->isSignedIntegerOrEnumerationType()) {
3675       switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
3676       case LangOptions::SOB_Defined:
3677         return Builder.CreateSub(op.LHS, op.RHS, "sub");
3678       case LangOptions::SOB_Undefined:
3679         if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
3680           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3681         LLVM_FALLTHROUGH;
3682       case LangOptions::SOB_Trapping:
3683         if (CanElideOverflowCheck(CGF.getContext(), op))
3684           return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
3685         return EmitOverflowCheckedBinOp(op);
3686       }
3687     }
3688 
3689     if (op.Ty->isUnsignedIntegerType() &&
3690         CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3691         !CanElideOverflowCheck(CGF.getContext(), op))
3692       return EmitOverflowCheckedBinOp(op);
3693 
3694     if (op.LHS->getType()->isFPOrFPVectorTy()) {
3695       // Try to form an fmuladd.
3696       if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3697         return FMulAdd;
3698       Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
3699       return propagateFMFlags(V, op);
3700     }
3701 
3702     if (op.isFixedPointOp())
3703       return EmitFixedPointBinOp(op);
3704 
3705     return Builder.CreateSub(op.LHS, op.RHS, "sub");
3706   }
3707 
3708   // If the RHS is not a pointer, then we have normal pointer
3709   // arithmetic.
3710   if (!op.RHS->getType()->isPointerTy())
3711     return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
3712 
3713   // Otherwise, this is a pointer subtraction.
3714 
3715   // Do the raw subtraction part.
3716   llvm::Value *LHS
3717     = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3718   llvm::Value *RHS
3719     = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3720   Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
3721 
3722   // Okay, figure out the element size.
3723   const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3724   QualType elementType = expr->getLHS()->getType()->getPointeeType();
3725 
3726   llvm::Value *divisor = nullptr;
3727 
3728   // For a variable-length array, this is going to be non-constant.
3729   if (const VariableArrayType *vla
3730         = CGF.getContext().getAsVariableArrayType(elementType)) {
3731     auto VlaSize = CGF.getVLASize(vla);
3732     elementType = VlaSize.Type;
3733     divisor = VlaSize.NumElts;
3734 
3735     // Scale the number of non-VLA elements by the non-VLA element size.
3736     CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3737     if (!eltSize.isOne())
3738       divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3739 
3740   // For everything elese, we can just compute it, safe in the
3741   // assumption that Sema won't let anything through that we can't
3742   // safely compute the size of.
3743   } else {
3744     CharUnits elementSize;
3745     // Handle GCC extension for pointer arithmetic on void* and
3746     // function pointer types.
3747     if (elementType->isVoidType() || elementType->isFunctionType())
3748       elementSize = CharUnits::One();
3749     else
3750       elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3751 
3752     // Don't even emit the divide for element size of 1.
3753     if (elementSize.isOne())
3754       return diffInChars;
3755 
3756     divisor = CGF.CGM.getSize(elementSize);
3757   }
3758 
3759   // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3760   // pointer difference in C is only defined in the case where both operands
3761   // are pointing to elements of an array.
3762   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
3763 }
3764 
3765 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
3766   llvm::IntegerType *Ty;
3767   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3768     Ty = cast<llvm::IntegerType>(VT->getElementType());
3769   else
3770     Ty = cast<llvm::IntegerType>(LHS->getType());
3771   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
3772 }
3773 
3774 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3775   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3776   // RHS to the same size as the LHS.
3777   Value *RHS = Ops.RHS;
3778   if (Ops.LHS->getType() != RHS->getType())
3779     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3780 
3781   bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
3782                       Ops.Ty->hasSignedIntegerRepresentation() &&
3783                       !CGF.getLangOpts().isSignedOverflowDefined() &&
3784                       !CGF.getLangOpts().CPlusPlus2a;
3785   bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3786   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3787   if (CGF.getLangOpts().OpenCL)
3788     RHS =
3789         Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
3790   else if ((SanitizeBase || SanitizeExponent) &&
3791            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3792     CodeGenFunction::SanitizerScope SanScope(&CGF);
3793     SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
3794     llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3795     llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
3796 
3797     if (SanitizeExponent) {
3798       Checks.push_back(
3799           std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3800     }
3801 
3802     if (SanitizeBase) {
3803       // Check whether we are shifting any non-zero bits off the top of the
3804       // integer. We only emit this check if exponent is valid - otherwise
3805       // instructions below will have undefined behavior themselves.
3806       llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3807       llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3808       llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3809       Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
3810       llvm::Value *PromotedWidthMinusOne =
3811           (RHS == Ops.RHS) ? WidthMinusOne
3812                            : GetWidthMinusOneValue(Ops.LHS, RHS);
3813       CGF.EmitBlock(CheckShiftBase);
3814       llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3815           Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3816                                      /*NUW*/ true, /*NSW*/ true),
3817           "shl.check");
3818       if (CGF.getLangOpts().CPlusPlus) {
3819         // In C99, we are not permitted to shift a 1 bit into the sign bit.
3820         // Under C++11's rules, shifting a 1 bit into the sign bit is
3821         // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3822         // define signed left shifts, so we use the C99 and C++11 rules there).
3823         llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3824         BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3825       }
3826       llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
3827       llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
3828       CGF.EmitBlock(Cont);
3829       llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3830       BaseCheck->addIncoming(Builder.getTrue(), Orig);
3831       BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3832       Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
3833     }
3834 
3835     assert(!Checks.empty());
3836     EmitBinOpCheck(Checks, Ops);
3837   }
3838 
3839   return Builder.CreateShl(Ops.LHS, RHS, "shl");
3840 }
3841 
3842 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3843   // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3844   // RHS to the same size as the LHS.
3845   Value *RHS = Ops.RHS;
3846   if (Ops.LHS->getType() != RHS->getType())
3847     RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
3848 
3849   // OpenCL 6.3j: shift values are effectively % word size of LHS.
3850   if (CGF.getLangOpts().OpenCL)
3851     RHS =
3852         Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
3853   else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3854            isa<llvm::IntegerType>(Ops.LHS->getType())) {
3855     CodeGenFunction::SanitizerScope SanScope(&CGF);
3856     llvm::Value *Valid =
3857         Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
3858     EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
3859   }
3860 
3861   if (Ops.Ty->hasUnsignedIntegerRepresentation())
3862     return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3863   return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3864 }
3865 
3866 enum IntrinsicType { VCMPEQ, VCMPGT };
3867 // return corresponding comparison intrinsic for given vector type
3868 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3869                                         BuiltinType::Kind ElemKind) {
3870   switch (ElemKind) {
3871   default: llvm_unreachable("unexpected element type");
3872   case BuiltinType::Char_U:
3873   case BuiltinType::UChar:
3874     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3875                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
3876   case BuiltinType::Char_S:
3877   case BuiltinType::SChar:
3878     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3879                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
3880   case BuiltinType::UShort:
3881     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3882                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
3883   case BuiltinType::Short:
3884     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3885                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
3886   case BuiltinType::UInt:
3887     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3888                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
3889   case BuiltinType::Int:
3890     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3891                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
3892   case BuiltinType::ULong:
3893   case BuiltinType::ULongLong:
3894     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3895                             llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3896   case BuiltinType::Long:
3897   case BuiltinType::LongLong:
3898     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3899                             llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
3900   case BuiltinType::Float:
3901     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3902                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
3903   case BuiltinType::Double:
3904     return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3905                             llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
3906   }
3907 }
3908 
3909 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3910                                       llvm::CmpInst::Predicate UICmpOpc,
3911                                       llvm::CmpInst::Predicate SICmpOpc,
3912                                       llvm::CmpInst::Predicate FCmpOpc,
3913                                       bool IsSignaling) {
3914   TestAndClearIgnoreResultAssign();
3915   Value *Result;
3916   QualType LHSTy = E->getLHS()->getType();
3917   QualType RHSTy = E->getRHS()->getType();
3918   if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
3919     assert(E->getOpcode() == BO_EQ ||
3920            E->getOpcode() == BO_NE);
3921     Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3922     Value *RHS = CGF.EmitScalarExpr(E->getRHS());
3923     Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
3924                    CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
3925   } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
3926     BinOpInfo BOInfo = EmitBinOps(E);
3927     Value *LHS = BOInfo.LHS;
3928     Value *RHS = BOInfo.RHS;
3929 
3930     // If AltiVec, the comparison results in a numeric type, so we use
3931     // intrinsics comparing vectors and giving 0 or 1 as a result
3932     if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
3933       // constants for mapping CR6 register bits to predicate result
3934       enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3935 
3936       llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3937 
3938       // in several cases vector arguments order will be reversed
3939       Value *FirstVecArg = LHS,
3940             *SecondVecArg = RHS;
3941 
3942       QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
3943       BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
3944 
3945       switch(E->getOpcode()) {
3946       default: llvm_unreachable("is not a comparison operation");
3947       case BO_EQ:
3948         CR6 = CR6_LT;
3949         ID = GetIntrinsic(VCMPEQ, ElementKind);
3950         break;
3951       case BO_NE:
3952         CR6 = CR6_EQ;
3953         ID = GetIntrinsic(VCMPEQ, ElementKind);
3954         break;
3955       case BO_LT:
3956         CR6 = CR6_LT;
3957         ID = GetIntrinsic(VCMPGT, ElementKind);
3958         std::swap(FirstVecArg, SecondVecArg);
3959         break;
3960       case BO_GT:
3961         CR6 = CR6_LT;
3962         ID = GetIntrinsic(VCMPGT, ElementKind);
3963         break;
3964       case BO_LE:
3965         if (ElementKind == BuiltinType::Float) {
3966           CR6 = CR6_LT;
3967           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3968           std::swap(FirstVecArg, SecondVecArg);
3969         }
3970         else {
3971           CR6 = CR6_EQ;
3972           ID = GetIntrinsic(VCMPGT, ElementKind);
3973         }
3974         break;
3975       case BO_GE:
3976         if (ElementKind == BuiltinType::Float) {
3977           CR6 = CR6_LT;
3978           ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3979         }
3980         else {
3981           CR6 = CR6_EQ;
3982           ID = GetIntrinsic(VCMPGT, ElementKind);
3983           std::swap(FirstVecArg, SecondVecArg);
3984         }
3985         break;
3986       }
3987 
3988       Value *CR6Param = Builder.getInt32(CR6);
3989       llvm::Function *F = CGF.CGM.getIntrinsic(ID);
3990       Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
3991 
3992       // The result type of intrinsic may not be same as E->getType().
3993       // If E->getType() is not BoolTy, EmitScalarConversion will do the
3994       // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
3995       // do nothing, if ResultTy is not i1 at the same time, it will cause
3996       // crash later.
3997       llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
3998       if (ResultTy->getBitWidth() > 1 &&
3999           E->getType() == CGF.getContext().BoolTy)
4000         Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
4001       return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4002                                   E->getExprLoc());
4003     }
4004 
4005     if (BOInfo.isFixedPointOp()) {
4006       Result = EmitFixedPointBinOp(BOInfo);
4007     } else if (LHS->getType()->isFPOrFPVectorTy()) {
4008       if (!IsSignaling)
4009         Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4010       else
4011         Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
4012     } else if (LHSTy->hasSignedIntegerRepresentation()) {
4013       Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
4014     } else {
4015       // Unsigned integers and pointers.
4016 
4017       if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4018           !isa<llvm::ConstantPointerNull>(LHS) &&
4019           !isa<llvm::ConstantPointerNull>(RHS)) {
4020 
4021         // Dynamic information is required to be stripped for comparisons,
4022         // because it could leak the dynamic information.  Based on comparisons
4023         // of pointers to dynamic objects, the optimizer can replace one pointer
4024         // with another, which might be incorrect in presence of invariant
4025         // groups. Comparison with null is safe because null does not carry any
4026         // dynamic information.
4027         if (LHSTy.mayBeDynamicClass())
4028           LHS = Builder.CreateStripInvariantGroup(LHS);
4029         if (RHSTy.mayBeDynamicClass())
4030           RHS = Builder.CreateStripInvariantGroup(RHS);
4031       }
4032 
4033       Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
4034     }
4035 
4036     // If this is a vector comparison, sign extend the result to the appropriate
4037     // vector integer type and return it (don't convert to bool).
4038     if (LHSTy->isVectorType())
4039       return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
4040 
4041   } else {
4042     // Complex Comparison: can only be an equality comparison.
4043     CodeGenFunction::ComplexPairTy LHS, RHS;
4044     QualType CETy;
4045     if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4046       LHS = CGF.EmitComplexExpr(E->getLHS());
4047       CETy = CTy->getElementType();
4048     } else {
4049       LHS.first = Visit(E->getLHS());
4050       LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4051       CETy = LHSTy;
4052     }
4053     if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4054       RHS = CGF.EmitComplexExpr(E->getRHS());
4055       assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4056                                                      CTy->getElementType()) &&
4057              "The element types must always match.");
4058       (void)CTy;
4059     } else {
4060       RHS.first = Visit(E->getRHS());
4061       RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4062       assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4063              "The element types must always match.");
4064     }
4065 
4066     Value *ResultR, *ResultI;
4067     if (CETy->isRealFloatingType()) {
4068       // As complex comparisons can only be equality comparisons, they
4069       // are never signaling comparisons.
4070       ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4071       ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
4072     } else {
4073       // Complex comparisons can only be equality comparisons.  As such, signed
4074       // and unsigned opcodes are the same.
4075       ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4076       ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
4077     }
4078 
4079     if (E->getOpcode() == BO_EQ) {
4080       Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4081     } else {
4082       assert(E->getOpcode() == BO_NE &&
4083              "Complex comparison other than == or != ?");
4084       Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4085     }
4086   }
4087 
4088   return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4089                               E->getExprLoc());
4090 }
4091 
4092 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
4093   bool Ignore = TestAndClearIgnoreResultAssign();
4094 
4095   Value *RHS;
4096   LValue LHS;
4097 
4098   switch (E->getLHS()->getType().getObjCLifetime()) {
4099   case Qualifiers::OCL_Strong:
4100     std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
4101     break;
4102 
4103   case Qualifiers::OCL_Autoreleasing:
4104     std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
4105     break;
4106 
4107   case Qualifiers::OCL_ExplicitNone:
4108     std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4109     break;
4110 
4111   case Qualifiers::OCL_Weak:
4112     RHS = Visit(E->getRHS());
4113     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4114     RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
4115     break;
4116 
4117   case Qualifiers::OCL_None:
4118     // __block variables need to have the rhs evaluated first, plus
4119     // this should improve codegen just a little.
4120     RHS = Visit(E->getRHS());
4121     LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
4122 
4123     // Store the value into the LHS.  Bit-fields are handled specially
4124     // because the result is altered by the store, i.e., [C99 6.5.16p1]
4125     // 'An assignment expression has the value of the left operand after
4126     // the assignment...'.
4127     if (LHS.isBitField()) {
4128       CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
4129     } else {
4130       CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
4131       CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
4132     }
4133   }
4134 
4135   // If the result is clearly ignored, return now.
4136   if (Ignore)
4137     return nullptr;
4138 
4139   // The result of an assignment in C is the assigned r-value.
4140   if (!CGF.getLangOpts().CPlusPlus)
4141     return RHS;
4142 
4143   // If the lvalue is non-volatile, return the computed value of the assignment.
4144   if (!LHS.isVolatileQualified())
4145     return RHS;
4146 
4147   // Otherwise, reload the value.
4148   return EmitLoadOfLValue(LHS, E->getExprLoc());
4149 }
4150 
4151 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
4152   // Perform vector logical and on comparisons with zero vectors.
4153   if (E->getType()->isVectorType()) {
4154     CGF.incrementProfileCounter(E);
4155 
4156     Value *LHS = Visit(E->getLHS());
4157     Value *RHS = Visit(E->getRHS());
4158     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4159     if (LHS->getType()->isFPOrFPVectorTy()) {
4160       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4161       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4162     } else {
4163       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4164       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4165     }
4166     Value *And = Builder.CreateAnd(LHS, RHS);
4167     return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
4168   }
4169 
4170   llvm::Type *ResTy = ConvertType(E->getType());
4171 
4172   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4173   // If we have 1 && X, just emit X without inserting the control flow.
4174   bool LHSCondVal;
4175   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4176     if (LHSCondVal) { // If we have 1 && X, just emit X.
4177       CGF.incrementProfileCounter(E);
4178 
4179       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4180       // ZExt result to int or bool.
4181       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
4182     }
4183 
4184     // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
4185     if (!CGF.ContainsLabel(E->getRHS()))
4186       return llvm::Constant::getNullValue(ResTy);
4187   }
4188 
4189   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
4190   llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
4191 
4192   CodeGenFunction::ConditionalEvaluation eval(CGF);
4193 
4194   // Branch on the LHS first.  If it is false, go to the failure (cont) block.
4195   CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4196                            CGF.getProfileCount(E->getRHS()));
4197 
4198   // Any edges into the ContBlock are now from an (indeterminate number of)
4199   // edges from this first condition.  All of these values will be false.  Start
4200   // setting up the PHI node in the Cont Block for this.
4201   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4202                                             "", ContBlock);
4203   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4204        PI != PE; ++PI)
4205     PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
4206 
4207   eval.begin(CGF);
4208   CGF.EmitBlock(RHSBlock);
4209   CGF.incrementProfileCounter(E);
4210   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4211   eval.end(CGF);
4212 
4213   // Reaquire the RHS block, as there may be subblocks inserted.
4214   RHSBlock = Builder.GetInsertBlock();
4215 
4216   // Emit an unconditional branch from this block to ContBlock.
4217   {
4218     // There is no need to emit line number for unconditional branch.
4219     auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4220     CGF.EmitBlock(ContBlock);
4221   }
4222   // Insert an entry into the phi node for the edge with the value of RHSCond.
4223   PN->addIncoming(RHSCond, RHSBlock);
4224 
4225   // Artificial location to preserve the scope information
4226   {
4227     auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4228     PN->setDebugLoc(Builder.getCurrentDebugLocation());
4229   }
4230 
4231   // ZExt result to int.
4232   return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
4233 }
4234 
4235 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
4236   // Perform vector logical or on comparisons with zero vectors.
4237   if (E->getType()->isVectorType()) {
4238     CGF.incrementProfileCounter(E);
4239 
4240     Value *LHS = Visit(E->getLHS());
4241     Value *RHS = Visit(E->getRHS());
4242     Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
4243     if (LHS->getType()->isFPOrFPVectorTy()) {
4244       LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4245       RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4246     } else {
4247       LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4248       RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4249     }
4250     Value *Or = Builder.CreateOr(LHS, RHS);
4251     return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
4252   }
4253 
4254   llvm::Type *ResTy = ConvertType(E->getType());
4255 
4256   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4257   // If we have 0 || X, just emit X without inserting the control flow.
4258   bool LHSCondVal;
4259   if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4260     if (!LHSCondVal) { // If we have 0 || X, just emit X.
4261       CGF.incrementProfileCounter(E);
4262 
4263       Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4264       // ZExt result to int or bool.
4265       return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
4266     }
4267 
4268     // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
4269     if (!CGF.ContainsLabel(E->getRHS()))
4270       return llvm::ConstantInt::get(ResTy, 1);
4271   }
4272 
4273   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4274   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
4275 
4276   CodeGenFunction::ConditionalEvaluation eval(CGF);
4277 
4278   // Branch on the LHS first.  If it is true, go to the success (cont) block.
4279   CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
4280                            CGF.getCurrentProfileCount() -
4281                                CGF.getProfileCount(E->getRHS()));
4282 
4283   // Any edges into the ContBlock are now from an (indeterminate number of)
4284   // edges from this first condition.  All of these values will be true.  Start
4285   // setting up the PHI node in the Cont Block for this.
4286   llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
4287                                             "", ContBlock);
4288   for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4289        PI != PE; ++PI)
4290     PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
4291 
4292   eval.begin(CGF);
4293 
4294   // Emit the RHS condition as a bool value.
4295   CGF.EmitBlock(RHSBlock);
4296   CGF.incrementProfileCounter(E);
4297   Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
4298 
4299   eval.end(CGF);
4300 
4301   // Reaquire the RHS block, as there may be subblocks inserted.
4302   RHSBlock = Builder.GetInsertBlock();
4303 
4304   // Emit an unconditional branch from this block to ContBlock.  Insert an entry
4305   // into the phi node for the edge with the value of RHSCond.
4306   CGF.EmitBlock(ContBlock);
4307   PN->addIncoming(RHSCond, RHSBlock);
4308 
4309   // ZExt result to int.
4310   return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
4311 }
4312 
4313 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
4314   CGF.EmitIgnoredExpr(E->getLHS());
4315   CGF.EnsureInsertPoint();
4316   return Visit(E->getRHS());
4317 }
4318 
4319 //===----------------------------------------------------------------------===//
4320 //                             Other Operators
4321 //===----------------------------------------------------------------------===//
4322 
4323 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4324 /// expression is cheap enough and side-effect-free enough to evaluate
4325 /// unconditionally instead of conditionally.  This is used to convert control
4326 /// flow into selects in some cases.
4327 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4328                                                    CodeGenFunction &CGF) {
4329   // Anything that is an integer or floating point constant is fine.
4330   return E->IgnoreParens()->isEvaluatable(CGF.getContext());
4331 
4332   // Even non-volatile automatic variables can't be evaluated unconditionally.
4333   // Referencing a thread_local may cause non-trivial initialization work to
4334   // occur. If we're inside a lambda and one of the variables is from the scope
4335   // outside the lambda, that function may have returned already. Reading its
4336   // locals is a bad idea. Also, these reads may introduce races there didn't
4337   // exist in the source-level program.
4338 }
4339 
4340 
4341 Value *ScalarExprEmitter::
4342 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
4343   TestAndClearIgnoreResultAssign();
4344 
4345   // Bind the common expression if necessary.
4346   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
4347 
4348   Expr *condExpr = E->getCond();
4349   Expr *lhsExpr = E->getTrueExpr();
4350   Expr *rhsExpr = E->getFalseExpr();
4351 
4352   // If the condition constant folds and can be elided, try to avoid emitting
4353   // the condition and the dead arm.
4354   bool CondExprBool;
4355   if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4356     Expr *live = lhsExpr, *dead = rhsExpr;
4357     if (!CondExprBool) std::swap(live, dead);
4358 
4359     // If the dead side doesn't have labels we need, just emit the Live part.
4360     if (!CGF.ContainsLabel(dead)) {
4361       if (CondExprBool)
4362         CGF.incrementProfileCounter(E);
4363       Value *Result = Visit(live);
4364 
4365       // If the live part is a throw expression, it acts like it has a void
4366       // type, so evaluating it returns a null Value*.  However, a conditional
4367       // with non-void type must return a non-null Value*.
4368       if (!Result && !E->getType()->isVoidType())
4369         Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4370 
4371       return Result;
4372     }
4373   }
4374 
4375   // OpenCL: If the condition is a vector, we can treat this condition like
4376   // the select function.
4377   if (CGF.getLangOpts().OpenCL
4378       && condExpr->getType()->isVectorType()) {
4379     CGF.incrementProfileCounter(E);
4380 
4381     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4382     llvm::Value *LHS = Visit(lhsExpr);
4383     llvm::Value *RHS = Visit(rhsExpr);
4384 
4385     llvm::Type *condType = ConvertType(condExpr->getType());
4386     llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
4387 
4388     unsigned numElem = vecTy->getNumElements();
4389     llvm::Type *elemType = vecTy->getElementType();
4390 
4391     llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
4392     llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
4393     llvm::Value *tmp = Builder.CreateSExt(TestMSB,
4394                                           llvm::VectorType::get(elemType,
4395                                                                 numElem),
4396                                           "sext");
4397     llvm::Value *tmp2 = Builder.CreateNot(tmp);
4398 
4399     // Cast float to int to perform ANDs if necessary.
4400     llvm::Value *RHSTmp = RHS;
4401     llvm::Value *LHSTmp = LHS;
4402     bool wasCast = false;
4403     llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
4404     if (rhsVTy->getElementType()->isFloatingPointTy()) {
4405       RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4406       LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4407       wasCast = true;
4408     }
4409 
4410     llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4411     llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4412     llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4413     if (wasCast)
4414       tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4415 
4416     return tmp5;
4417   }
4418 
4419   if (condExpr->getType()->isVectorType()) {
4420     CGF.incrementProfileCounter(E);
4421 
4422     llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4423     llvm::Value *LHS = Visit(lhsExpr);
4424     llvm::Value *RHS = Visit(rhsExpr);
4425 
4426     llvm::Type *CondType = ConvertType(condExpr->getType());
4427     auto *VecTy = cast<llvm::VectorType>(CondType);
4428     llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
4429 
4430     CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
4431     return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
4432   }
4433 
4434   // If this is a really simple expression (like x ? 4 : 5), emit this as a
4435   // select instead of as control flow.  We can only do this if it is cheap and
4436   // safe to evaluate the LHS and RHS unconditionally.
4437   if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4438       isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4439     llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
4440     llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4441 
4442     CGF.incrementProfileCounter(E, StepV);
4443 
4444     llvm::Value *LHS = Visit(lhsExpr);
4445     llvm::Value *RHS = Visit(rhsExpr);
4446     if (!LHS) {
4447       // If the conditional has void type, make sure we return a null Value*.
4448       assert(!RHS && "LHS and RHS types must match");
4449       return nullptr;
4450     }
4451     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4452   }
4453 
4454   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4455   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
4456   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4457 
4458   CodeGenFunction::ConditionalEvaluation eval(CGF);
4459   CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4460                            CGF.getProfileCount(lhsExpr));
4461 
4462   CGF.EmitBlock(LHSBlock);
4463   CGF.incrementProfileCounter(E);
4464   eval.begin(CGF);
4465   Value *LHS = Visit(lhsExpr);
4466   eval.end(CGF);
4467 
4468   LHSBlock = Builder.GetInsertBlock();
4469   Builder.CreateBr(ContBlock);
4470 
4471   CGF.EmitBlock(RHSBlock);
4472   eval.begin(CGF);
4473   Value *RHS = Visit(rhsExpr);
4474   eval.end(CGF);
4475 
4476   RHSBlock = Builder.GetInsertBlock();
4477   CGF.EmitBlock(ContBlock);
4478 
4479   // If the LHS or RHS is a throw expression, it will be legitimately null.
4480   if (!LHS)
4481     return RHS;
4482   if (!RHS)
4483     return LHS;
4484 
4485   // Create a PHI node for the real part.
4486   llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
4487   PN->addIncoming(LHS, LHSBlock);
4488   PN->addIncoming(RHS, RHSBlock);
4489   return PN;
4490 }
4491 
4492 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
4493   return Visit(E->getChosenSubExpr());
4494 }
4495 
4496 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
4497   QualType Ty = VE->getType();
4498 
4499   if (Ty->isVariablyModifiedType())
4500     CGF.EmitVariablyModifiedType(Ty);
4501 
4502   Address ArgValue = Address::invalid();
4503   Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4504 
4505   llvm::Type *ArgTy = ConvertType(VE->getType());
4506 
4507   // If EmitVAArg fails, emit an error.
4508   if (!ArgPtr.isValid()) {
4509     CGF.ErrorUnsupported(VE, "va_arg expression");
4510     return llvm::UndefValue::get(ArgTy);
4511   }
4512 
4513   // FIXME Volatility.
4514   llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4515 
4516   // If EmitVAArg promoted the type, we must truncate it.
4517   if (ArgTy != Val->getType()) {
4518     if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4519       Val = Builder.CreateIntToPtr(Val, ArgTy);
4520     else
4521       Val = Builder.CreateTrunc(Val, ArgTy);
4522   }
4523 
4524   return Val;
4525 }
4526 
4527 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4528   return CGF.EmitBlockLiteral(block);
4529 }
4530 
4531 // Convert a vec3 to vec4, or vice versa.
4532 static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4533                                  Value *Src, unsigned NumElementsDst) {
4534   llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
4535   SmallVector<llvm::Constant*, 4> Args;
4536   Args.push_back(Builder.getInt32(0));
4537   Args.push_back(Builder.getInt32(1));
4538   Args.push_back(Builder.getInt32(2));
4539   if (NumElementsDst == 4)
4540     Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
4541   llvm::Constant *Mask = llvm::ConstantVector::get(Args);
4542   return Builder.CreateShuffleVector(Src, UnV, Mask);
4543 }
4544 
4545 // Create cast instructions for converting LLVM value \p Src to LLVM type \p
4546 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
4547 // but could be scalar or vectors of different lengths, and either can be
4548 // pointer.
4549 // There are 4 cases:
4550 // 1. non-pointer -> non-pointer  : needs 1 bitcast
4551 // 2. pointer -> pointer          : needs 1 bitcast or addrspacecast
4552 // 3. pointer -> non-pointer
4553 //   a) pointer -> intptr_t       : needs 1 ptrtoint
4554 //   b) pointer -> non-intptr_t   : needs 1 ptrtoint then 1 bitcast
4555 // 4. non-pointer -> pointer
4556 //   a) intptr_t -> pointer       : needs 1 inttoptr
4557 //   b) non-intptr_t -> pointer   : needs 1 bitcast then 1 inttoptr
4558 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
4559 // allow casting directly between pointer types and non-integer non-pointer
4560 // types.
4561 static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4562                                            const llvm::DataLayout &DL,
4563                                            Value *Src, llvm::Type *DstTy,
4564                                            StringRef Name = "") {
4565   auto SrcTy = Src->getType();
4566 
4567   // Case 1.
4568   if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4569     return Builder.CreateBitCast(Src, DstTy, Name);
4570 
4571   // Case 2.
4572   if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4573     return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4574 
4575   // Case 3.
4576   if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4577     // Case 3b.
4578     if (!DstTy->isIntegerTy())
4579       Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4580     // Cases 3a and 3b.
4581     return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4582   }
4583 
4584   // Case 4b.
4585   if (!SrcTy->isIntegerTy())
4586     Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4587   // Cases 4a and 4b.
4588   return Builder.CreateIntToPtr(Src, DstTy, Name);
4589 }
4590 
4591 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4592   Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
4593   llvm::Type *DstTy = ConvertType(E->getType());
4594 
4595   llvm::Type *SrcTy = Src->getType();
4596   unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4597     cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4598   unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4599     cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
4600 
4601   // Going from vec3 to non-vec3 is a special case and requires a shuffle
4602   // vector to get a vec4, then a bitcast if the target type is different.
4603   if (NumElementsSrc == 3 && NumElementsDst != 3) {
4604     Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
4605 
4606     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4607       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4608                                          DstTy);
4609     }
4610 
4611     Src->setName("astype");
4612     return Src;
4613   }
4614 
4615   // Going from non-vec3 to vec3 is a special case and requires a bitcast
4616   // to vec4 if the original type is not vec4, then a shuffle vector to
4617   // get a vec3.
4618   if (NumElementsSrc != 3 && NumElementsDst == 3) {
4619     if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4620       auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
4621       Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4622                                          Vec4Ty);
4623     }
4624 
4625     Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4626     Src->setName("astype");
4627     return Src;
4628   }
4629 
4630   return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4631                                       Src, DstTy, "astype");
4632 }
4633 
4634 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4635   return CGF.EmitAtomicExpr(E).getScalarVal();
4636 }
4637 
4638 //===----------------------------------------------------------------------===//
4639 //                         Entry Point into this File
4640 //===----------------------------------------------------------------------===//
4641 
4642 /// Emit the computation of the specified expression of scalar type, ignoring
4643 /// the result.
4644 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
4645   assert(E && hasScalarEvaluationKind(E->getType()) &&
4646          "Invalid scalar expression to emit");
4647 
4648   return ScalarExprEmitter(*this, IgnoreResultAssign)
4649       .Visit(const_cast<Expr *>(E));
4650 }
4651 
4652 /// Emit a conversion from the specified type to the specified destination type,
4653 /// both of which are LLVM scalar types.
4654 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
4655                                              QualType DstTy,
4656                                              SourceLocation Loc) {
4657   assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
4658          "Invalid scalar expression to emit");
4659   return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
4660 }
4661 
4662 /// Emit a conversion from the specified complex type to the specified
4663 /// destination type, where the destination type is an LLVM scalar type.
4664 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4665                                                       QualType SrcTy,
4666                                                       QualType DstTy,
4667                                                       SourceLocation Loc) {
4668   assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
4669          "Invalid complex -> scalar conversion");
4670   return ScalarExprEmitter(*this)
4671       .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
4672 }
4673 
4674 
4675 llvm::Value *CodeGenFunction::
4676 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4677                         bool isInc, bool isPre) {
4678   return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4679 }
4680 
4681 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
4682   // object->isa or (*object).isa
4683   // Generate code as for: *(Class*)object
4684 
4685   Expr *BaseExpr = E->getBase();
4686   Address Addr = Address::invalid();
4687   if (BaseExpr->isRValue()) {
4688     Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
4689   } else {
4690     Addr = EmitLValue(BaseExpr).getAddress(*this);
4691   }
4692 
4693   // Cast the address to Class*.
4694   Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4695   return MakeAddrLValue(Addr, E->getType());
4696 }
4697 
4698 
4699 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
4700                                             const CompoundAssignOperator *E) {
4701   ScalarExprEmitter Scalar(*this);
4702   Value *Result = nullptr;
4703   switch (E->getOpcode()) {
4704 #define COMPOUND_OP(Op)                                                       \
4705     case BO_##Op##Assign:                                                     \
4706       return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
4707                                              Result)
4708   COMPOUND_OP(Mul);
4709   COMPOUND_OP(Div);
4710   COMPOUND_OP(Rem);
4711   COMPOUND_OP(Add);
4712   COMPOUND_OP(Sub);
4713   COMPOUND_OP(Shl);
4714   COMPOUND_OP(Shr);
4715   COMPOUND_OP(And);
4716   COMPOUND_OP(Xor);
4717   COMPOUND_OP(Or);
4718 #undef COMPOUND_OP
4719 
4720   case BO_PtrMemD:
4721   case BO_PtrMemI:
4722   case BO_Mul:
4723   case BO_Div:
4724   case BO_Rem:
4725   case BO_Add:
4726   case BO_Sub:
4727   case BO_Shl:
4728   case BO_Shr:
4729   case BO_LT:
4730   case BO_GT:
4731   case BO_LE:
4732   case BO_GE:
4733   case BO_EQ:
4734   case BO_NE:
4735   case BO_Cmp:
4736   case BO_And:
4737   case BO_Xor:
4738   case BO_Or:
4739   case BO_LAnd:
4740   case BO_LOr:
4741   case BO_Assign:
4742   case BO_Comma:
4743     llvm_unreachable("Not valid compound assignment operators");
4744   }
4745 
4746   llvm_unreachable("Unhandled compound assignment operator");
4747 }
4748 
4749 struct GEPOffsetAndOverflow {
4750   // The total (signed) byte offset for the GEP.
4751   llvm::Value *TotalOffset;
4752   // The offset overflow flag - true if the total offset overflows.
4753   llvm::Value *OffsetOverflows;
4754 };
4755 
4756 /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
4757 /// and compute the total offset it applies from it's base pointer BasePtr.
4758 /// Returns offset in bytes and a boolean flag whether an overflow happened
4759 /// during evaluation.
4760 static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4761                                                  llvm::LLVMContext &VMContext,
4762                                                  CodeGenModule &CGM,
4763                                                  CGBuilderTy &Builder) {
4764   const auto &DL = CGM.getDataLayout();
4765 
4766   // The total (signed) byte offset for the GEP.
4767   llvm::Value *TotalOffset = nullptr;
4768 
4769   // Was the GEP already reduced to a constant?
4770   if (isa<llvm::Constant>(GEPVal)) {
4771     // Compute the offset by casting both pointers to integers and subtracting:
4772     // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4773     Value *BasePtr_int =
4774         Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4775     Value *GEPVal_int =
4776         Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4777     TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4778     return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4779   }
4780 
4781   auto *GEP = cast<llvm::GEPOperator>(GEPVal);
4782   assert(GEP->getPointerOperand() == BasePtr &&
4783          "BasePtr must be the the base of the GEP.");
4784   assert(GEP->isInBounds() && "Expected inbounds GEP");
4785 
4786   auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4787 
4788   // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4789   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4790   auto *SAddIntrinsic =
4791       CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4792   auto *SMulIntrinsic =
4793       CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4794 
4795   // The offset overflow flag - true if the total offset overflows.
4796   llvm::Value *OffsetOverflows = Builder.getFalse();
4797 
4798   /// Return the result of the given binary operation.
4799   auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4800                   llvm::Value *RHS) -> llvm::Value * {
4801     assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
4802 
4803     // If the operands are constants, return a constant result.
4804     if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4805       if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4806         llvm::APInt N;
4807         bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4808                                                   /*Signed=*/true, N);
4809         if (HasOverflow)
4810           OffsetOverflows = Builder.getTrue();
4811         return llvm::ConstantInt::get(VMContext, N);
4812       }
4813     }
4814 
4815     // Otherwise, compute the result with checked arithmetic.
4816     auto *ResultAndOverflow = Builder.CreateCall(
4817         (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4818     OffsetOverflows = Builder.CreateOr(
4819         Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
4820     return Builder.CreateExtractValue(ResultAndOverflow, 0);
4821   };
4822 
4823   // Determine the total byte offset by looking at each GEP operand.
4824   for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4825        GTI != GTE; ++GTI) {
4826     llvm::Value *LocalOffset;
4827     auto *Index = GTI.getOperand();
4828     // Compute the local offset contributed by this indexing step:
4829     if (auto *STy = GTI.getStructTypeOrNull()) {
4830       // For struct indexing, the local offset is the byte position of the
4831       // specified field.
4832       unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4833       LocalOffset = llvm::ConstantInt::get(
4834           IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4835     } else {
4836       // Otherwise this is array-like indexing. The local offset is the index
4837       // multiplied by the element size.
4838       auto *ElementSize = llvm::ConstantInt::get(
4839           IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4840       auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4841       LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4842     }
4843 
4844     // If this is the first offset, set it as the total offset. Otherwise, add
4845     // the local offset into the running total.
4846     if (!TotalOffset || TotalOffset == Zero)
4847       TotalOffset = LocalOffset;
4848     else
4849       TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4850   }
4851 
4852   return {TotalOffset, OffsetOverflows};
4853 }
4854 
4855 Value *
4856 CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
4857                                         bool SignedIndices, bool IsSubtraction,
4858                                         SourceLocation Loc, const Twine &Name) {
4859   Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4860 
4861   // If the pointer overflow sanitizer isn't enabled, do nothing.
4862   if (!SanOpts.has(SanitizerKind::PointerOverflow))
4863     return GEPVal;
4864 
4865   llvm::Type *PtrTy = Ptr->getType();
4866 
4867   // Perform nullptr-and-offset check unless the nullptr is defined.
4868   bool PerformNullCheck = !NullPointerIsDefined(
4869       Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
4870   // Check for overflows unless the GEP got constant-folded,
4871   // and only in the default address space
4872   bool PerformOverflowCheck =
4873       !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
4874 
4875   if (!(PerformNullCheck || PerformOverflowCheck))
4876     return GEPVal;
4877 
4878   const auto &DL = CGM.getDataLayout();
4879 
4880   SanitizerScope SanScope(this);
4881   llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4882 
4883   GEPOffsetAndOverflow EvaluatedGEP =
4884       EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
4885 
4886   assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
4887           EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
4888          "If the offset got constant-folded, we don't expect that there was an "
4889          "overflow.");
4890 
4891   auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4892 
4893   // Common case: if the total offset is zero, and we are using C++ semantics,
4894   // where nullptr+0 is defined, don't emit a check.
4895   if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
4896     return GEPVal;
4897 
4898   // Now that we've computed the total offset, add it to the base pointer (with
4899   // wrapping semantics).
4900   auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
4901   auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
4902 
4903   llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
4904 
4905   if (PerformNullCheck) {
4906     // In C++, if the base pointer evaluates to a null pointer value,
4907     // the only valid  pointer this inbounds GEP can produce is also
4908     // a null pointer, so the offset must also evaluate to zero.
4909     // Likewise, if we have non-zero base pointer, we can not get null pointer
4910     // as a result, so the offset can not be -intptr_t(BasePtr).
4911     // In other words, both pointers are either null, or both are non-null,
4912     // or the behaviour is undefined.
4913     //
4914     // C, however, is more strict in this regard, and gives more
4915     // optimization opportunities: in C, additionally, nullptr+0 is undefined.
4916     // So both the input to the 'gep inbounds' AND the output must not be null.
4917     auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
4918     auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
4919     auto *Valid =
4920         CGM.getLangOpts().CPlusPlus
4921             ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
4922             : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
4923     Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
4924   }
4925 
4926   if (PerformOverflowCheck) {
4927     // The GEP is valid if:
4928     // 1) The total offset doesn't overflow, and
4929     // 2) The sign of the difference between the computed address and the base
4930     // pointer matches the sign of the total offset.
4931     llvm::Value *ValidGEP;
4932     auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
4933     if (SignedIndices) {
4934       // GEP is computed as `unsigned base + signed offset`, therefore:
4935       // * If offset was positive, then the computed pointer can not be
4936       //   [unsigned] less than the base pointer, unless it overflowed.
4937       // * If offset was negative, then the computed pointer can not be
4938       //   [unsigned] greater than the bas pointere, unless it overflowed.
4939       auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4940       auto *PosOrZeroOffset =
4941           Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
4942       llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
4943       ValidGEP =
4944           Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
4945     } else if (!IsSubtraction) {
4946       // GEP is computed as `unsigned base + unsigned offset`,  therefore the
4947       // computed pointer can not be [unsigned] less than base pointer,
4948       // unless there was an overflow.
4949       // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
4950       ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4951     } else {
4952       // GEP is computed as `unsigned base - unsigned offset`, therefore the
4953       // computed pointer can not be [unsigned] greater than base pointer,
4954       // unless there was an overflow.
4955       // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
4956       ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
4957     }
4958     ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
4959     Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
4960   }
4961 
4962   assert(!Checks.empty() && "Should have produced some checks.");
4963 
4964   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
4965   // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
4966   llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4967   EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
4968 
4969   return GEPVal;
4970 }
4971