clang API Documentation

CGExpr.cpp
Go to the documentation of this file.
00001 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code to emit Expr nodes as LLVM code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CGCXXABI.h"
00016 #include "CGCall.h"
00017 #include "CGDebugInfo.h"
00018 #include "CGObjCRuntime.h"
00019 #include "CGOpenMPRuntime.h"
00020 #include "CGRecordLayout.h"
00021 #include "CodeGenModule.h"
00022 #include "TargetInfo.h"
00023 #include "clang/AST/ASTContext.h"
00024 #include "clang/AST/DeclObjC.h"
00025 #include "clang/AST/Attr.h"
00026 #include "clang/Frontend/CodeGenOptions.h"
00027 #include "llvm/ADT/Hashing.h"
00028 #include "llvm/ADT/StringExtras.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/Intrinsics.h"
00031 #include "llvm/IR/LLVMContext.h"
00032 #include "llvm/IR/MDBuilder.h"
00033 #include "llvm/Support/ConvertUTF.h"
00034 
00035 using namespace clang;
00036 using namespace CodeGen;
00037 
00038 //===--------------------------------------------------------------------===//
00039 //                        Miscellaneous Helper Methods
00040 //===--------------------------------------------------------------------===//
00041 
00042 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
00043   unsigned addressSpace =
00044     cast<llvm::PointerType>(value->getType())->getAddressSpace();
00045 
00046   llvm::PointerType *destType = Int8PtrTy;
00047   if (addressSpace)
00048     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
00049 
00050   if (value->getType() == destType) return value;
00051   return Builder.CreateBitCast(value, destType);
00052 }
00053 
00054 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
00055 /// block.
00056 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
00057                                                     const Twine &Name) {
00058   if (!Builder.isNamePreserving())
00059     return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
00060   return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
00061 }
00062 
00063 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
00064                                      llvm::Value *Init) {
00065   auto *Store = new llvm::StoreInst(Init, Var);
00066   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
00067   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
00068 }
00069 
00070 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
00071                                                 const Twine &Name) {
00072   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
00073   // FIXME: Should we prefer the preferred type alignment here?
00074   CharUnits Align = getContext().getTypeAlignInChars(Ty);
00075   Alloc->setAlignment(Align.getQuantity());
00076   return Alloc;
00077 }
00078 
00079 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
00080                                                  const Twine &Name) {
00081   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
00082   // FIXME: Should we prefer the preferred type alignment here?
00083   CharUnits Align = getContext().getTypeAlignInChars(Ty);
00084   Alloc->setAlignment(Align.getQuantity());
00085   return Alloc;
00086 }
00087 
00088 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
00089 /// expression and compare the result against zero, returning an Int1Ty value.
00090 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
00091   PGO.setCurrentStmt(E);
00092   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
00093     llvm::Value *MemPtr = EmitScalarExpr(E);
00094     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
00095   }
00096 
00097   QualType BoolTy = getContext().BoolTy;
00098   if (!E->getType()->isAnyComplexType())
00099     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
00100 
00101   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
00102 }
00103 
00104 /// EmitIgnoredExpr - Emit code to compute the specified expression,
00105 /// ignoring the result.
00106 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
00107   if (E->isRValue())
00108     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
00109 
00110   // Just emit it as an l-value and drop the result.
00111   EmitLValue(E);
00112 }
00113 
00114 /// EmitAnyExpr - Emit code to compute the specified expression which
00115 /// can have any type.  The result is returned as an RValue struct.
00116 /// If this is an aggregate expression, AggSlot indicates where the
00117 /// result should be returned.
00118 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
00119                                     AggValueSlot aggSlot,
00120                                     bool ignoreResult) {
00121   switch (getEvaluationKind(E->getType())) {
00122   case TEK_Scalar:
00123     return RValue::get(EmitScalarExpr(E, ignoreResult));
00124   case TEK_Complex:
00125     return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
00126   case TEK_Aggregate:
00127     if (!ignoreResult && aggSlot.isIgnored())
00128       aggSlot = CreateAggTemp(E->getType(), "agg-temp");
00129     EmitAggExpr(E, aggSlot);
00130     return aggSlot.asRValue();
00131   }
00132   llvm_unreachable("bad evaluation kind");
00133 }
00134 
00135 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
00136 /// always be accessible even if no aggregate location is provided.
00137 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
00138   AggValueSlot AggSlot = AggValueSlot::ignored();
00139 
00140   if (hasAggregateEvaluationKind(E->getType()))
00141     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
00142   return EmitAnyExpr(E, AggSlot);
00143 }
00144 
00145 /// EmitAnyExprToMem - Evaluate an expression into a given memory
00146 /// location.
00147 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
00148                                        llvm::Value *Location,
00149                                        Qualifiers Quals,
00150                                        bool IsInit) {
00151   // FIXME: This function should take an LValue as an argument.
00152   switch (getEvaluationKind(E->getType())) {
00153   case TEK_Complex:
00154     EmitComplexExprIntoLValue(E,
00155                          MakeNaturalAlignAddrLValue(Location, E->getType()),
00156                               /*isInit*/ false);
00157     return;
00158 
00159   case TEK_Aggregate: {
00160     CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
00161     EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
00162                                          AggValueSlot::IsDestructed_t(IsInit),
00163                                          AggValueSlot::DoesNotNeedGCBarriers,
00164                                          AggValueSlot::IsAliased_t(!IsInit)));
00165     return;
00166   }
00167 
00168   case TEK_Scalar: {
00169     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
00170     LValue LV = MakeAddrLValue(Location, E->getType());
00171     EmitStoreThroughLValue(RV, LV);
00172     return;
00173   }
00174   }
00175   llvm_unreachable("bad evaluation kind");
00176 }
00177 
00178 static void
00179 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
00180                      const Expr *E, llvm::Value *ReferenceTemporary) {
00181   // Objective-C++ ARC:
00182   //   If we are binding a reference to a temporary that has ownership, we
00183   //   need to perform retain/release operations on the temporary.
00184   //
00185   // FIXME: This should be looking at E, not M.
00186   if (CGF.getLangOpts().ObjCAutoRefCount &&
00187       M->getType()->isObjCLifetimeType()) {
00188     QualType ObjCARCReferenceLifetimeType = M->getType();
00189     switch (Qualifiers::ObjCLifetime Lifetime =
00190                 ObjCARCReferenceLifetimeType.getObjCLifetime()) {
00191     case Qualifiers::OCL_None:
00192     case Qualifiers::OCL_ExplicitNone:
00193       // Carry on to normal cleanup handling.
00194       break;
00195 
00196     case Qualifiers::OCL_Autoreleasing:
00197       // Nothing to do; cleaned up by an autorelease pool.
00198       return;
00199 
00200     case Qualifiers::OCL_Strong:
00201     case Qualifiers::OCL_Weak:
00202       switch (StorageDuration Duration = M->getStorageDuration()) {
00203       case SD_Static:
00204         // Note: we intentionally do not register a cleanup to release
00205         // the object on program termination.
00206         return;
00207 
00208       case SD_Thread:
00209         // FIXME: We should probably register a cleanup in this case.
00210         return;
00211 
00212       case SD_Automatic:
00213       case SD_FullExpression:
00214         CodeGenFunction::Destroyer *Destroy;
00215         CleanupKind CleanupKind;
00216         if (Lifetime == Qualifiers::OCL_Strong) {
00217           const ValueDecl *VD = M->getExtendingDecl();
00218           bool Precise =
00219               VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
00220           CleanupKind = CGF.getARCCleanupKind();
00221           Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
00222                             : &CodeGenFunction::destroyARCStrongImprecise;
00223         } else {
00224           // __weak objects always get EH cleanups; otherwise, exceptions
00225           // could cause really nasty crashes instead of mere leaks.
00226           CleanupKind = NormalAndEHCleanup;
00227           Destroy = &CodeGenFunction::destroyARCWeak;
00228         }
00229         if (Duration == SD_FullExpression)
00230           CGF.pushDestroy(CleanupKind, ReferenceTemporary,
00231                           ObjCARCReferenceLifetimeType, *Destroy,
00232                           CleanupKind & EHCleanup);
00233         else
00234           CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
00235                                           ObjCARCReferenceLifetimeType,
00236                                           *Destroy, CleanupKind & EHCleanup);
00237         return;
00238 
00239       case SD_Dynamic:
00240         llvm_unreachable("temporary cannot have dynamic storage duration");
00241       }
00242       llvm_unreachable("unknown storage duration");
00243     }
00244   }
00245 
00246   CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
00247   if (const RecordType *RT =
00248           E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
00249     // Get the destructor for the reference temporary.
00250     auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
00251     if (!ClassDecl->hasTrivialDestructor())
00252       ReferenceTemporaryDtor = ClassDecl->getDestructor();
00253   }
00254 
00255   if (!ReferenceTemporaryDtor)
00256     return;
00257 
00258   // Call the destructor for the temporary.
00259   switch (M->getStorageDuration()) {
00260   case SD_Static:
00261   case SD_Thread: {
00262     llvm::Constant *CleanupFn;
00263     llvm::Constant *CleanupArg;
00264     if (E->getType()->isArrayType()) {
00265       CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
00266           cast<llvm::Constant>(ReferenceTemporary), E->getType(),
00267           CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
00268           dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
00269       CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
00270     } else {
00271       CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
00272                                                StructorType::Complete);
00273       CleanupArg = cast<llvm::Constant>(ReferenceTemporary);
00274     }
00275     CGF.CGM.getCXXABI().registerGlobalDtor(
00276         CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
00277     break;
00278   }
00279 
00280   case SD_FullExpression:
00281     CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
00282                     CodeGenFunction::destroyCXXObject,
00283                     CGF.getLangOpts().Exceptions);
00284     break;
00285 
00286   case SD_Automatic:
00287     CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
00288                                     ReferenceTemporary, E->getType(),
00289                                     CodeGenFunction::destroyCXXObject,
00290                                     CGF.getLangOpts().Exceptions);
00291     break;
00292 
00293   case SD_Dynamic:
00294     llvm_unreachable("temporary cannot have dynamic storage duration");
00295   }
00296 }
00297 
00298 static llvm::Value *
00299 createReferenceTemporary(CodeGenFunction &CGF,
00300                          const MaterializeTemporaryExpr *M, const Expr *Inner) {
00301   switch (M->getStorageDuration()) {
00302   case SD_FullExpression:
00303   case SD_Automatic:
00304     return CGF.CreateMemTemp(Inner->getType(), "ref.tmp");
00305 
00306   case SD_Thread:
00307   case SD_Static:
00308     return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
00309 
00310   case SD_Dynamic:
00311     llvm_unreachable("temporary can't have dynamic storage duration");
00312   }
00313   llvm_unreachable("unknown storage duration");
00314 }
00315 
00316 LValue CodeGenFunction::
00317 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
00318   const Expr *E = M->GetTemporaryExpr();
00319 
00320     // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
00321     // as that will cause the lifetime adjustment to be lost for ARC
00322   if (getLangOpts().ObjCAutoRefCount &&
00323       M->getType()->isObjCLifetimeType() &&
00324       M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
00325       M->getType().getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
00326     llvm::Value *Object = createReferenceTemporary(*this, M, E);
00327     LValue RefTempDst = MakeAddrLValue(Object, M->getType());
00328 
00329     if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
00330       // We should not have emitted the initializer for this temporary as a
00331       // constant.
00332       assert(!Var->hasInitializer());
00333       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
00334     }
00335 
00336     switch (getEvaluationKind(E->getType())) {
00337     default: llvm_unreachable("expected scalar or aggregate expression");
00338     case TEK_Scalar:
00339       EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
00340       break;
00341     case TEK_Aggregate: {
00342       CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
00343       EmitAggExpr(E, AggValueSlot::forAddr(Object, Alignment,
00344                                            E->getType().getQualifiers(),
00345                                            AggValueSlot::IsDestructed,
00346                                            AggValueSlot::DoesNotNeedGCBarriers,
00347                                            AggValueSlot::IsNotAliased));
00348       break;
00349     }
00350     }
00351 
00352     pushTemporaryCleanup(*this, M, E, Object);
00353     return RefTempDst;
00354   }
00355 
00356   SmallVector<const Expr *, 2> CommaLHSs;
00357   SmallVector<SubobjectAdjustment, 2> Adjustments;
00358   E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
00359 
00360   for (const auto &Ignored : CommaLHSs)
00361     EmitIgnoredExpr(Ignored);
00362 
00363   if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
00364     if (opaque->getType()->isRecordType()) {
00365       assert(Adjustments.empty());
00366       return EmitOpaqueValueLValue(opaque);
00367     }
00368   }
00369 
00370   // Create and initialize the reference temporary.
00371   llvm::Value *Object = createReferenceTemporary(*this, M, E);
00372   if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
00373     // If the temporary is a global and has a constant initializer, we may
00374     // have already initialized it.
00375     if (!Var->hasInitializer()) {
00376       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
00377       EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
00378     }
00379   } else {
00380     EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
00381   }
00382   pushTemporaryCleanup(*this, M, E, Object);
00383 
00384   // Perform derived-to-base casts and/or field accesses, to get from the
00385   // temporary object we created (and, potentially, for which we extended
00386   // the lifetime) to the subobject we're binding the reference to.
00387   for (unsigned I = Adjustments.size(); I != 0; --I) {
00388     SubobjectAdjustment &Adjustment = Adjustments[I-1];
00389     switch (Adjustment.Kind) {
00390     case SubobjectAdjustment::DerivedToBaseAdjustment:
00391       Object =
00392           GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
00393                                 Adjustment.DerivedToBase.BasePath->path_begin(),
00394                                 Adjustment.DerivedToBase.BasePath->path_end(),
00395                                 /*NullCheckValue=*/ false, E->getExprLoc());
00396       break;
00397 
00398     case SubobjectAdjustment::FieldAdjustment: {
00399       LValue LV = MakeAddrLValue(Object, E->getType());
00400       LV = EmitLValueForField(LV, Adjustment.Field);
00401       assert(LV.isSimple() &&
00402              "materialized temporary field is not a simple lvalue");
00403       Object = LV.getAddress();
00404       break;
00405     }
00406 
00407     case SubobjectAdjustment::MemberPointerAdjustment: {
00408       llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
00409       Object = CGM.getCXXABI().EmitMemberDataPointerAddress(
00410           *this, E, Object, Ptr, Adjustment.Ptr.MPT);
00411       break;
00412     }
00413     }
00414   }
00415 
00416   return MakeAddrLValue(Object, M->getType());
00417 }
00418 
00419 RValue
00420 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
00421   // Emit the expression as an lvalue.
00422   LValue LV = EmitLValue(E);
00423   assert(LV.isSimple());
00424   llvm::Value *Value = LV.getAddress();
00425 
00426   if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
00427     // C++11 [dcl.ref]p5 (as amended by core issue 453):
00428     //   If a glvalue to which a reference is directly bound designates neither
00429     //   an existing object or function of an appropriate type nor a region of
00430     //   storage of suitable size and alignment to contain an object of the
00431     //   reference's type, the behavior is undefined.
00432     QualType Ty = E->getType();
00433     EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
00434   }
00435 
00436   return RValue::get(Value);
00437 }
00438 
00439 
00440 /// getAccessedFieldNo - Given an encoded value and a result number, return the
00441 /// input field number being accessed.
00442 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
00443                                              const llvm::Constant *Elts) {
00444   return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
00445       ->getZExtValue();
00446 }
00447 
00448 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
00449 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
00450                                     llvm::Value *High) {
00451   llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
00452   llvm::Value *K47 = Builder.getInt64(47);
00453   llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
00454   llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
00455   llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
00456   llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
00457   return Builder.CreateMul(B1, KMul);
00458 }
00459 
00460 bool CodeGenFunction::sanitizePerformTypeCheck() const {
00461   return SanOpts.has(SanitizerKind::Null) |
00462          SanOpts.has(SanitizerKind::Alignment) |
00463          SanOpts.has(SanitizerKind::ObjectSize) |
00464          SanOpts.has(SanitizerKind::Vptr);
00465 }
00466 
00467 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
00468                                     llvm::Value *Address, QualType Ty,
00469                                     CharUnits Alignment, bool SkipNullCheck) {
00470   if (!sanitizePerformTypeCheck())
00471     return;
00472 
00473   // Don't check pointers outside the default address space. The null check
00474   // isn't correct, the object-size check isn't supported by LLVM, and we can't
00475   // communicate the addresses to the runtime handler for the vptr check.
00476   if (Address->getType()->getPointerAddressSpace())
00477     return;
00478 
00479   SanitizerScope SanScope(this);
00480 
00481   SmallVector<std::pair<llvm::Value *, SanitizerKind>, 3> Checks;
00482   llvm::BasicBlock *Done = nullptr;
00483 
00484   bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
00485                            TCK == TCK_UpcastToVirtualBase;
00486   if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
00487       !SkipNullCheck) {
00488     // The glvalue must not be an empty glvalue.
00489     llvm::Value *IsNonNull = Builder.CreateICmpNE(
00490         Address, llvm::Constant::getNullValue(Address->getType()));
00491 
00492     if (AllowNullPointers) {
00493       // When performing pointer casts, it's OK if the value is null.
00494       // Skip the remaining checks in that case.
00495       Done = createBasicBlock("null");
00496       llvm::BasicBlock *Rest = createBasicBlock("not.null");
00497       Builder.CreateCondBr(IsNonNull, Rest, Done);
00498       EmitBlock(Rest);
00499     } else {
00500       Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
00501     }
00502   }
00503 
00504   if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
00505     uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
00506 
00507     // The glvalue must refer to a large enough storage region.
00508     // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
00509     //        to check this.
00510     // FIXME: Get object address space
00511     llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
00512     llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
00513     llvm::Value *Min = Builder.getFalse();
00514     llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
00515     llvm::Value *LargeEnough =
00516         Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
00517                               llvm::ConstantInt::get(IntPtrTy, Size));
00518     Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
00519   }
00520 
00521   uint64_t AlignVal = 0;
00522 
00523   if (SanOpts.has(SanitizerKind::Alignment)) {
00524     AlignVal = Alignment.getQuantity();
00525     if (!Ty->isIncompleteType() && !AlignVal)
00526       AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
00527 
00528     // The glvalue must be suitably aligned.
00529     if (AlignVal) {
00530       llvm::Value *Align =
00531           Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
00532                             llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
00533       llvm::Value *Aligned =
00534         Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
00535       Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
00536     }
00537   }
00538 
00539   if (Checks.size() > 0) {
00540     llvm::Constant *StaticData[] = {
00541       EmitCheckSourceLocation(Loc),
00542       EmitCheckTypeDescriptor(Ty),
00543       llvm::ConstantInt::get(SizeTy, AlignVal),
00544       llvm::ConstantInt::get(Int8Ty, TCK)
00545     };
00546     EmitCheck(Checks, "type_mismatch", StaticData, Address);
00547   }
00548 
00549   // If possible, check that the vptr indicates that there is a subobject of
00550   // type Ty at offset zero within this object.
00551   //
00552   // C++11 [basic.life]p5,6:
00553   //   [For storage which does not refer to an object within its lifetime]
00554   //   The program has undefined behavior if:
00555   //    -- the [pointer or glvalue] is used to access a non-static data member
00556   //       or call a non-static member function
00557   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
00558   if (SanOpts.has(SanitizerKind::Vptr) &&
00559       (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
00560        TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
00561        TCK == TCK_UpcastToVirtualBase) &&
00562       RD && RD->hasDefinition() && RD->isDynamicClass()) {
00563     // Compute a hash of the mangled name of the type.
00564     //
00565     // FIXME: This is not guaranteed to be deterministic! Move to a
00566     //        fingerprinting mechanism once LLVM provides one. For the time
00567     //        being the implementation happens to be deterministic.
00568     SmallString<64> MangledName;
00569     llvm::raw_svector_ostream Out(MangledName);
00570     CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
00571                                                      Out);
00572 
00573     // Blacklist based on the mangled type.
00574     if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
00575             Out.str())) {
00576       llvm::hash_code TypeHash = hash_value(Out.str());
00577 
00578       // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
00579       llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
00580       llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
00581       llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
00582       llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
00583       llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
00584 
00585       llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
00586       Hash = Builder.CreateTrunc(Hash, IntPtrTy);
00587 
00588       // Look the hash up in our cache.
00589       const int CacheSize = 128;
00590       llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
00591       llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
00592                                                      "__ubsan_vptr_type_cache");
00593       llvm::Value *Slot = Builder.CreateAnd(Hash,
00594                                             llvm::ConstantInt::get(IntPtrTy,
00595                                                                    CacheSize-1));
00596       llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
00597       llvm::Value *CacheVal =
00598         Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
00599 
00600       // If the hash isn't in the cache, call a runtime handler to perform the
00601       // hard work of checking whether the vptr is for an object of the right
00602       // type. This will either fill in the cache and return, or produce a
00603       // diagnostic.
00604       llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
00605       llvm::Constant *StaticData[] = {
00606         EmitCheckSourceLocation(Loc),
00607         EmitCheckTypeDescriptor(Ty),
00608         CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
00609         llvm::ConstantInt::get(Int8Ty, TCK)
00610       };
00611       llvm::Value *DynamicData[] = { Address, Hash };
00612       EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
00613                 "dynamic_type_cache_miss", StaticData, DynamicData);
00614     }
00615   }
00616 
00617   if (Done) {
00618     Builder.CreateBr(Done);
00619     EmitBlock(Done);
00620   }
00621 }
00622 
00623 /// Determine whether this expression refers to a flexible array member in a
00624 /// struct. We disable array bounds checks for such members.
00625 static bool isFlexibleArrayMemberExpr(const Expr *E) {
00626   // For compatibility with existing code, we treat arrays of length 0 or
00627   // 1 as flexible array members.
00628   const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
00629   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
00630     if (CAT->getSize().ugt(1))
00631       return false;
00632   } else if (!isa<IncompleteArrayType>(AT))
00633     return false;
00634 
00635   E = E->IgnoreParens();
00636 
00637   // A flexible array member must be the last member in the class.
00638   if (const auto *ME = dyn_cast<MemberExpr>(E)) {
00639     // FIXME: If the base type of the member expr is not FD->getParent(),
00640     // this should not be treated as a flexible array member access.
00641     if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
00642       RecordDecl::field_iterator FI(
00643           DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
00644       return ++FI == FD->getParent()->field_end();
00645     }
00646   }
00647 
00648   return false;
00649 }
00650 
00651 /// If Base is known to point to the start of an array, return the length of
00652 /// that array. Return 0 if the length cannot be determined.
00653 static llvm::Value *getArrayIndexingBound(
00654     CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
00655   // For the vector indexing extension, the bound is the number of elements.
00656   if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
00657     IndexedType = Base->getType();
00658     return CGF.Builder.getInt32(VT->getNumElements());
00659   }
00660 
00661   Base = Base->IgnoreParens();
00662 
00663   if (const auto *CE = dyn_cast<CastExpr>(Base)) {
00664     if (CE->getCastKind() == CK_ArrayToPointerDecay &&
00665         !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
00666       IndexedType = CE->getSubExpr()->getType();
00667       const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
00668       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
00669         return CGF.Builder.getInt(CAT->getSize());
00670       else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
00671         return CGF.getVLASize(VAT).first;
00672     }
00673   }
00674 
00675   return nullptr;
00676 }
00677 
00678 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
00679                                       llvm::Value *Index, QualType IndexType,
00680                                       bool Accessed) {
00681   assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
00682          "should not be called unless adding bounds checks");
00683   SanitizerScope SanScope(this);
00684 
00685   QualType IndexedType;
00686   llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
00687   if (!Bound)
00688     return;
00689 
00690   bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
00691   llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
00692   llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
00693 
00694   llvm::Constant *StaticData[] = {
00695     EmitCheckSourceLocation(E->getExprLoc()),
00696     EmitCheckTypeDescriptor(IndexedType),
00697     EmitCheckTypeDescriptor(IndexType)
00698   };
00699   llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
00700                                 : Builder.CreateICmpULE(IndexVal, BoundVal);
00701   EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
00702             StaticData, Index);
00703 }
00704 
00705 
00706 CodeGenFunction::ComplexPairTy CodeGenFunction::
00707 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
00708                          bool isInc, bool isPre) {
00709   ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
00710 
00711   llvm::Value *NextVal;
00712   if (isa<llvm::IntegerType>(InVal.first->getType())) {
00713     uint64_t AmountVal = isInc ? 1 : -1;
00714     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
00715 
00716     // Add the inc/dec to the real part.
00717     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
00718   } else {
00719     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
00720     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
00721     if (!isInc)
00722       FVal.changeSign();
00723     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
00724 
00725     // Add the inc/dec to the real part.
00726     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
00727   }
00728 
00729   ComplexPairTy IncVal(NextVal, InVal.second);
00730 
00731   // Store the updated result through the lvalue.
00732   EmitStoreOfComplex(IncVal, LV, /*init*/ false);
00733 
00734   // If this is a postinc, return the value read from memory, otherwise use the
00735   // updated value.
00736   return isPre ? IncVal : InVal;
00737 }
00738 
00739 //===----------------------------------------------------------------------===//
00740 //                         LValue Expression Emission
00741 //===----------------------------------------------------------------------===//
00742 
00743 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
00744   if (Ty->isVoidType())
00745     return RValue::get(nullptr);
00746 
00747   switch (getEvaluationKind(Ty)) {
00748   case TEK_Complex: {
00749     llvm::Type *EltTy =
00750       ConvertType(Ty->castAs<ComplexType>()->getElementType());
00751     llvm::Value *U = llvm::UndefValue::get(EltTy);
00752     return RValue::getComplex(std::make_pair(U, U));
00753   }
00754 
00755   // If this is a use of an undefined aggregate type, the aggregate must have an
00756   // identifiable address.  Just because the contents of the value are undefined
00757   // doesn't mean that the address can't be taken and compared.
00758   case TEK_Aggregate: {
00759     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
00760     return RValue::getAggregate(DestPtr);
00761   }
00762 
00763   case TEK_Scalar:
00764     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
00765   }
00766   llvm_unreachable("bad evaluation kind");
00767 }
00768 
00769 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
00770                                               const char *Name) {
00771   ErrorUnsupported(E, Name);
00772   return GetUndefRValue(E->getType());
00773 }
00774 
00775 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
00776                                               const char *Name) {
00777   ErrorUnsupported(E, Name);
00778   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
00779   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
00780 }
00781 
00782 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
00783   LValue LV;
00784   if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
00785     LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
00786   else
00787     LV = EmitLValue(E);
00788   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
00789     EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
00790                   E->getType(), LV.getAlignment());
00791   return LV;
00792 }
00793 
00794 /// EmitLValue - Emit code to compute a designator that specifies the location
00795 /// of the expression.
00796 ///
00797 /// This can return one of two things: a simple address or a bitfield reference.
00798 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
00799 /// an LLVM pointer type.
00800 ///
00801 /// If this returns a bitfield reference, nothing about the pointee type of the
00802 /// LLVM value is known: For example, it may not be a pointer to an integer.
00803 ///
00804 /// If this returns a normal address, and if the lvalue's C type is fixed size,
00805 /// this method guarantees that the returned pointer type will point to an LLVM
00806 /// type of the same size of the lvalue's type.  If the lvalue has a variable
00807 /// length type, this is not possible.
00808 ///
00809 LValue CodeGenFunction::EmitLValue(const Expr *E) {
00810   switch (E->getStmtClass()) {
00811   default: return EmitUnsupportedLValue(E, "l-value expression");
00812 
00813   case Expr::ObjCPropertyRefExprClass:
00814     llvm_unreachable("cannot emit a property reference directly");
00815 
00816   case Expr::ObjCSelectorExprClass:
00817     return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
00818   case Expr::ObjCIsaExprClass:
00819     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
00820   case Expr::BinaryOperatorClass:
00821     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
00822   case Expr::CompoundAssignOperatorClass:
00823     if (!E->getType()->isAnyComplexType())
00824       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
00825     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
00826   case Expr::CallExprClass:
00827   case Expr::CXXMemberCallExprClass:
00828   case Expr::CXXOperatorCallExprClass:
00829   case Expr::UserDefinedLiteralClass:
00830     return EmitCallExprLValue(cast<CallExpr>(E));
00831   case Expr::VAArgExprClass:
00832     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
00833   case Expr::DeclRefExprClass:
00834     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
00835   case Expr::ParenExprClass:
00836     return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
00837   case Expr::GenericSelectionExprClass:
00838     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
00839   case Expr::PredefinedExprClass:
00840     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
00841   case Expr::StringLiteralClass:
00842     return EmitStringLiteralLValue(cast<StringLiteral>(E));
00843   case Expr::ObjCEncodeExprClass:
00844     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
00845   case Expr::PseudoObjectExprClass:
00846     return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
00847   case Expr::InitListExprClass:
00848     return EmitInitListLValue(cast<InitListExpr>(E));
00849   case Expr::CXXTemporaryObjectExprClass:
00850   case Expr::CXXConstructExprClass:
00851     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
00852   case Expr::CXXBindTemporaryExprClass:
00853     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
00854   case Expr::CXXUuidofExprClass:
00855     return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
00856   case Expr::LambdaExprClass:
00857     return EmitLambdaLValue(cast<LambdaExpr>(E));
00858 
00859   case Expr::ExprWithCleanupsClass: {
00860     const auto *cleanups = cast<ExprWithCleanups>(E);
00861     enterFullExpression(cleanups);
00862     RunCleanupsScope Scope(*this);
00863     return EmitLValue(cleanups->getSubExpr());
00864   }
00865 
00866   case Expr::CXXDefaultArgExprClass:
00867     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
00868   case Expr::CXXDefaultInitExprClass: {
00869     CXXDefaultInitExprScope Scope(*this);
00870     return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
00871   }
00872   case Expr::CXXTypeidExprClass:
00873     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
00874 
00875   case Expr::ObjCMessageExprClass:
00876     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
00877   case Expr::ObjCIvarRefExprClass:
00878     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
00879   case Expr::StmtExprClass:
00880     return EmitStmtExprLValue(cast<StmtExpr>(E));
00881   case Expr::UnaryOperatorClass:
00882     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
00883   case Expr::ArraySubscriptExprClass:
00884     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
00885   case Expr::ExtVectorElementExprClass:
00886     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
00887   case Expr::MemberExprClass:
00888     return EmitMemberExpr(cast<MemberExpr>(E));
00889   case Expr::CompoundLiteralExprClass:
00890     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
00891   case Expr::ConditionalOperatorClass:
00892     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
00893   case Expr::BinaryConditionalOperatorClass:
00894     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
00895   case Expr::ChooseExprClass:
00896     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
00897   case Expr::OpaqueValueExprClass:
00898     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
00899   case Expr::SubstNonTypeTemplateParmExprClass:
00900     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
00901   case Expr::ImplicitCastExprClass:
00902   case Expr::CStyleCastExprClass:
00903   case Expr::CXXFunctionalCastExprClass:
00904   case Expr::CXXStaticCastExprClass:
00905   case Expr::CXXDynamicCastExprClass:
00906   case Expr::CXXReinterpretCastExprClass:
00907   case Expr::CXXConstCastExprClass:
00908   case Expr::ObjCBridgedCastExprClass:
00909     return EmitCastLValue(cast<CastExpr>(E));
00910 
00911   case Expr::MaterializeTemporaryExprClass:
00912     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
00913   }
00914 }
00915 
00916 /// Given an object of the given canonical type, can we safely copy a
00917 /// value out of it based on its initializer?
00918 static bool isConstantEmittableObjectType(QualType type) {
00919   assert(type.isCanonical());
00920   assert(!type->isReferenceType());
00921 
00922   // Must be const-qualified but non-volatile.
00923   Qualifiers qs = type.getLocalQualifiers();
00924   if (!qs.hasConst() || qs.hasVolatile()) return false;
00925 
00926   // Otherwise, all object types satisfy this except C++ classes with
00927   // mutable subobjects or non-trivial copy/destroy behavior.
00928   if (const auto *RT = dyn_cast<RecordType>(type))
00929     if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
00930       if (RD->hasMutableFields() || !RD->isTrivial())
00931         return false;
00932 
00933   return true;
00934 }
00935 
00936 /// Can we constant-emit a load of a reference to a variable of the
00937 /// given type?  This is different from predicates like
00938 /// Decl::isUsableInConstantExpressions because we do want it to apply
00939 /// in situations that don't necessarily satisfy the language's rules
00940 /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
00941 /// to do this with const float variables even if those variables
00942 /// aren't marked 'constexpr'.
00943 enum ConstantEmissionKind {
00944   CEK_None,
00945   CEK_AsReferenceOnly,
00946   CEK_AsValueOrReference,
00947   CEK_AsValueOnly
00948 };
00949 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
00950   type = type.getCanonicalType();
00951   if (const auto *ref = dyn_cast<ReferenceType>(type)) {
00952     if (isConstantEmittableObjectType(ref->getPointeeType()))
00953       return CEK_AsValueOrReference;
00954     return CEK_AsReferenceOnly;
00955   }
00956   if (isConstantEmittableObjectType(type))
00957     return CEK_AsValueOnly;
00958   return CEK_None;
00959 }
00960 
00961 /// Try to emit a reference to the given value without producing it as
00962 /// an l-value.  This is actually more than an optimization: we can't
00963 /// produce an l-value for variables that we never actually captured
00964 /// in a block or lambda, which means const int variables or constexpr
00965 /// literals or similar.
00966 CodeGenFunction::ConstantEmission
00967 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
00968   ValueDecl *value = refExpr->getDecl();
00969 
00970   // The value needs to be an enum constant or a constant variable.
00971   ConstantEmissionKind CEK;
00972   if (isa<ParmVarDecl>(value)) {
00973     CEK = CEK_None;
00974   } else if (auto *var = dyn_cast<VarDecl>(value)) {
00975     CEK = checkVarTypeForConstantEmission(var->getType());
00976   } else if (isa<EnumConstantDecl>(value)) {
00977     CEK = CEK_AsValueOnly;
00978   } else {
00979     CEK = CEK_None;
00980   }
00981   if (CEK == CEK_None) return ConstantEmission();
00982 
00983   Expr::EvalResult result;
00984   bool resultIsReference;
00985   QualType resultType;
00986 
00987   // It's best to evaluate all the way as an r-value if that's permitted.
00988   if (CEK != CEK_AsReferenceOnly &&
00989       refExpr->EvaluateAsRValue(result, getContext())) {
00990     resultIsReference = false;
00991     resultType = refExpr->getType();
00992 
00993   // Otherwise, try to evaluate as an l-value.
00994   } else if (CEK != CEK_AsValueOnly &&
00995              refExpr->EvaluateAsLValue(result, getContext())) {
00996     resultIsReference = true;
00997     resultType = value->getType();
00998 
00999   // Failure.
01000   } else {
01001     return ConstantEmission();
01002   }
01003 
01004   // In any case, if the initializer has side-effects, abandon ship.
01005   if (result.HasSideEffects)
01006     return ConstantEmission();
01007 
01008   // Emit as a constant.
01009   llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
01010 
01011   // Make sure we emit a debug reference to the global variable.
01012   // This should probably fire even for
01013   if (isa<VarDecl>(value)) {
01014     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
01015       EmitDeclRefExprDbgValue(refExpr, C);
01016   } else {
01017     assert(isa<EnumConstantDecl>(value));
01018     EmitDeclRefExprDbgValue(refExpr, C);
01019   }
01020 
01021   // If we emitted a reference constant, we need to dereference that.
01022   if (resultIsReference)
01023     return ConstantEmission::forReference(C);
01024 
01025   return ConstantEmission::forValue(C);
01026 }
01027 
01028 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
01029                                                SourceLocation Loc) {
01030   return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
01031                           lvalue.getAlignment().getQuantity(),
01032                           lvalue.getType(), Loc, lvalue.getTBAAInfo(),
01033                           lvalue.getTBAABaseType(), lvalue.getTBAAOffset());
01034 }
01035 
01036 static bool hasBooleanRepresentation(QualType Ty) {
01037   if (Ty->isBooleanType())
01038     return true;
01039 
01040   if (const EnumType *ET = Ty->getAs<EnumType>())
01041     return ET->getDecl()->getIntegerType()->isBooleanType();
01042 
01043   if (const AtomicType *AT = Ty->getAs<AtomicType>())
01044     return hasBooleanRepresentation(AT->getValueType());
01045 
01046   return false;
01047 }
01048 
01049 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
01050                             llvm::APInt &Min, llvm::APInt &End,
01051                             bool StrictEnums) {
01052   const EnumType *ET = Ty->getAs<EnumType>();
01053   bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
01054                                 ET && !ET->getDecl()->isFixed();
01055   bool IsBool = hasBooleanRepresentation(Ty);
01056   if (!IsBool && !IsRegularCPlusPlusEnum)
01057     return false;
01058 
01059   if (IsBool) {
01060     Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
01061     End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
01062   } else {
01063     const EnumDecl *ED = ET->getDecl();
01064     llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
01065     unsigned Bitwidth = LTy->getScalarSizeInBits();
01066     unsigned NumNegativeBits = ED->getNumNegativeBits();
01067     unsigned NumPositiveBits = ED->getNumPositiveBits();
01068 
01069     if (NumNegativeBits) {
01070       unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
01071       assert(NumBits <= Bitwidth);
01072       End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
01073       Min = -End;
01074     } else {
01075       assert(NumPositiveBits <= Bitwidth);
01076       End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
01077       Min = llvm::APInt(Bitwidth, 0);
01078     }
01079   }
01080   return true;
01081 }
01082 
01083 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
01084   llvm::APInt Min, End;
01085   if (!getRangeForType(*this, Ty, Min, End,
01086                        CGM.getCodeGenOpts().StrictEnums))
01087     return nullptr;
01088 
01089   llvm::MDBuilder MDHelper(getLLVMContext());
01090   return MDHelper.createRange(Min, End);
01091 }
01092 
01093 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
01094                                                unsigned Alignment, QualType Ty,
01095                                                SourceLocation Loc,
01096                                                llvm::MDNode *TBAAInfo,
01097                                                QualType TBAABaseType,
01098                                                uint64_t TBAAOffset) {
01099   // For better performance, handle vector loads differently.
01100   if (Ty->isVectorType()) {
01101     llvm::Value *V;
01102     const llvm::Type *EltTy =
01103     cast<llvm::PointerType>(Addr->getType())->getElementType();
01104 
01105     const auto *VTy = cast<llvm::VectorType>(EltTy);
01106 
01107     // Handle vectors of size 3, like size 4 for better performance.
01108     if (VTy->getNumElements() == 3) {
01109 
01110       // Bitcast to vec4 type.
01111       llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
01112                                                          4);
01113       llvm::PointerType *ptVec4Ty =
01114       llvm::PointerType::get(vec4Ty,
01115                              (cast<llvm::PointerType>(
01116                                       Addr->getType()))->getAddressSpace());
01117       llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
01118                                                 "castToVec4");
01119       // Now load value.
01120       llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
01121 
01122       // Shuffle vector to get vec3.
01123       llvm::Constant *Mask[] = {
01124         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
01125         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
01126         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
01127       };
01128 
01129       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
01130       V = Builder.CreateShuffleVector(LoadVal,
01131                                       llvm::UndefValue::get(vec4Ty),
01132                                       MaskV, "extractVec");
01133       return EmitFromMemory(V, Ty);
01134     }
01135   }
01136 
01137   // Atomic operations have to be done on integral types.
01138   if (Ty->isAtomicType()) {
01139     LValue lvalue = LValue::MakeAddr(Addr, Ty,
01140                                      CharUnits::fromQuantity(Alignment),
01141                                      getContext(), TBAAInfo);
01142     return EmitAtomicLoad(lvalue, Loc).getScalarVal();
01143   }
01144 
01145   llvm::LoadInst *Load = Builder.CreateLoad(Addr);
01146   if (Volatile)
01147     Load->setVolatile(true);
01148   if (Alignment)
01149     Load->setAlignment(Alignment);
01150   if (TBAAInfo) {
01151     llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
01152                                                       TBAAOffset);
01153     if (TBAAPath)
01154       CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
01155   }
01156 
01157   bool NeedsBoolCheck =
01158       SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
01159   bool NeedsEnumCheck =
01160       SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
01161   if (NeedsBoolCheck || NeedsEnumCheck) {
01162     SanitizerScope SanScope(this);
01163     llvm::APInt Min, End;
01164     if (getRangeForType(*this, Ty, Min, End, true)) {
01165       --End;
01166       llvm::Value *Check;
01167       if (!Min)
01168         Check = Builder.CreateICmpULE(
01169           Load, llvm::ConstantInt::get(getLLVMContext(), End));
01170       else {
01171         llvm::Value *Upper = Builder.CreateICmpSLE(
01172           Load, llvm::ConstantInt::get(getLLVMContext(), End));
01173         llvm::Value *Lower = Builder.CreateICmpSGE(
01174           Load, llvm::ConstantInt::get(getLLVMContext(), Min));
01175         Check = Builder.CreateAnd(Upper, Lower);
01176       }
01177       llvm::Constant *StaticArgs[] = {
01178         EmitCheckSourceLocation(Loc),
01179         EmitCheckTypeDescriptor(Ty)
01180       };
01181       SanitizerKind Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
01182       EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
01183                 EmitCheckValue(Load));
01184     }
01185   } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
01186     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
01187       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
01188 
01189   return EmitFromMemory(Load, Ty);
01190 }
01191 
01192 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
01193   // Bool has a different representation in memory than in registers.
01194   if (hasBooleanRepresentation(Ty)) {
01195     // This should really always be an i1, but sometimes it's already
01196     // an i8, and it's awkward to track those cases down.
01197     if (Value->getType()->isIntegerTy(1))
01198       return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
01199     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
01200            "wrong value rep of bool");
01201   }
01202 
01203   return Value;
01204 }
01205 
01206 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
01207   // Bool has a different representation in memory than in registers.
01208   if (hasBooleanRepresentation(Ty)) {
01209     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
01210            "wrong value rep of bool");
01211     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
01212   }
01213 
01214   return Value;
01215 }
01216 
01217 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
01218                                         bool Volatile, unsigned Alignment,
01219                                         QualType Ty, llvm::MDNode *TBAAInfo,
01220                                         bool isInit, QualType TBAABaseType,
01221                                         uint64_t TBAAOffset) {
01222 
01223   // Handle vectors differently to get better performance.
01224   if (Ty->isVectorType()) {
01225     llvm::Type *SrcTy = Value->getType();
01226     auto *VecTy = cast<llvm::VectorType>(SrcTy);
01227     // Handle vec3 special.
01228     if (VecTy->getNumElements() == 3) {
01229       llvm::LLVMContext &VMContext = getLLVMContext();
01230 
01231       // Our source is a vec3, do a shuffle vector to make it a vec4.
01232       SmallVector<llvm::Constant*, 4> Mask;
01233       Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
01234                                             0));
01235       Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
01236                                             1));
01237       Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
01238                                             2));
01239       Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
01240 
01241       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
01242       Value = Builder.CreateShuffleVector(Value,
01243                                           llvm::UndefValue::get(VecTy),
01244                                           MaskV, "extractVec");
01245       SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
01246     }
01247     auto *DstPtr = cast<llvm::PointerType>(Addr->getType());
01248     if (DstPtr->getElementType() != SrcTy) {
01249       llvm::Type *MemTy =
01250       llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
01251       Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
01252     }
01253   }
01254 
01255   Value = EmitToMemory(Value, Ty);
01256 
01257   if (Ty->isAtomicType()) {
01258     EmitAtomicStore(RValue::get(Value),
01259                     LValue::MakeAddr(Addr, Ty,
01260                                      CharUnits::fromQuantity(Alignment),
01261                                      getContext(), TBAAInfo),
01262                     isInit);
01263     return;
01264   }
01265 
01266   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
01267   if (Alignment)
01268     Store->setAlignment(Alignment);
01269   if (TBAAInfo) {
01270     llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
01271                                                       TBAAOffset);
01272     if (TBAAPath)
01273       CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
01274   }
01275 }
01276 
01277 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
01278                                         bool isInit) {
01279   EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
01280                     lvalue.getAlignment().getQuantity(), lvalue.getType(),
01281                     lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
01282                     lvalue.getTBAAOffset());
01283 }
01284 
01285 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
01286 /// method emits the address of the lvalue, then loads the result as an rvalue,
01287 /// returning the rvalue.
01288 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
01289   if (LV.isObjCWeak()) {
01290     // load of a __weak object.
01291     llvm::Value *AddrWeakObj = LV.getAddress();
01292     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
01293                                                              AddrWeakObj));
01294   }
01295   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
01296     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
01297     Object = EmitObjCConsumeObject(LV.getType(), Object);
01298     return RValue::get(Object);
01299   }
01300 
01301   if (LV.isSimple()) {
01302     assert(!LV.getType()->isFunctionType());
01303 
01304     // Everything needs a load.
01305     return RValue::get(EmitLoadOfScalar(LV, Loc));
01306   }
01307 
01308   if (LV.isVectorElt()) {
01309     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
01310                                               LV.isVolatileQualified());
01311     Load->setAlignment(LV.getAlignment().getQuantity());
01312     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
01313                                                     "vecext"));
01314   }
01315 
01316   // If this is a reference to a subset of the elements of a vector, either
01317   // shuffle the input or extract/insert them as appropriate.
01318   if (LV.isExtVectorElt())
01319     return EmitLoadOfExtVectorElementLValue(LV);
01320 
01321   // Global Register variables always invoke intrinsics
01322   if (LV.isGlobalReg())
01323     return EmitLoadOfGlobalRegLValue(LV);
01324 
01325   assert(LV.isBitField() && "Unknown LValue type!");
01326   return EmitLoadOfBitfieldLValue(LV);
01327 }
01328 
01329 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
01330   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
01331 
01332   // Get the output type.
01333   llvm::Type *ResLTy = ConvertType(LV.getType());
01334 
01335   llvm::Value *Ptr = LV.getBitFieldAddr();
01336   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
01337                                         "bf.load");
01338   cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
01339 
01340   if (Info.IsSigned) {
01341     assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
01342     unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
01343     if (HighBits)
01344       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
01345     if (Info.Offset + HighBits)
01346       Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
01347   } else {
01348     if (Info.Offset)
01349       Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
01350     if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
01351       Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
01352                                                               Info.Size),
01353                               "bf.clear");
01354   }
01355   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
01356 
01357   return RValue::get(Val);
01358 }
01359 
01360 // If this is a reference to a subset of the elements of a vector, create an
01361 // appropriate shufflevector.
01362 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
01363   llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
01364                                             LV.isVolatileQualified());
01365   Load->setAlignment(LV.getAlignment().getQuantity());
01366   llvm::Value *Vec = Load;
01367 
01368   const llvm::Constant *Elts = LV.getExtVectorElts();
01369 
01370   // If the result of the expression is a non-vector type, we must be extracting
01371   // a single element.  Just codegen as an extractelement.
01372   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
01373   if (!ExprVT) {
01374     unsigned InIdx = getAccessedFieldNo(0, Elts);
01375     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
01376     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
01377   }
01378 
01379   // Always use shuffle vector to try to retain the original program structure
01380   unsigned NumResultElts = ExprVT->getNumElements();
01381 
01382   SmallVector<llvm::Constant*, 4> Mask;
01383   for (unsigned i = 0; i != NumResultElts; ++i)
01384     Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
01385 
01386   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
01387   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
01388                                     MaskV);
01389   return RValue::get(Vec);
01390 }
01391 
01392 /// @brief Generates lvalue for partial ext_vector access.
01393 llvm::Value *CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
01394   llvm::Value *VectorAddress = LV.getExtVectorAddr();
01395   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
01396   QualType EQT = ExprVT->getElementType();
01397   llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
01398   llvm::Type *VectorElementPtrToTy = VectorElementTy->getPointerTo();
01399   
01400   llvm::Value *CastToPointerElement =
01401     Builder.CreateBitCast(VectorAddress,
01402                           VectorElementPtrToTy, "conv.ptr.element");
01403   
01404   const llvm::Constant *Elts = LV.getExtVectorElts();
01405   unsigned ix = getAccessedFieldNo(0, Elts);
01406   
01407   llvm::Value *VectorBasePtrPlusIx =
01408     Builder.CreateInBoundsGEP(CastToPointerElement,
01409                               llvm::ConstantInt::get(SizeTy, ix), "add.ptr");
01410   
01411   return VectorBasePtrPlusIx;
01412 }
01413 
01414 /// @brief Load of global gamed gegisters are always calls to intrinsics.
01415 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
01416   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
01417          "Bad type for register variable");
01418   llvm::MDNode *RegName = dyn_cast<llvm::MDNode>(LV.getGlobalReg());
01419   assert(RegName && "Register LValue is not metadata");
01420 
01421   // We accept integer and pointer types only
01422   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
01423   llvm::Type *Ty = OrigTy;
01424   if (OrigTy->isPointerTy())
01425     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
01426   llvm::Type *Types[] = { Ty };
01427 
01428   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
01429   llvm::Value *Call = Builder.CreateCall(F, RegName);
01430   if (OrigTy->isPointerTy())
01431     Call = Builder.CreateIntToPtr(Call, OrigTy);
01432   return RValue::get(Call);
01433 }
01434 
01435 
01436 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
01437 /// lvalue, where both are guaranteed to the have the same type, and that type
01438 /// is 'Ty'.
01439 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
01440                                              bool isInit) {
01441   if (!Dst.isSimple()) {
01442     if (Dst.isVectorElt()) {
01443       // Read/modify/write the vector, inserting the new element.
01444       llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
01445                                                 Dst.isVolatileQualified());
01446       Load->setAlignment(Dst.getAlignment().getQuantity());
01447       llvm::Value *Vec = Load;
01448       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
01449                                         Dst.getVectorIdx(), "vecins");
01450       llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
01451                                                    Dst.isVolatileQualified());
01452       Store->setAlignment(Dst.getAlignment().getQuantity());
01453       return;
01454     }
01455 
01456     // If this is an update of extended vector elements, insert them as
01457     // appropriate.
01458     if (Dst.isExtVectorElt())
01459       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
01460 
01461     if (Dst.isGlobalReg())
01462       return EmitStoreThroughGlobalRegLValue(Src, Dst);
01463 
01464     assert(Dst.isBitField() && "Unknown LValue type");
01465     return EmitStoreThroughBitfieldLValue(Src, Dst);
01466   }
01467 
01468   // There's special magic for assigning into an ARC-qualified l-value.
01469   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
01470     switch (Lifetime) {
01471     case Qualifiers::OCL_None:
01472       llvm_unreachable("present but none");
01473 
01474     case Qualifiers::OCL_ExplicitNone:
01475       // nothing special
01476       break;
01477 
01478     case Qualifiers::OCL_Strong:
01479       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
01480       return;
01481 
01482     case Qualifiers::OCL_Weak:
01483       EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
01484       return;
01485 
01486     case Qualifiers::OCL_Autoreleasing:
01487       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
01488                                                      Src.getScalarVal()));
01489       // fall into the normal path
01490       break;
01491     }
01492   }
01493 
01494   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
01495     // load of a __weak object.
01496     llvm::Value *LvalueDst = Dst.getAddress();
01497     llvm::Value *src = Src.getScalarVal();
01498      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
01499     return;
01500   }
01501 
01502   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
01503     // load of a __strong object.
01504     llvm::Value *LvalueDst = Dst.getAddress();
01505     llvm::Value *src = Src.getScalarVal();
01506     if (Dst.isObjCIvar()) {
01507       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
01508       llvm::Type *ResultType = ConvertType(getContext().LongTy);
01509       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
01510       llvm::Value *dst = RHS;
01511       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
01512       llvm::Value *LHS =
01513         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
01514       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
01515       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
01516                                               BytesBetween);
01517     } else if (Dst.isGlobalObjCRef()) {
01518       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
01519                                                 Dst.isThreadLocalRef());
01520     }
01521     else
01522       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
01523     return;
01524   }
01525 
01526   assert(Src.isScalar() && "Can't emit an agg store with this method");
01527   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
01528 }
01529 
01530 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
01531                                                      llvm::Value **Result) {
01532   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
01533   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
01534   llvm::Value *Ptr = Dst.getBitFieldAddr();
01535 
01536   // Get the source value, truncated to the width of the bit-field.
01537   llvm::Value *SrcVal = Src.getScalarVal();
01538 
01539   // Cast the source to the storage type and shift it into place.
01540   SrcVal = Builder.CreateIntCast(SrcVal,
01541                                  Ptr->getType()->getPointerElementType(),
01542                                  /*IsSigned=*/false);
01543   llvm::Value *MaskedVal = SrcVal;
01544 
01545   // See if there are other bits in the bitfield's storage we'll need to load
01546   // and mask together with source before storing.
01547   if (Info.StorageSize != Info.Size) {
01548     assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
01549     llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
01550                                           "bf.load");
01551     cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
01552 
01553     // Mask the source value as needed.
01554     if (!hasBooleanRepresentation(Dst.getType()))
01555       SrcVal = Builder.CreateAnd(SrcVal,
01556                                  llvm::APInt::getLowBitsSet(Info.StorageSize,
01557                                                             Info.Size),
01558                                  "bf.value");
01559     MaskedVal = SrcVal;
01560     if (Info.Offset)
01561       SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
01562 
01563     // Mask out the original value.
01564     Val = Builder.CreateAnd(Val,
01565                             ~llvm::APInt::getBitsSet(Info.StorageSize,
01566                                                      Info.Offset,
01567                                                      Info.Offset + Info.Size),
01568                             "bf.clear");
01569 
01570     // Or together the unchanged values and the source value.
01571     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
01572   } else {
01573     assert(Info.Offset == 0);
01574   }
01575 
01576   // Write the new value back out.
01577   llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
01578                                                Dst.isVolatileQualified());
01579   Store->setAlignment(Info.StorageAlignment);
01580 
01581   // Return the new value of the bit-field, if requested.
01582   if (Result) {
01583     llvm::Value *ResultVal = MaskedVal;
01584 
01585     // Sign extend the value if needed.
01586     if (Info.IsSigned) {
01587       assert(Info.Size <= Info.StorageSize);
01588       unsigned HighBits = Info.StorageSize - Info.Size;
01589       if (HighBits) {
01590         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
01591         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
01592       }
01593     }
01594 
01595     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
01596                                       "bf.result.cast");
01597     *Result = EmitFromMemory(ResultVal, Dst.getType());
01598   }
01599 }
01600 
01601 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
01602                                                                LValue Dst) {
01603   // This access turns into a read/modify/write of the vector.  Load the input
01604   // value now.
01605   llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
01606                                             Dst.isVolatileQualified());
01607   Load->setAlignment(Dst.getAlignment().getQuantity());
01608   llvm::Value *Vec = Load;
01609   const llvm::Constant *Elts = Dst.getExtVectorElts();
01610 
01611   llvm::Value *SrcVal = Src.getScalarVal();
01612 
01613   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
01614     unsigned NumSrcElts = VTy->getNumElements();
01615     unsigned NumDstElts =
01616        cast<llvm::VectorType>(Vec->getType())->getNumElements();
01617     if (NumDstElts == NumSrcElts) {
01618       // Use shuffle vector is the src and destination are the same number of
01619       // elements and restore the vector mask since it is on the side it will be
01620       // stored.
01621       SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
01622       for (unsigned i = 0; i != NumSrcElts; ++i)
01623         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
01624 
01625       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
01626       Vec = Builder.CreateShuffleVector(SrcVal,
01627                                         llvm::UndefValue::get(Vec->getType()),
01628                                         MaskV);
01629     } else if (NumDstElts > NumSrcElts) {
01630       // Extended the source vector to the same length and then shuffle it
01631       // into the destination.
01632       // FIXME: since we're shuffling with undef, can we just use the indices
01633       //        into that?  This could be simpler.
01634       SmallVector<llvm::Constant*, 4> ExtMask;
01635       for (unsigned i = 0; i != NumSrcElts; ++i)
01636         ExtMask.push_back(Builder.getInt32(i));
01637       ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
01638       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
01639       llvm::Value *ExtSrcVal =
01640         Builder.CreateShuffleVector(SrcVal,
01641                                     llvm::UndefValue::get(SrcVal->getType()),
01642                                     ExtMaskV);
01643       // build identity
01644       SmallVector<llvm::Constant*, 4> Mask;
01645       for (unsigned i = 0; i != NumDstElts; ++i)
01646         Mask.push_back(Builder.getInt32(i));
01647 
01648       // When the vector size is odd and .odd or .hi is used, the last element
01649       // of the Elts constant array will be one past the size of the vector.
01650       // Ignore the last element here, if it is greater than the mask size.
01651       if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
01652         NumSrcElts--;
01653 
01654       // modify when what gets shuffled in
01655       for (unsigned i = 0; i != NumSrcElts; ++i)
01656         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
01657       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
01658       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
01659     } else {
01660       // We should never shorten the vector
01661       llvm_unreachable("unexpected shorten vector length");
01662     }
01663   } else {
01664     // If the Src is a scalar (not a vector) it must be updating one element.
01665     unsigned InIdx = getAccessedFieldNo(0, Elts);
01666     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
01667     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
01668   }
01669 
01670   llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
01671                                                Dst.isVolatileQualified());
01672   Store->setAlignment(Dst.getAlignment().getQuantity());
01673 }
01674 
01675 /// @brief Store of global named registers are always calls to intrinsics.
01676 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
01677   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
01678          "Bad type for register variable");
01679   llvm::MDNode *RegName = dyn_cast<llvm::MDNode>(Dst.getGlobalReg());
01680   assert(RegName && "Register LValue is not metadata");
01681 
01682   // We accept integer and pointer types only
01683   llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
01684   llvm::Type *Ty = OrigTy;
01685   if (OrigTy->isPointerTy())
01686     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
01687   llvm::Type *Types[] = { Ty };
01688 
01689   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
01690   llvm::Value *Value = Src.getScalarVal();
01691   if (OrigTy->isPointerTy())
01692     Value = Builder.CreatePtrToInt(Value, Ty);
01693   Builder.CreateCall2(F, RegName, Value);
01694 }
01695 
01696 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
01697 // generating write-barries API. It is currently a global, ivar,
01698 // or neither.
01699 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
01700                                  LValue &LV,
01701                                  bool IsMemberAccess=false) {
01702   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
01703     return;
01704 
01705   if (isa<ObjCIvarRefExpr>(E)) {
01706     QualType ExpTy = E->getType();
01707     if (IsMemberAccess && ExpTy->isPointerType()) {
01708       // If ivar is a structure pointer, assigning to field of
01709       // this struct follows gcc's behavior and makes it a non-ivar
01710       // writer-barrier conservatively.
01711       ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
01712       if (ExpTy->isRecordType()) {
01713         LV.setObjCIvar(false);
01714         return;
01715       }
01716     }
01717     LV.setObjCIvar(true);
01718     auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
01719     LV.setBaseIvarExp(Exp->getBase());
01720     LV.setObjCArray(E->getType()->isArrayType());
01721     return;
01722   }
01723 
01724   if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
01725     if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
01726       if (VD->hasGlobalStorage()) {
01727         LV.setGlobalObjCRef(true);
01728         LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
01729       }
01730     }
01731     LV.setObjCArray(E->getType()->isArrayType());
01732     return;
01733   }
01734 
01735   if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
01736     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
01737     return;
01738   }
01739 
01740   if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
01741     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
01742     if (LV.isObjCIvar()) {
01743       // If cast is to a structure pointer, follow gcc's behavior and make it
01744       // a non-ivar write-barrier.
01745       QualType ExpTy = E->getType();
01746       if (ExpTy->isPointerType())
01747         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
01748       if (ExpTy->isRecordType())
01749         LV.setObjCIvar(false);
01750     }
01751     return;
01752   }
01753 
01754   if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
01755     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
01756     return;
01757   }
01758 
01759   if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
01760     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
01761     return;
01762   }
01763 
01764   if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
01765     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
01766     return;
01767   }
01768 
01769   if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
01770     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
01771     return;
01772   }
01773 
01774   if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
01775     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
01776     if (LV.isObjCIvar() && !LV.isObjCArray())
01777       // Using array syntax to assigning to what an ivar points to is not
01778       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
01779       LV.setObjCIvar(false);
01780     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
01781       // Using array syntax to assigning to what global points to is not
01782       // same as assigning to the global itself. {id *G;} G[i] = 0;
01783       LV.setGlobalObjCRef(false);
01784     return;
01785   }
01786 
01787   if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
01788     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
01789     // We don't know if member is an 'ivar', but this flag is looked at
01790     // only in the context of LV.isObjCIvar().
01791     LV.setObjCArray(E->getType()->isArrayType());
01792     return;
01793   }
01794 }
01795 
01796 static llvm::Value *
01797 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
01798                                 llvm::Value *V, llvm::Type *IRType,
01799                                 StringRef Name = StringRef()) {
01800   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
01801   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
01802 }
01803 
01804 static LValue EmitThreadPrivateVarDeclLValue(
01805     CodeGenFunction &CGF, const VarDecl *VD, QualType T, llvm::Value *V,
01806     llvm::Type *RealVarTy, CharUnits Alignment, SourceLocation Loc) {
01807   V = CGF.CGM.getOpenMPRuntime().getOMPAddrOfThreadPrivate(CGF, VD, V, Loc);
01808   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
01809   return CGF.MakeAddrLValue(V, T, Alignment);
01810 }
01811 
01812 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
01813                                       const Expr *E, const VarDecl *VD) {
01814   QualType T = E->getType();
01815 
01816   // If it's thread_local, emit a call to its wrapper function instead.
01817   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
01818       CGF.CGM.getCXXABI().usesThreadWrapperFunction())
01819     return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
01820 
01821   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
01822   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
01823   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
01824   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
01825   LValue LV;
01826   // Emit reference to the private copy of the variable if it is an OpenMP
01827   // threadprivate variable.
01828   if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
01829     return EmitThreadPrivateVarDeclLValue(CGF, VD, T, V, RealVarTy, Alignment,
01830                                           E->getExprLoc());
01831   if (VD->getType()->isReferenceType()) {
01832     llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
01833     LI->setAlignment(Alignment.getQuantity());
01834     V = LI;
01835     LV = CGF.MakeNaturalAlignAddrLValue(V, T);
01836   } else {
01837     LV = CGF.MakeAddrLValue(V, T, Alignment);
01838   }
01839   setObjCGCLValueClass(CGF.getContext(), E, LV);
01840   return LV;
01841 }
01842 
01843 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
01844                                      const Expr *E, const FunctionDecl *FD) {
01845   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
01846   if (!FD->hasPrototype()) {
01847     if (const FunctionProtoType *Proto =
01848             FD->getType()->getAs<FunctionProtoType>()) {
01849       // Ugly case: for a K&R-style definition, the type of the definition
01850       // isn't the same as the type of a use.  Correct for this with a
01851       // bitcast.
01852       QualType NoProtoType =
01853           CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
01854       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
01855       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
01856     }
01857   }
01858   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
01859   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
01860 }
01861 
01862 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
01863                                       llvm::Value *ThisValue) {
01864   QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
01865   LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
01866   return CGF.EmitLValueForField(LV, FD);
01867 }
01868 
01869 /// Named Registers are named metadata pointing to the register name
01870 /// which will be read from/written to as an argument to the intrinsic
01871 /// @llvm.read/write_register.
01872 /// So far, only the name is being passed down, but other options such as
01873 /// register type, allocation type or even optimization options could be
01874 /// passed down via the metadata node.
01875 static LValue EmitGlobalNamedRegister(const VarDecl *VD,
01876                                       CodeGenModule &CGM,
01877                                       CharUnits Alignment) {
01878   SmallString<64> Name("llvm.named.register.");
01879   AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
01880   assert(Asm->getLabel().size() < 64-Name.size() &&
01881       "Register name too big");
01882   Name.append(Asm->getLabel());
01883   llvm::NamedMDNode *M =
01884     CGM.getModule().getOrInsertNamedMetadata(Name);
01885   if (M->getNumOperands() == 0) {
01886     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
01887                                               Asm->getLabel());
01888     llvm::Value *Ops[] = { Str };
01889     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
01890   }
01891   return LValue::MakeGlobalReg(M->getOperand(0), VD->getType(), Alignment);
01892 }
01893 
01894 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
01895   const NamedDecl *ND = E->getDecl();
01896   CharUnits Alignment = getContext().getDeclAlign(ND);
01897   QualType T = E->getType();
01898 
01899   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
01900     // Global Named registers access via intrinsics only
01901     if (VD->getStorageClass() == SC_Register &&
01902         VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
01903       return EmitGlobalNamedRegister(VD, CGM, Alignment);
01904 
01905     // A DeclRefExpr for a reference initialized by a constant expression can
01906     // appear without being odr-used. Directly emit the constant initializer.
01907     const Expr *Init = VD->getAnyInitializer(VD);
01908     if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
01909         VD->isUsableInConstantExpressions(getContext()) &&
01910         VD->checkInitIsICE()) {
01911       llvm::Constant *Val =
01912         CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
01913       assert(Val && "failed to emit reference constant expression");
01914       // FIXME: Eventually we will want to emit vector element references.
01915       return MakeAddrLValue(Val, T, Alignment);
01916     }
01917   }
01918 
01919   // FIXME: We should be able to assert this for FunctionDecls as well!
01920   // FIXME: We should be able to assert this for all DeclRefExprs, not just
01921   // those with a valid source location.
01922   assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
01923           !E->getLocation().isValid()) &&
01924          "Should not use decl without marking it used!");
01925 
01926   if (ND->hasAttr<WeakRefAttr>()) {
01927     const auto *VD = cast<ValueDecl>(ND);
01928     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
01929     return MakeAddrLValue(Aliasee, T, Alignment);
01930   }
01931 
01932   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
01933     // Check if this is a global variable.
01934     if (VD->hasLinkage() || VD->isStaticDataMember())
01935       return EmitGlobalVarDeclLValue(*this, E, VD);
01936 
01937     bool isBlockVariable = VD->hasAttr<BlocksAttr>();
01938 
01939     llvm::Value *V = LocalDeclMap.lookup(VD);
01940     if (!V && VD->isStaticLocal())
01941       V = CGM.getOrCreateStaticVarDecl(
01942           *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
01943 
01944     // Check if variable is threadprivate.
01945     if (V && getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
01946       return EmitThreadPrivateVarDeclLValue(
01947           *this, VD, T, V, getTypes().ConvertTypeForMem(VD->getType()),
01948           Alignment, E->getExprLoc());
01949 
01950     // Use special handling for lambdas.
01951     if (!V) {
01952       if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
01953         return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
01954       } else if (CapturedStmtInfo) {
01955         if (const FieldDecl *FD = CapturedStmtInfo->lookup(VD))
01956           return EmitCapturedFieldLValue(*this, FD,
01957                                          CapturedStmtInfo->getContextValue());
01958       }
01959 
01960       assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
01961       return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
01962                             T, Alignment);
01963     }
01964 
01965     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
01966 
01967     if (isBlockVariable)
01968       V = BuildBlockByrefAddress(V, VD);
01969 
01970     LValue LV;
01971     if (VD->getType()->isReferenceType()) {
01972       llvm::LoadInst *LI = Builder.CreateLoad(V);
01973       LI->setAlignment(Alignment.getQuantity());
01974       V = LI;
01975       LV = MakeNaturalAlignAddrLValue(V, T);
01976     } else {
01977       LV = MakeAddrLValue(V, T, Alignment);
01978     }
01979 
01980     bool isLocalStorage = VD->hasLocalStorage();
01981 
01982     bool NonGCable = isLocalStorage &&
01983                      !VD->getType()->isReferenceType() &&
01984                      !isBlockVariable;
01985     if (NonGCable) {
01986       LV.getQuals().removeObjCGCAttr();
01987       LV.setNonGC(true);
01988     }
01989 
01990     bool isImpreciseLifetime =
01991       (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
01992     if (isImpreciseLifetime)
01993       LV.setARCPreciseLifetime(ARCImpreciseLifetime);
01994     setObjCGCLValueClass(getContext(), E, LV);
01995     return LV;
01996   }
01997 
01998   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
01999     return EmitFunctionDeclLValue(*this, E, FD);
02000 
02001   llvm_unreachable("Unhandled DeclRefExpr");
02002 }
02003 
02004 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
02005   // __extension__ doesn't affect lvalue-ness.
02006   if (E->getOpcode() == UO_Extension)
02007     return EmitLValue(E->getSubExpr());
02008 
02009   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
02010   switch (E->getOpcode()) {
02011   default: llvm_unreachable("Unknown unary operator lvalue!");
02012   case UO_Deref: {
02013     QualType T = E->getSubExpr()->getType()->getPointeeType();
02014     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
02015 
02016     LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
02017     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
02018 
02019     // We should not generate __weak write barrier on indirect reference
02020     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
02021     // But, we continue to generate __strong write barrier on indirect write
02022     // into a pointer to object.
02023     if (getLangOpts().ObjC1 &&
02024         getLangOpts().getGC() != LangOptions::NonGC &&
02025         LV.isObjCWeak())
02026       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
02027     return LV;
02028   }
02029   case UO_Real:
02030   case UO_Imag: {
02031     LValue LV = EmitLValue(E->getSubExpr());
02032     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
02033     llvm::Value *Addr = LV.getAddress();
02034 
02035     // __real is valid on scalars.  This is a faster way of testing that.
02036     // __imag can only produce an rvalue on scalars.
02037     if (E->getOpcode() == UO_Real &&
02038         !cast<llvm::PointerType>(Addr->getType())
02039            ->getElementType()->isStructTy()) {
02040       assert(E->getSubExpr()->getType()->isArithmeticType());
02041       return LV;
02042     }
02043 
02044     assert(E->getSubExpr()->getType()->isAnyComplexType());
02045 
02046     unsigned Idx = E->getOpcode() == UO_Imag;
02047     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
02048                                                   Idx, "idx"),
02049                           ExprTy);
02050   }
02051   case UO_PreInc:
02052   case UO_PreDec: {
02053     LValue LV = EmitLValue(E->getSubExpr());
02054     bool isInc = E->getOpcode() == UO_PreInc;
02055 
02056     if (E->getType()->isAnyComplexType())
02057       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
02058     else
02059       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
02060     return LV;
02061   }
02062   }
02063 }
02064 
02065 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
02066   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
02067                         E->getType());
02068 }
02069 
02070 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
02071   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
02072                         E->getType());
02073 }
02074 
02075 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
02076   auto SL = E->getFunctionName();
02077   assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
02078   StringRef FnName = CurFn->getName();
02079   if (FnName.startswith("\01"))
02080     FnName = FnName.substr(1);
02081   StringRef NameItems[] = {
02082       PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
02083   std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
02084   if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
02085     auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str(), 1);
02086     return MakeAddrLValue(C, E->getType());
02087   }
02088   auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
02089   return MakeAddrLValue(C, E->getType());
02090 }
02091 
02092 /// Emit a type description suitable for use by a runtime sanitizer library. The
02093 /// format of a type descriptor is
02094 ///
02095 /// \code
02096 ///   { i16 TypeKind, i16 TypeInfo }
02097 /// \endcode
02098 ///
02099 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
02100 /// integer, 1 for a floating point value, and -1 for anything else.
02101 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
02102   // Only emit each type's descriptor once.
02103   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
02104     return C;
02105 
02106   uint16_t TypeKind = -1;
02107   uint16_t TypeInfo = 0;
02108 
02109   if (T->isIntegerType()) {
02110     TypeKind = 0;
02111     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
02112                (T->isSignedIntegerType() ? 1 : 0);
02113   } else if (T->isFloatingType()) {
02114     TypeKind = 1;
02115     TypeInfo = getContext().getTypeSize(T);
02116   }
02117 
02118   // Format the type name as if for a diagnostic, including quotes and
02119   // optionally an 'aka'.
02120   SmallString<32> Buffer;
02121   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
02122                                     (intptr_t)T.getAsOpaquePtr(),
02123                                     StringRef(), StringRef(), None, Buffer,
02124                                     None);
02125 
02126   llvm::Constant *Components[] = {
02127     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
02128     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
02129   };
02130   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
02131 
02132   auto *GV = new llvm::GlobalVariable(
02133       CGM.getModule(), Descriptor->getType(),
02134       /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
02135   GV->setUnnamedAddr(true);
02136   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
02137 
02138   // Remember the descriptor for this type.
02139   CGM.setTypeDescriptorInMap(T, GV);
02140 
02141   return GV;
02142 }
02143 
02144 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
02145   llvm::Type *TargetTy = IntPtrTy;
02146 
02147   // Floating-point types which fit into intptr_t are bitcast to integers
02148   // and then passed directly (after zero-extension, if necessary).
02149   if (V->getType()->isFloatingPointTy()) {
02150     unsigned Bits = V->getType()->getPrimitiveSizeInBits();
02151     if (Bits <= TargetTy->getIntegerBitWidth())
02152       V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
02153                                                          Bits));
02154   }
02155 
02156   // Integers which fit in intptr_t are zero-extended and passed directly.
02157   if (V->getType()->isIntegerTy() &&
02158       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
02159     return Builder.CreateZExt(V, TargetTy);
02160 
02161   // Pointers are passed directly, everything else is passed by address.
02162   if (!V->getType()->isPointerTy()) {
02163     llvm::Value *Ptr = CreateTempAlloca(V->getType());
02164     Builder.CreateStore(V, Ptr);
02165     V = Ptr;
02166   }
02167   return Builder.CreatePtrToInt(V, TargetTy);
02168 }
02169 
02170 /// \brief Emit a representation of a SourceLocation for passing to a handler
02171 /// in a sanitizer runtime library. The format for this data is:
02172 /// \code
02173 ///   struct SourceLocation {
02174 ///     const char *Filename;
02175 ///     int32_t Line, Column;
02176 ///   };
02177 /// \endcode
02178 /// For an invalid SourceLocation, the Filename pointer is null.
02179 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
02180   llvm::Constant *Filename;
02181   int Line, Column;
02182 
02183   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
02184   if (PLoc.isValid()) {
02185     auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
02186     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(FilenameGV);
02187     Filename = FilenameGV;
02188     Line = PLoc.getLine();
02189     Column = PLoc.getColumn();
02190   } else {
02191     Filename = llvm::Constant::getNullValue(Int8PtrTy);
02192     Line = Column = 0;
02193   }
02194 
02195   llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
02196                             Builder.getInt32(Column)};
02197 
02198   return llvm::ConstantStruct::getAnon(Data);
02199 }
02200 
02201 namespace {
02202 /// \brief Specify under what conditions this check can be recovered
02203 enum class CheckRecoverableKind {
02204   /// Always terminate program execution if this check fails
02205   Unrecoverable,
02206   /// Check supports recovering, allows user to specify which
02207   Recoverable,
02208   /// Runtime conditionally aborts, always need to support recovery.
02209   AlwaysRecoverable
02210 };
02211 }
02212 
02213 static CheckRecoverableKind getRecoverableKind(SanitizerKind Kind) {
02214   switch (Kind) {
02215   case SanitizerKind::Vptr:
02216     return CheckRecoverableKind::AlwaysRecoverable;
02217   case SanitizerKind::Return:
02218   case SanitizerKind::Unreachable:
02219     return CheckRecoverableKind::Unrecoverable;
02220   default:
02221     return CheckRecoverableKind::Recoverable;
02222   }
02223 }
02224 
02225 void CodeGenFunction::EmitCheck(
02226     ArrayRef<std::pair<llvm::Value *, SanitizerKind>> Checked,
02227     StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
02228     ArrayRef<llvm::Value *> DynamicArgs) {
02229   assert(IsSanitizerScope);
02230   assert(Checked.size() > 0);
02231   llvm::Value *Cond = Checked[0].first;
02232   CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
02233   assert(SanOpts.has(Checked[0].second));
02234   for (int i = 1, n = Checked.size(); i < n; ++i) {
02235     Cond = Builder.CreateAnd(Cond, Checked[i].first);
02236     assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
02237            "All recoverable kinds in a single check must be same!");
02238     assert(SanOpts.has(Checked[i].second));
02239   }
02240 
02241   if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
02242     assert (RecoverKind != CheckRecoverableKind::AlwaysRecoverable &&
02243             "Runtime call required for AlwaysRecoverable kind!");
02244     return EmitTrapCheck(Cond);
02245   }
02246 
02247   llvm::BasicBlock *Cont = createBasicBlock("cont");
02248 
02249   llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
02250 
02251   llvm::Instruction *Branch = Builder.CreateCondBr(Cond, Cont, Handler);
02252 
02253   // Give hint that we very much don't expect to execute the handler
02254   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
02255   llvm::MDBuilder MDHelper(getLLVMContext());
02256   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
02257   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
02258 
02259   EmitBlock(Handler);
02260 
02261   llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
02262   auto *InfoPtr =
02263       new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
02264                                llvm::GlobalVariable::PrivateLinkage, Info);
02265   InfoPtr->setUnnamedAddr(true);
02266   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
02267 
02268   SmallVector<llvm::Value *, 4> Args;
02269   SmallVector<llvm::Type *, 4> ArgTypes;
02270   Args.reserve(DynamicArgs.size() + 1);
02271   ArgTypes.reserve(DynamicArgs.size() + 1);
02272 
02273   // Handler functions take an i8* pointing to the (handler-specific) static
02274   // information block, followed by a sequence of intptr_t arguments
02275   // representing operand values.
02276   Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
02277   ArgTypes.push_back(Int8PtrTy);
02278   for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
02279     Args.push_back(EmitCheckValue(DynamicArgs[i]));
02280     ArgTypes.push_back(IntPtrTy);
02281   }
02282 
02283   bool Recover = RecoverKind == CheckRecoverableKind::AlwaysRecoverable ||
02284                  (RecoverKind == CheckRecoverableKind::Recoverable &&
02285                   CGM.getCodeGenOpts().SanitizeRecover);
02286 
02287   llvm::FunctionType *FnType =
02288     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
02289   llvm::AttrBuilder B;
02290   if (!Recover) {
02291     B.addAttribute(llvm::Attribute::NoReturn)
02292      .addAttribute(llvm::Attribute::NoUnwind);
02293   }
02294   B.addAttribute(llvm::Attribute::UWTable);
02295 
02296   // Checks that have two variants use a suffix to differentiate them
02297   bool NeedsAbortSuffix = RecoverKind != CheckRecoverableKind::Unrecoverable &&
02298                           !CGM.getCodeGenOpts().SanitizeRecover;
02299   std::string FunctionName = ("__ubsan_handle_" + CheckName +
02300                               (NeedsAbortSuffix? "_abort" : "")).str();
02301   llvm::Value *Fn = CGM.CreateRuntimeFunction(
02302       FnType, FunctionName,
02303       llvm::AttributeSet::get(getLLVMContext(),
02304                               llvm::AttributeSet::FunctionIndex, B));
02305   llvm::CallInst *HandlerCall = EmitNounwindRuntimeCall(Fn, Args);
02306   if (Recover) {
02307     Builder.CreateBr(Cont);
02308   } else {
02309     HandlerCall->setDoesNotReturn();
02310     Builder.CreateUnreachable();
02311   }
02312 
02313   EmitBlock(Cont);
02314 }
02315 
02316 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
02317   llvm::BasicBlock *Cont = createBasicBlock("cont");
02318 
02319   // If we're optimizing, collapse all calls to trap down to just one per
02320   // function to save on code size.
02321   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
02322     TrapBB = createBasicBlock("trap");
02323     Builder.CreateCondBr(Checked, Cont, TrapBB);
02324     EmitBlock(TrapBB);
02325     llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
02326     llvm::CallInst *TrapCall = Builder.CreateCall(F);
02327     TrapCall->setDoesNotReturn();
02328     TrapCall->setDoesNotThrow();
02329     Builder.CreateUnreachable();
02330   } else {
02331     Builder.CreateCondBr(Checked, Cont, TrapBB);
02332   }
02333 
02334   EmitBlock(Cont);
02335 }
02336 
02337 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
02338 /// array to pointer, return the array subexpression.
02339 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
02340   // If this isn't just an array->pointer decay, bail out.
02341   const auto *CE = dyn_cast<CastExpr>(E);
02342   if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
02343     return nullptr;
02344 
02345   // If this is a decay from variable width array, bail out.
02346   const Expr *SubExpr = CE->getSubExpr();
02347   if (SubExpr->getType()->isVariableArrayType())
02348     return nullptr;
02349 
02350   return SubExpr;
02351 }
02352 
02353 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
02354                                                bool Accessed) {
02355   // The index must always be an integer, which is not an aggregate.  Emit it.
02356   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
02357   QualType IdxTy  = E->getIdx()->getType();
02358   bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
02359 
02360   if (SanOpts.has(SanitizerKind::ArrayBounds))
02361     EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
02362 
02363   // If the base is a vector type, then we are forming a vector element lvalue
02364   // with this subscript.
02365   if (E->getBase()->getType()->isVectorType() &&
02366       !isa<ExtVectorElementExpr>(E->getBase())) {
02367     // Emit the vector as an lvalue to get its address.
02368     LValue LHS = EmitLValue(E->getBase());
02369     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
02370     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
02371                                  E->getBase()->getType(), LHS.getAlignment());
02372   }
02373 
02374   // Extend or truncate the index type to 32 or 64-bits.
02375   if (Idx->getType() != IntPtrTy)
02376     Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
02377 
02378   // We know that the pointer points to a type of the correct size, unless the
02379   // size is a VLA or Objective-C interface.
02380   llvm::Value *Address = nullptr;
02381   CharUnits ArrayAlignment;
02382   if (isa<ExtVectorElementExpr>(E->getBase())) {
02383     LValue LV = EmitLValue(E->getBase());
02384     Address = EmitExtVectorElementLValue(LV);
02385     Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
02386     const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
02387     QualType EQT = ExprVT->getElementType();
02388     return MakeAddrLValue(Address, EQT,
02389                           getContext().getTypeAlignInChars(EQT));
02390   }
02391   else if (const VariableArrayType *vla =
02392            getContext().getAsVariableArrayType(E->getType())) {
02393     // The base must be a pointer, which is not an aggregate.  Emit
02394     // it.  It needs to be emitted first in case it's what captures
02395     // the VLA bounds.
02396     Address = EmitScalarExpr(E->getBase());
02397 
02398     // The element count here is the total number of non-VLA elements.
02399     llvm::Value *numElements = getVLASize(vla).first;
02400 
02401     // Effectively, the multiply by the VLA size is part of the GEP.
02402     // GEP indexes are signed, and scaling an index isn't permitted to
02403     // signed-overflow, so we use the same semantics for our explicit
02404     // multiply.  We suppress this if overflow is not undefined behavior.
02405     if (getLangOpts().isSignedOverflowDefined()) {
02406       Idx = Builder.CreateMul(Idx, numElements);
02407       Address = Builder.CreateGEP(Address, Idx, "arrayidx");
02408     } else {
02409       Idx = Builder.CreateNSWMul(Idx, numElements);
02410       Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
02411     }
02412   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
02413     // Indexing over an interface, as in "NSString *P; P[4];"
02414     llvm::Value *InterfaceSize =
02415       llvm::ConstantInt::get(Idx->getType(),
02416           getContext().getTypeSizeInChars(OIT).getQuantity());
02417 
02418     Idx = Builder.CreateMul(Idx, InterfaceSize);
02419 
02420     // The base must be a pointer, which is not an aggregate.  Emit it.
02421     llvm::Value *Base = EmitScalarExpr(E->getBase());
02422     Address = EmitCastToVoidPtr(Base);
02423     Address = Builder.CreateGEP(Address, Idx, "arrayidx");
02424     Address = Builder.CreateBitCast(Address, Base->getType());
02425   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
02426     // If this is A[i] where A is an array, the frontend will have decayed the
02427     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
02428     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
02429     // "gep x, i" here.  Emit one "gep A, 0, i".
02430     assert(Array->getType()->isArrayType() &&
02431            "Array to pointer decay must have array source type!");
02432     LValue ArrayLV;
02433     // For simple multidimensional array indexing, set the 'accessed' flag for
02434     // better bounds-checking of the base expression.
02435     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
02436       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
02437     else
02438       ArrayLV = EmitLValue(Array);
02439     llvm::Value *ArrayPtr = ArrayLV.getAddress();
02440     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
02441     llvm::Value *Args[] = { Zero, Idx };
02442 
02443     // Propagate the alignment from the array itself to the result.
02444     ArrayAlignment = ArrayLV.getAlignment();
02445 
02446     if (getLangOpts().isSignedOverflowDefined())
02447       Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
02448     else
02449       Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
02450   } else {
02451     // The base must be a pointer, which is not an aggregate.  Emit it.
02452     llvm::Value *Base = EmitScalarExpr(E->getBase());
02453     if (getLangOpts().isSignedOverflowDefined())
02454       Address = Builder.CreateGEP(Base, Idx, "arrayidx");
02455     else
02456       Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
02457   }
02458 
02459   QualType T = E->getBase()->getType()->getPointeeType();
02460   assert(!T.isNull() &&
02461          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
02462 
02463 
02464   // Limit the alignment to that of the result type.
02465   LValue LV;
02466   if (!ArrayAlignment.isZero()) {
02467     CharUnits Align = getContext().getTypeAlignInChars(T);
02468     ArrayAlignment = std::min(Align, ArrayAlignment);
02469     LV = MakeAddrLValue(Address, T, ArrayAlignment);
02470   } else {
02471     LV = MakeNaturalAlignAddrLValue(Address, T);
02472   }
02473 
02474   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
02475 
02476   if (getLangOpts().ObjC1 &&
02477       getLangOpts().getGC() != LangOptions::NonGC) {
02478     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
02479     setObjCGCLValueClass(getContext(), E, LV);
02480   }
02481   return LV;
02482 }
02483 
02484 static
02485 llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
02486                                        SmallVectorImpl<unsigned> &Elts) {
02487   SmallVector<llvm::Constant*, 4> CElts;
02488   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
02489     CElts.push_back(Builder.getInt32(Elts[i]));
02490 
02491   return llvm::ConstantVector::get(CElts);
02492 }
02493 
02494 LValue CodeGenFunction::
02495 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
02496   // Emit the base vector as an l-value.
02497   LValue Base;
02498 
02499   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
02500   if (E->isArrow()) {
02501     // If it is a pointer to a vector, emit the address and form an lvalue with
02502     // it.
02503     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
02504     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
02505     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
02506     Base.getQuals().removeObjCGCAttr();
02507   } else if (E->getBase()->isGLValue()) {
02508     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
02509     // emit the base as an lvalue.
02510     assert(E->getBase()->getType()->isVectorType());
02511     Base = EmitLValue(E->getBase());
02512   } else {
02513     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
02514     assert(E->getBase()->getType()->isVectorType() &&
02515            "Result must be a vector");
02516     llvm::Value *Vec = EmitScalarExpr(E->getBase());
02517 
02518     // Store the vector to memory (because LValue wants an address).
02519     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
02520     Builder.CreateStore(Vec, VecMem);
02521     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
02522   }
02523 
02524   QualType type =
02525     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
02526 
02527   // Encode the element access list into a vector of unsigned indices.
02528   SmallVector<unsigned, 4> Indices;
02529   E->getEncodedElementAccess(Indices);
02530 
02531   if (Base.isSimple()) {
02532     llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
02533     return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
02534                                     Base.getAlignment());
02535   }
02536   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
02537 
02538   llvm::Constant *BaseElts = Base.getExtVectorElts();
02539   SmallVector<llvm::Constant *, 4> CElts;
02540 
02541   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
02542     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
02543   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
02544   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
02545                                   Base.getAlignment());
02546 }
02547 
02548 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
02549   Expr *BaseExpr = E->getBase();
02550 
02551   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
02552   LValue BaseLV;
02553   if (E->isArrow()) {
02554     llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
02555     QualType PtrTy = BaseExpr->getType()->getPointeeType();
02556     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
02557     BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
02558   } else
02559     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
02560 
02561   NamedDecl *ND = E->getMemberDecl();
02562   if (auto *Field = dyn_cast<FieldDecl>(ND)) {
02563     LValue LV = EmitLValueForField(BaseLV, Field);
02564     setObjCGCLValueClass(getContext(), E, LV);
02565     return LV;
02566   }
02567 
02568   if (auto *VD = dyn_cast<VarDecl>(ND))
02569     return EmitGlobalVarDeclLValue(*this, E, VD);
02570 
02571   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
02572     return EmitFunctionDeclLValue(*this, E, FD);
02573 
02574   llvm_unreachable("Unhandled member declaration!");
02575 }
02576 
02577 /// Given that we are currently emitting a lambda, emit an l-value for
02578 /// one of its members.
02579 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
02580   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
02581   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
02582   QualType LambdaTagType =
02583     getContext().getTagDeclType(Field->getParent());
02584   LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
02585   return EmitLValueForField(LambdaLV, Field);
02586 }
02587 
02588 LValue CodeGenFunction::EmitLValueForField(LValue base,
02589                                            const FieldDecl *field) {
02590   if (field->isBitField()) {
02591     const CGRecordLayout &RL =
02592       CGM.getTypes().getCGRecordLayout(field->getParent());
02593     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
02594     llvm::Value *Addr = base.getAddress();
02595     unsigned Idx = RL.getLLVMFieldNo(field);
02596     if (Idx != 0)
02597       // For structs, we GEP to the field that the record layout suggests.
02598       Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
02599     // Get the access type.
02600     llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
02601       getLLVMContext(), Info.StorageSize,
02602       CGM.getContext().getTargetAddressSpace(base.getType()));
02603     if (Addr->getType() != PtrTy)
02604       Addr = Builder.CreateBitCast(Addr, PtrTy);
02605 
02606     QualType fieldType =
02607       field->getType().withCVRQualifiers(base.getVRQualifiers());
02608     return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
02609   }
02610 
02611   const RecordDecl *rec = field->getParent();
02612   QualType type = field->getType();
02613   CharUnits alignment = getContext().getDeclAlign(field);
02614 
02615   // FIXME: It should be impossible to have an LValue without alignment for a
02616   // complete type.
02617   if (!base.getAlignment().isZero())
02618     alignment = std::min(alignment, base.getAlignment());
02619 
02620   bool mayAlias = rec->hasAttr<MayAliasAttr>();
02621 
02622   llvm::Value *addr = base.getAddress();
02623   unsigned cvr = base.getVRQualifiers();
02624   bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
02625   if (rec->isUnion()) {
02626     // For unions, there is no pointer adjustment.
02627     assert(!type->isReferenceType() && "union has reference member");
02628     // TODO: handle path-aware TBAA for union.
02629     TBAAPath = false;
02630   } else {
02631     // For structs, we GEP to the field that the record layout suggests.
02632     unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
02633     addr = Builder.CreateStructGEP(addr, idx, field->getName());
02634 
02635     // If this is a reference field, load the reference right now.
02636     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
02637       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
02638       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
02639       load->setAlignment(alignment.getQuantity());
02640 
02641       // Loading the reference will disable path-aware TBAA.
02642       TBAAPath = false;
02643       if (CGM.shouldUseTBAA()) {
02644         llvm::MDNode *tbaa;
02645         if (mayAlias)
02646           tbaa = CGM.getTBAAInfo(getContext().CharTy);
02647         else
02648           tbaa = CGM.getTBAAInfo(type);
02649         if (tbaa)
02650           CGM.DecorateInstruction(load, tbaa);
02651       }
02652 
02653       addr = load;
02654       mayAlias = false;
02655       type = refType->getPointeeType();
02656       if (type->isIncompleteType())
02657         alignment = CharUnits();
02658       else
02659         alignment = getContext().getTypeAlignInChars(type);
02660       cvr = 0; // qualifiers don't recursively apply to referencee
02661     }
02662   }
02663 
02664   // Make sure that the address is pointing to the right type.  This is critical
02665   // for both unions and structs.  A union needs a bitcast, a struct element
02666   // will need a bitcast if the LLVM type laid out doesn't match the desired
02667   // type.
02668   addr = EmitBitCastOfLValueToProperType(*this, addr,
02669                                          CGM.getTypes().ConvertTypeForMem(type),
02670                                          field->getName());
02671 
02672   if (field->hasAttr<AnnotateAttr>())
02673     addr = EmitFieldAnnotations(field, addr);
02674 
02675   LValue LV = MakeAddrLValue(addr, type, alignment);
02676   LV.getQuals().addCVRQualifiers(cvr);
02677   if (TBAAPath) {
02678     const ASTRecordLayout &Layout =
02679         getContext().getASTRecordLayout(field->getParent());
02680     // Set the base type to be the base type of the base LValue and
02681     // update offset to be relative to the base type.
02682     LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
02683     LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
02684                      Layout.getFieldOffset(field->getFieldIndex()) /
02685                                            getContext().getCharWidth());
02686   }
02687 
02688   // __weak attribute on a field is ignored.
02689   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
02690     LV.getQuals().removeObjCGCAttr();
02691 
02692   // Fields of may_alias structs act like 'char' for TBAA purposes.
02693   // FIXME: this should get propagated down through anonymous structs
02694   // and unions.
02695   if (mayAlias && LV.getTBAAInfo())
02696     LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
02697 
02698   return LV;
02699 }
02700 
02701 LValue
02702 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
02703                                                   const FieldDecl *Field) {
02704   QualType FieldType = Field->getType();
02705 
02706   if (!FieldType->isReferenceType())
02707     return EmitLValueForField(Base, Field);
02708 
02709   const CGRecordLayout &RL =
02710     CGM.getTypes().getCGRecordLayout(Field->getParent());
02711   unsigned idx = RL.getLLVMFieldNo(Field);
02712   llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
02713   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
02714 
02715   // Make sure that the address is pointing to the right type.  This is critical
02716   // for both unions and structs.  A union needs a bitcast, a struct element
02717   // will need a bitcast if the LLVM type laid out doesn't match the desired
02718   // type.
02719   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
02720   V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
02721 
02722   CharUnits Alignment = getContext().getDeclAlign(Field);
02723 
02724   // FIXME: It should be impossible to have an LValue without alignment for a
02725   // complete type.
02726   if (!Base.getAlignment().isZero())
02727     Alignment = std::min(Alignment, Base.getAlignment());
02728 
02729   return MakeAddrLValue(V, FieldType, Alignment);
02730 }
02731 
02732 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
02733   if (E->isFileScope()) {
02734     llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
02735     return MakeAddrLValue(GlobalPtr, E->getType());
02736   }
02737   if (E->getType()->isVariablyModifiedType())
02738     // make sure to emit the VLA size.
02739     EmitVariablyModifiedType(E->getType());
02740 
02741   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
02742   const Expr *InitExpr = E->getInitializer();
02743   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
02744 
02745   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
02746                    /*Init*/ true);
02747 
02748   return Result;
02749 }
02750 
02751 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
02752   if (!E->isGLValue())
02753     // Initializing an aggregate temporary in C++11: T{...}.
02754     return EmitAggExprToLValue(E);
02755 
02756   // An lvalue initializer list must be initializing a reference.
02757   assert(E->getNumInits() == 1 && "reference init with multiple values");
02758   return EmitLValue(E->getInit(0));
02759 }
02760 
02761 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
02762 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
02763 /// LValue is returned and the current block has been terminated.
02764 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
02765                                                     const Expr *Operand) {
02766   if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
02767     CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
02768     return None;
02769   }
02770 
02771   return CGF.EmitLValue(Operand);
02772 }
02773 
02774 LValue CodeGenFunction::
02775 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
02776   if (!expr->isGLValue()) {
02777     // ?: here should be an aggregate.
02778     assert(hasAggregateEvaluationKind(expr->getType()) &&
02779            "Unexpected conditional operator!");
02780     return EmitAggExprToLValue(expr);
02781   }
02782 
02783   OpaqueValueMapping binding(*this, expr);
02784   RegionCounter Cnt = getPGORegionCounter(expr);
02785 
02786   const Expr *condExpr = expr->getCond();
02787   bool CondExprBool;
02788   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
02789     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
02790     if (!CondExprBool) std::swap(live, dead);
02791 
02792     if (!ContainsLabel(dead)) {
02793       // If the true case is live, we need to track its region.
02794       if (CondExprBool)
02795         Cnt.beginRegion(Builder);
02796       return EmitLValue(live);
02797     }
02798   }
02799 
02800   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
02801   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
02802   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
02803 
02804   ConditionalEvaluation eval(*this);
02805   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, Cnt.getCount());
02806 
02807   // Any temporaries created here are conditional.
02808   EmitBlock(lhsBlock);
02809   Cnt.beginRegion(Builder);
02810   eval.begin(*this);
02811   Optional<LValue> lhs =
02812       EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
02813   eval.end(*this);
02814 
02815   if (lhs && !lhs->isSimple())
02816     return EmitUnsupportedLValue(expr, "conditional operator");
02817 
02818   lhsBlock = Builder.GetInsertBlock();
02819   if (lhs)
02820     Builder.CreateBr(contBlock);
02821 
02822   // Any temporaries created here are conditional.
02823   EmitBlock(rhsBlock);
02824   eval.begin(*this);
02825   Optional<LValue> rhs =
02826       EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
02827   eval.end(*this);
02828   if (rhs && !rhs->isSimple())
02829     return EmitUnsupportedLValue(expr, "conditional operator");
02830   rhsBlock = Builder.GetInsertBlock();
02831 
02832   EmitBlock(contBlock);
02833 
02834   if (lhs && rhs) {
02835     llvm::PHINode *phi = Builder.CreatePHI(lhs->getAddress()->getType(),
02836                                            2, "cond-lvalue");
02837     phi->addIncoming(lhs->getAddress(), lhsBlock);
02838     phi->addIncoming(rhs->getAddress(), rhsBlock);
02839     return MakeAddrLValue(phi, expr->getType());
02840   } else {
02841     assert((lhs || rhs) &&
02842            "both operands of glvalue conditional are throw-expressions?");
02843     return lhs ? *lhs : *rhs;
02844   }
02845 }
02846 
02847 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
02848 /// type. If the cast is to a reference, we can have the usual lvalue result,
02849 /// otherwise if a cast is needed by the code generator in an lvalue context,
02850 /// then it must mean that we need the address of an aggregate in order to
02851 /// access one of its members.  This can happen for all the reasons that casts
02852 /// are permitted with aggregate result, including noop aggregate casts, and
02853 /// cast from scalar to union.
02854 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
02855   switch (E->getCastKind()) {
02856   case CK_ToVoid:
02857   case CK_BitCast:
02858   case CK_ArrayToPointerDecay:
02859   case CK_FunctionToPointerDecay:
02860   case CK_NullToMemberPointer:
02861   case CK_NullToPointer:
02862   case CK_IntegralToPointer:
02863   case CK_PointerToIntegral:
02864   case CK_PointerToBoolean:
02865   case CK_VectorSplat:
02866   case CK_IntegralCast:
02867   case CK_IntegralToBoolean:
02868   case CK_IntegralToFloating:
02869   case CK_FloatingToIntegral:
02870   case CK_FloatingToBoolean:
02871   case CK_FloatingCast:
02872   case CK_FloatingRealToComplex:
02873   case CK_FloatingComplexToReal:
02874   case CK_FloatingComplexToBoolean:
02875   case CK_FloatingComplexCast:
02876   case CK_FloatingComplexToIntegralComplex:
02877   case CK_IntegralRealToComplex:
02878   case CK_IntegralComplexToReal:
02879   case CK_IntegralComplexToBoolean:
02880   case CK_IntegralComplexCast:
02881   case CK_IntegralComplexToFloatingComplex:
02882   case CK_DerivedToBaseMemberPointer:
02883   case CK_BaseToDerivedMemberPointer:
02884   case CK_MemberPointerToBoolean:
02885   case CK_ReinterpretMemberPointer:
02886   case CK_AnyPointerToBlockPointerCast:
02887   case CK_ARCProduceObject:
02888   case CK_ARCConsumeObject:
02889   case CK_ARCReclaimReturnedObject:
02890   case CK_ARCExtendBlockObject:
02891   case CK_CopyAndAutoreleaseBlockObject:
02892   case CK_AddressSpaceConversion:
02893     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
02894 
02895   case CK_Dependent:
02896     llvm_unreachable("dependent cast kind in IR gen!");
02897 
02898   case CK_BuiltinFnToFnPtr:
02899     llvm_unreachable("builtin functions are handled elsewhere");
02900 
02901   // These are never l-values; just use the aggregate emission code.
02902   case CK_NonAtomicToAtomic:
02903   case CK_AtomicToNonAtomic:
02904     return EmitAggExprToLValue(E);
02905 
02906   case CK_Dynamic: {
02907     LValue LV = EmitLValue(E->getSubExpr());
02908     llvm::Value *V = LV.getAddress();
02909     const auto *DCE = cast<CXXDynamicCastExpr>(E);
02910     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
02911   }
02912 
02913   case CK_ConstructorConversion:
02914   case CK_UserDefinedConversion:
02915   case CK_CPointerToObjCPointerCast:
02916   case CK_BlockPointerToObjCPointerCast:
02917   case CK_NoOp:
02918   case CK_LValueToRValue:
02919     return EmitLValue(E->getSubExpr());
02920 
02921   case CK_UncheckedDerivedToBase:
02922   case CK_DerivedToBase: {
02923     const RecordType *DerivedClassTy =
02924       E->getSubExpr()->getType()->getAs<RecordType>();
02925     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
02926 
02927     LValue LV = EmitLValue(E->getSubExpr());
02928     llvm::Value *This = LV.getAddress();
02929 
02930     // Perform the derived-to-base conversion
02931     llvm::Value *Base = GetAddressOfBaseClass(
02932         This, DerivedClassDecl, E->path_begin(), E->path_end(),
02933         /*NullCheckValue=*/false, E->getExprLoc());
02934 
02935     return MakeAddrLValue(Base, E->getType());
02936   }
02937   case CK_ToUnion:
02938     return EmitAggExprToLValue(E);
02939   case CK_BaseToDerived: {
02940     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
02941     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
02942 
02943     LValue LV = EmitLValue(E->getSubExpr());
02944 
02945     // Perform the base-to-derived conversion
02946     llvm::Value *Derived =
02947       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
02948                                E->path_begin(), E->path_end(),
02949                                /*NullCheckValue=*/false);
02950 
02951     // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
02952     // performed and the object is not of the derived type.
02953     if (sanitizePerformTypeCheck())
02954       EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
02955                     Derived, E->getType());
02956 
02957     return MakeAddrLValue(Derived, E->getType());
02958   }
02959   case CK_LValueBitCast: {
02960     // This must be a reinterpret_cast (or c-style equivalent).
02961     const auto *CE = cast<ExplicitCastExpr>(E);
02962 
02963     LValue LV = EmitLValue(E->getSubExpr());
02964     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
02965                                            ConvertType(CE->getTypeAsWritten()));
02966     return MakeAddrLValue(V, E->getType());
02967   }
02968   case CK_ObjCObjectLValueCast: {
02969     LValue LV = EmitLValue(E->getSubExpr());
02970     QualType ToType = getContext().getLValueReferenceType(E->getType());
02971     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
02972                                            ConvertType(ToType));
02973     return MakeAddrLValue(V, E->getType());
02974   }
02975   case CK_ZeroToOCLEvent:
02976     llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
02977   }
02978 
02979   llvm_unreachable("Unhandled lvalue cast kind?");
02980 }
02981 
02982 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
02983   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
02984   return getOpaqueLValueMapping(e);
02985 }
02986 
02987 RValue CodeGenFunction::EmitRValueForField(LValue LV,
02988                                            const FieldDecl *FD,
02989                                            SourceLocation Loc) {
02990   QualType FT = FD->getType();
02991   LValue FieldLV = EmitLValueForField(LV, FD);
02992   switch (getEvaluationKind(FT)) {
02993   case TEK_Complex:
02994     return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
02995   case TEK_Aggregate:
02996     return FieldLV.asAggregateRValue();
02997   case TEK_Scalar:
02998     return EmitLoadOfLValue(FieldLV, Loc);
02999   }
03000   llvm_unreachable("bad evaluation kind");
03001 }
03002 
03003 //===--------------------------------------------------------------------===//
03004 //                             Expression Emission
03005 //===--------------------------------------------------------------------===//
03006 
03007 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
03008                                      ReturnValueSlot ReturnValue) {
03009   if (CGDebugInfo *DI = getDebugInfo()) {
03010     SourceLocation Loc = E->getLocStart();
03011     // Force column info to be generated so we can differentiate
03012     // multiple call sites on the same line in the debug info.
03013     // FIXME: This is insufficient. Two calls coming from the same macro
03014     // expansion will still get the same line/column and break debug info. It's
03015     // possible that LLVM can be fixed to not rely on this uniqueness, at which
03016     // point this workaround can be removed.
03017     const FunctionDecl* Callee = E->getDirectCallee();
03018     bool ForceColumnInfo = Callee && Callee->isInlineSpecified();
03019     DI->EmitLocation(Builder, Loc, ForceColumnInfo);
03020   }
03021 
03022   // Builtins never have block type.
03023   if (E->getCallee()->getType()->isBlockPointerType())
03024     return EmitBlockCallExpr(E, ReturnValue);
03025 
03026   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
03027     return EmitCXXMemberCallExpr(CE, ReturnValue);
03028 
03029   if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
03030     return EmitCUDAKernelCallExpr(CE, ReturnValue);
03031 
03032   const Decl *TargetDecl = E->getCalleeDecl();
03033   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
03034     if (unsigned builtinID = FD->getBuiltinID())
03035       return EmitBuiltinExpr(FD, builtinID, E);
03036   }
03037 
03038   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
03039     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
03040       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
03041 
03042   if (const auto *PseudoDtor =
03043           dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
03044     QualType DestroyedType = PseudoDtor->getDestroyedType();
03045     if (getLangOpts().ObjCAutoRefCount &&
03046         DestroyedType->isObjCLifetimeType() &&
03047         (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
03048          DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
03049       // Automatic Reference Counting:
03050       //   If the pseudo-expression names a retainable object with weak or
03051       //   strong lifetime, the object shall be released.
03052       Expr *BaseExpr = PseudoDtor->getBase();
03053       llvm::Value *BaseValue = nullptr;
03054       Qualifiers BaseQuals;
03055 
03056       // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
03057       if (PseudoDtor->isArrow()) {
03058         BaseValue = EmitScalarExpr(BaseExpr);
03059         const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
03060         BaseQuals = PTy->getPointeeType().getQualifiers();
03061       } else {
03062         LValue BaseLV = EmitLValue(BaseExpr);
03063         BaseValue = BaseLV.getAddress();
03064         QualType BaseTy = BaseExpr->getType();
03065         BaseQuals = BaseTy.getQualifiers();
03066       }
03067 
03068       switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
03069       case Qualifiers::OCL_None:
03070       case Qualifiers::OCL_ExplicitNone:
03071       case Qualifiers::OCL_Autoreleasing:
03072         break;
03073 
03074       case Qualifiers::OCL_Strong:
03075         EmitARCRelease(Builder.CreateLoad(BaseValue,
03076                           PseudoDtor->getDestroyedType().isVolatileQualified()),
03077                        ARCPreciseLifetime);
03078         break;
03079 
03080       case Qualifiers::OCL_Weak:
03081         EmitARCDestroyWeak(BaseValue);
03082         break;
03083       }
03084     } else {
03085       // C++ [expr.pseudo]p1:
03086       //   The result shall only be used as the operand for the function call
03087       //   operator (), and the result of such a call has type void. The only
03088       //   effect is the evaluation of the postfix-expression before the dot or
03089       //   arrow.
03090       EmitScalarExpr(E->getCallee());
03091     }
03092 
03093     return RValue::get(nullptr);
03094   }
03095 
03096   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
03097   return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
03098                   TargetDecl);
03099 }
03100 
03101 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
03102   // Comma expressions just emit their LHS then their RHS as an l-value.
03103   if (E->getOpcode() == BO_Comma) {
03104     EmitIgnoredExpr(E->getLHS());
03105     EnsureInsertPoint();
03106     return EmitLValue(E->getRHS());
03107   }
03108 
03109   if (E->getOpcode() == BO_PtrMemD ||
03110       E->getOpcode() == BO_PtrMemI)
03111     return EmitPointerToDataMemberBinaryExpr(E);
03112 
03113   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
03114 
03115   // Note that in all of these cases, __block variables need the RHS
03116   // evaluated first just in case the variable gets moved by the RHS.
03117 
03118   switch (getEvaluationKind(E->getType())) {
03119   case TEK_Scalar: {
03120     switch (E->getLHS()->getType().getObjCLifetime()) {
03121     case Qualifiers::OCL_Strong:
03122       return EmitARCStoreStrong(E, /*ignored*/ false).first;
03123 
03124     case Qualifiers::OCL_Autoreleasing:
03125       return EmitARCStoreAutoreleasing(E).first;
03126 
03127     // No reason to do any of these differently.
03128     case Qualifiers::OCL_None:
03129     case Qualifiers::OCL_ExplicitNone:
03130     case Qualifiers::OCL_Weak:
03131       break;
03132     }
03133 
03134     RValue RV = EmitAnyExpr(E->getRHS());
03135     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
03136     EmitStoreThroughLValue(RV, LV);
03137     return LV;
03138   }
03139 
03140   case TEK_Complex:
03141     return EmitComplexAssignmentLValue(E);
03142 
03143   case TEK_Aggregate:
03144     return EmitAggExprToLValue(E);
03145   }
03146   llvm_unreachable("bad evaluation kind");
03147 }
03148 
03149 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
03150   RValue RV = EmitCallExpr(E);
03151 
03152   if (!RV.isScalar())
03153     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
03154 
03155   assert(E->getCallReturnType()->isReferenceType() &&
03156          "Can't have a scalar return unless the return type is a "
03157          "reference type!");
03158 
03159   return MakeAddrLValue(RV.getScalarVal(), E->getType());
03160 }
03161 
03162 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
03163   // FIXME: This shouldn't require another copy.
03164   return EmitAggExprToLValue(E);
03165 }
03166 
03167 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
03168   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
03169          && "binding l-value to type which needs a temporary");
03170   AggValueSlot Slot = CreateAggTemp(E->getType());
03171   EmitCXXConstructExpr(E, Slot);
03172   return MakeAddrLValue(Slot.getAddr(), E->getType());
03173 }
03174 
03175 LValue
03176 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
03177   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
03178 }
03179 
03180 llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
03181   return Builder.CreateBitCast(CGM.GetAddrOfUuidDescriptor(E),
03182                                ConvertType(E->getType())->getPointerTo());
03183 }
03184 
03185 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
03186   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
03187 }
03188 
03189 LValue
03190 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
03191   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
03192   Slot.setExternallyDestructed();
03193   EmitAggExpr(E->getSubExpr(), Slot);
03194   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
03195   return MakeAddrLValue(Slot.getAddr(), E->getType());
03196 }
03197 
03198 LValue
03199 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
03200   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
03201   EmitLambdaExpr(E, Slot);
03202   return MakeAddrLValue(Slot.getAddr(), E->getType());
03203 }
03204 
03205 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
03206   RValue RV = EmitObjCMessageExpr(E);
03207 
03208   if (!RV.isScalar())
03209     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
03210 
03211   assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
03212          "Can't have a scalar return unless the return type is a "
03213          "reference type!");
03214 
03215   return MakeAddrLValue(RV.getScalarVal(), E->getType());
03216 }
03217 
03218 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
03219   llvm::Value *V =
03220     CGM.getObjCRuntime().GetSelector(*this, E->getSelector(), true);
03221   return MakeAddrLValue(V, E->getType());
03222 }
03223 
03224 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
03225                                              const ObjCIvarDecl *Ivar) {
03226   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
03227 }
03228 
03229 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
03230                                           llvm::Value *BaseValue,
03231                                           const ObjCIvarDecl *Ivar,
03232                                           unsigned CVRQualifiers) {
03233   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
03234                                                    Ivar, CVRQualifiers);
03235 }
03236 
03237 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
03238   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
03239   llvm::Value *BaseValue = nullptr;
03240   const Expr *BaseExpr = E->getBase();
03241   Qualifiers BaseQuals;
03242   QualType ObjectTy;
03243   if (E->isArrow()) {
03244     BaseValue = EmitScalarExpr(BaseExpr);
03245     ObjectTy = BaseExpr->getType()->getPointeeType();
03246     BaseQuals = ObjectTy.getQualifiers();
03247   } else {
03248     LValue BaseLV = EmitLValue(BaseExpr);
03249     // FIXME: this isn't right for bitfields.
03250     BaseValue = BaseLV.getAddress();
03251     ObjectTy = BaseExpr->getType();
03252     BaseQuals = ObjectTy.getQualifiers();
03253   }
03254 
03255   LValue LV =
03256     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
03257                       BaseQuals.getCVRQualifiers());
03258   setObjCGCLValueClass(getContext(), E, LV);
03259   return LV;
03260 }
03261 
03262 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
03263   // Can only get l-value for message expression returning aggregate type
03264   RValue RV = EmitAnyExprToTemp(E);
03265   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
03266 }
03267 
03268 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
03269                                  const CallExpr *E, ReturnValueSlot ReturnValue,
03270                                  const Decl *TargetDecl) {
03271   // Get the actual function type. The callee type will always be a pointer to
03272   // function type or a block pointer type.
03273   assert(CalleeType->isFunctionPointerType() &&
03274          "Call must have function pointer type!");
03275 
03276   CalleeType = getContext().getCanonicalType(CalleeType);
03277 
03278   const auto *FnType =
03279       cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
03280 
03281   // Force column info to differentiate multiple inlined call sites on
03282   // the same line, analoguous to EmitCallExpr.
03283   // FIXME: This is insufficient. Two calls coming from the same macro expansion
03284   // will still get the same line/column and break debug info. It's possible
03285   // that LLVM can be fixed to not rely on this uniqueness, at which point this
03286   // workaround can be removed.
03287   bool ForceColumnInfo = false;
03288   if (const FunctionDecl* FD = dyn_cast_or_null<const FunctionDecl>(TargetDecl))
03289     ForceColumnInfo = FD->isInlineSpecified();
03290 
03291   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
03292       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
03293     if (llvm::Constant *PrefixSig =
03294             CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
03295       SanitizerScope SanScope(this);
03296       llvm::Constant *FTRTTIConst =
03297           CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
03298       llvm::Type *PrefixStructTyElems[] = {
03299         PrefixSig->getType(),
03300         FTRTTIConst->getType()
03301       };
03302       llvm::StructType *PrefixStructTy = llvm::StructType::get(
03303           CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
03304 
03305       llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
03306           Callee, llvm::PointerType::getUnqual(PrefixStructTy));
03307       llvm::Value *CalleeSigPtr =
03308           Builder.CreateConstGEP2_32(CalleePrefixStruct, 0, 0);
03309       llvm::Value *CalleeSig = Builder.CreateLoad(CalleeSigPtr);
03310       llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
03311 
03312       llvm::BasicBlock *Cont = createBasicBlock("cont");
03313       llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
03314       Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
03315 
03316       EmitBlock(TypeCheck);
03317       llvm::Value *CalleeRTTIPtr =
03318           Builder.CreateConstGEP2_32(CalleePrefixStruct, 0, 1);
03319       llvm::Value *CalleeRTTI = Builder.CreateLoad(CalleeRTTIPtr);
03320       llvm::Value *CalleeRTTIMatch =
03321           Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
03322       llvm::Constant *StaticData[] = {
03323         EmitCheckSourceLocation(E->getLocStart()),
03324         EmitCheckTypeDescriptor(CalleeType)
03325       };
03326       EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
03327                 "function_type_mismatch", StaticData, Callee);
03328 
03329       Builder.CreateBr(Cont);
03330       EmitBlock(Cont);
03331     }
03332   }
03333 
03334   CallArgList Args;
03335   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arg_begin(),
03336                E->arg_end(), E->getDirectCallee(), /*ParamsToSkip*/ 0,
03337                ForceColumnInfo);
03338 
03339   const CGFunctionInfo &FnInfo =
03340     CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
03341 
03342   // C99 6.5.2.2p6:
03343   //   If the expression that denotes the called function has a type
03344   //   that does not include a prototype, [the default argument
03345   //   promotions are performed]. If the number of arguments does not
03346   //   equal the number of parameters, the behavior is undefined. If
03347   //   the function is defined with a type that includes a prototype,
03348   //   and either the prototype ends with an ellipsis (, ...) or the
03349   //   types of the arguments after promotion are not compatible with
03350   //   the types of the parameters, the behavior is undefined. If the
03351   //   function is defined with a type that does not include a
03352   //   prototype, and the types of the arguments after promotion are
03353   //   not compatible with those of the parameters after promotion,
03354   //   the behavior is undefined [except in some trivial cases].
03355   // That is, in the general case, we should assume that a call
03356   // through an unprototyped function type works like a *non-variadic*
03357   // call.  The way we make this work is to cast to the exact type
03358   // of the promoted arguments.
03359   if (isa<FunctionNoProtoType>(FnType)) {
03360     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
03361     CalleeTy = CalleeTy->getPointerTo();
03362     Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
03363   }
03364 
03365   return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
03366 }
03367 
03368 LValue CodeGenFunction::
03369 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
03370   llvm::Value *BaseV;
03371   if (E->getOpcode() == BO_PtrMemI)
03372     BaseV = EmitScalarExpr(E->getLHS());
03373   else
03374     BaseV = EmitLValue(E->getLHS()).getAddress();
03375 
03376   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
03377 
03378   const MemberPointerType *MPT
03379     = E->getRHS()->getType()->getAs<MemberPointerType>();
03380 
03381   llvm::Value *AddV = CGM.getCXXABI().EmitMemberDataPointerAddress(
03382       *this, E, BaseV, OffsetV, MPT);
03383 
03384   return MakeAddrLValue(AddV, MPT->getPointeeType());
03385 }
03386 
03387 /// Given the address of a temporary variable, produce an r-value of
03388 /// its type.
03389 RValue CodeGenFunction::convertTempToRValue(llvm::Value *addr,
03390                                             QualType type,
03391                                             SourceLocation loc) {
03392   LValue lvalue = MakeNaturalAlignAddrLValue(addr, type);
03393   switch (getEvaluationKind(type)) {
03394   case TEK_Complex:
03395     return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
03396   case TEK_Aggregate:
03397     return lvalue.asAggregateRValue();
03398   case TEK_Scalar:
03399     return RValue::get(EmitLoadOfScalar(lvalue, loc));
03400   }
03401   llvm_unreachable("bad evaluation kind");
03402 }
03403 
03404 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
03405   assert(Val->getType()->isFPOrFPVectorTy());
03406   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
03407     return;
03408 
03409   llvm::MDBuilder MDHelper(getLLVMContext());
03410   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
03411 
03412   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
03413 }
03414 
03415 namespace {
03416   struct LValueOrRValue {
03417     LValue LV;
03418     RValue RV;
03419   };
03420 }
03421 
03422 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
03423                                            const PseudoObjectExpr *E,
03424                                            bool forLValue,
03425                                            AggValueSlot slot) {
03426   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
03427 
03428   // Find the result expression, if any.
03429   const Expr *resultExpr = E->getResultExpr();
03430   LValueOrRValue result;
03431 
03432   for (PseudoObjectExpr::const_semantics_iterator
03433          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
03434     const Expr *semantic = *i;
03435 
03436     // If this semantic expression is an opaque value, bind it
03437     // to the result of its source expression.
03438     if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
03439 
03440       // If this is the result expression, we may need to evaluate
03441       // directly into the slot.
03442       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
03443       OVMA opaqueData;
03444       if (ov == resultExpr && ov->isRValue() && !forLValue &&
03445           CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
03446         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
03447 
03448         LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
03449         opaqueData = OVMA::bind(CGF, ov, LV);
03450         result.RV = slot.asRValue();
03451 
03452       // Otherwise, emit as normal.
03453       } else {
03454         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
03455 
03456         // If this is the result, also evaluate the result now.
03457         if (ov == resultExpr) {
03458           if (forLValue)
03459             result.LV = CGF.EmitLValue(ov);
03460           else
03461             result.RV = CGF.EmitAnyExpr(ov, slot);
03462         }
03463       }
03464 
03465       opaques.push_back(opaqueData);
03466 
03467     // Otherwise, if the expression is the result, evaluate it
03468     // and remember the result.
03469     } else if (semantic == resultExpr) {
03470       if (forLValue)
03471         result.LV = CGF.EmitLValue(semantic);
03472       else
03473         result.RV = CGF.EmitAnyExpr(semantic, slot);
03474 
03475     // Otherwise, evaluate the expression in an ignored context.
03476     } else {
03477       CGF.EmitIgnoredExpr(semantic);
03478     }
03479   }
03480 
03481   // Unbind all the opaques now.
03482   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
03483     opaques[i].unbind(CGF);
03484 
03485   return result;
03486 }
03487 
03488 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
03489                                                AggValueSlot slot) {
03490   return emitPseudoObjectExpr(*this, E, false, slot).RV;
03491 }
03492 
03493 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
03494   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
03495 }