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