1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGCXXABI.h" 15 #include "CGCall.h" 16 #include "CGCleanup.h" 17 #include "CGDebugInfo.h" 18 #include "CGObjCRuntime.h" 19 #include "CGOpenMPRuntime.h" 20 #include "CGRecordLayout.h" 21 #include "CodeGenFunction.h" 22 #include "CodeGenModule.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/Attr.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/AST/NSAPI.h" 28 #include "clang/Frontend/CodeGenOptions.h" 29 #include "llvm/ADT/Hashing.h" 30 #include "llvm/ADT/StringExtras.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/IR/LLVMContext.h" 34 #include "llvm/IR/MDBuilder.h" 35 #include "llvm/Support/ConvertUTF.h" 36 #include "llvm/Support/MathExtras.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Transforms/Utils/SanitizerStats.h" 39 40 #include <string> 41 42 using namespace clang; 43 using namespace CodeGen; 44 45 //===--------------------------------------------------------------------===// 46 // Miscellaneous Helper Methods 47 //===--------------------------------------------------------------------===// 48 49 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) { 50 unsigned addressSpace = 51 cast<llvm::PointerType>(value->getType())->getAddressSpace(); 52 53 llvm::PointerType *destType = Int8PtrTy; 54 if (addressSpace) 55 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace); 56 57 if (value->getType() == destType) return value; 58 return Builder.CreateBitCast(value, destType); 59 } 60 61 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 62 /// block. 63 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align, 64 const Twine &Name) { 65 auto Alloca = CreateTempAlloca(Ty, Name); 66 Alloca->setAlignment(Align.getQuantity()); 67 return Address(Alloca, Align); 68 } 69 70 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 71 /// block. 72 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, 73 const Twine &Name) { 74 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(), 75 nullptr, Name, AllocaInsertPt); 76 } 77 78 /// CreateDefaultAlignTempAlloca - This creates an alloca with the 79 /// default alignment of the corresponding LLVM type, which is *not* 80 /// guaranteed to be related in any way to the expected alignment of 81 /// an AST type that might have been lowered to Ty. 82 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty, 83 const Twine &Name) { 84 CharUnits Align = 85 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty)); 86 return CreateTempAlloca(Ty, Align, Name); 87 } 88 89 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) { 90 assert(isa<llvm::AllocaInst>(Var.getPointer())); 91 auto *Store = new llvm::StoreInst(Init, Var.getPointer()); 92 Store->setAlignment(Var.getAlignment().getQuantity()); 93 llvm::BasicBlock *Block = AllocaInsertPt->getParent(); 94 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store); 95 } 96 97 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) { 98 CharUnits Align = getContext().getTypeAlignInChars(Ty); 99 return CreateTempAlloca(ConvertType(Ty), Align, Name); 100 } 101 102 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) { 103 // FIXME: Should we prefer the preferred type alignment here? 104 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name); 105 } 106 107 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align, 108 const Twine &Name) { 109 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name); 110 } 111 112 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 113 /// expression and compare the result against zero, returning an Int1Ty value. 114 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 115 PGO.setCurrentStmt(E); 116 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) { 117 llvm::Value *MemPtr = EmitScalarExpr(E); 118 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT); 119 } 120 121 QualType BoolTy = getContext().BoolTy; 122 SourceLocation Loc = E->getExprLoc(); 123 if (!E->getType()->isAnyComplexType()) 124 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc); 125 126 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy, 127 Loc); 128 } 129 130 /// EmitIgnoredExpr - Emit code to compute the specified expression, 131 /// ignoring the result. 132 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) { 133 if (E->isRValue()) 134 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true); 135 136 // Just emit it as an l-value and drop the result. 137 EmitLValue(E); 138 } 139 140 /// EmitAnyExpr - Emit code to compute the specified expression which 141 /// can have any type. The result is returned as an RValue struct. 142 /// If this is an aggregate expression, AggSlot indicates where the 143 /// result should be returned. 144 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, 145 AggValueSlot aggSlot, 146 bool ignoreResult) { 147 switch (getEvaluationKind(E->getType())) { 148 case TEK_Scalar: 149 return RValue::get(EmitScalarExpr(E, ignoreResult)); 150 case TEK_Complex: 151 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult)); 152 case TEK_Aggregate: 153 if (!ignoreResult && aggSlot.isIgnored()) 154 aggSlot = CreateAggTemp(E->getType(), "agg-temp"); 155 EmitAggExpr(E, aggSlot); 156 return aggSlot.asRValue(); 157 } 158 llvm_unreachable("bad evaluation kind"); 159 } 160 161 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 162 /// always be accessible even if no aggregate location is provided. 163 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) { 164 AggValueSlot AggSlot = AggValueSlot::ignored(); 165 166 if (hasAggregateEvaluationKind(E->getType())) 167 AggSlot = CreateAggTemp(E->getType(), "agg.tmp"); 168 return EmitAnyExpr(E, AggSlot); 169 } 170 171 /// EmitAnyExprToMem - Evaluate an expression into a given memory 172 /// location. 173 void CodeGenFunction::EmitAnyExprToMem(const Expr *E, 174 Address Location, 175 Qualifiers Quals, 176 bool IsInit) { 177 // FIXME: This function should take an LValue as an argument. 178 switch (getEvaluationKind(E->getType())) { 179 case TEK_Complex: 180 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()), 181 /*isInit*/ false); 182 return; 183 184 case TEK_Aggregate: { 185 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals, 186 AggValueSlot::IsDestructed_t(IsInit), 187 AggValueSlot::DoesNotNeedGCBarriers, 188 AggValueSlot::IsAliased_t(!IsInit))); 189 return; 190 } 191 192 case TEK_Scalar: { 193 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false)); 194 LValue LV = MakeAddrLValue(Location, E->getType()); 195 EmitStoreThroughLValue(RV, LV); 196 return; 197 } 198 } 199 llvm_unreachable("bad evaluation kind"); 200 } 201 202 static void 203 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, 204 const Expr *E, Address ReferenceTemporary) { 205 // Objective-C++ ARC: 206 // If we are binding a reference to a temporary that has ownership, we 207 // need to perform retain/release operations on the temporary. 208 // 209 // FIXME: This should be looking at E, not M. 210 if (auto Lifetime = M->getType().getObjCLifetime()) { 211 switch (Lifetime) { 212 case Qualifiers::OCL_None: 213 case Qualifiers::OCL_ExplicitNone: 214 // Carry on to normal cleanup handling. 215 break; 216 217 case Qualifiers::OCL_Autoreleasing: 218 // Nothing to do; cleaned up by an autorelease pool. 219 return; 220 221 case Qualifiers::OCL_Strong: 222 case Qualifiers::OCL_Weak: 223 switch (StorageDuration Duration = M->getStorageDuration()) { 224 case SD_Static: 225 // Note: we intentionally do not register a cleanup to release 226 // the object on program termination. 227 return; 228 229 case SD_Thread: 230 // FIXME: We should probably register a cleanup in this case. 231 return; 232 233 case SD_Automatic: 234 case SD_FullExpression: 235 CodeGenFunction::Destroyer *Destroy; 236 CleanupKind CleanupKind; 237 if (Lifetime == Qualifiers::OCL_Strong) { 238 const ValueDecl *VD = M->getExtendingDecl(); 239 bool Precise = 240 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>(); 241 CleanupKind = CGF.getARCCleanupKind(); 242 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise 243 : &CodeGenFunction::destroyARCStrongImprecise; 244 } else { 245 // __weak objects always get EH cleanups; otherwise, exceptions 246 // could cause really nasty crashes instead of mere leaks. 247 CleanupKind = NormalAndEHCleanup; 248 Destroy = &CodeGenFunction::destroyARCWeak; 249 } 250 if (Duration == SD_FullExpression) 251 CGF.pushDestroy(CleanupKind, ReferenceTemporary, 252 M->getType(), *Destroy, 253 CleanupKind & EHCleanup); 254 else 255 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary, 256 M->getType(), 257 *Destroy, CleanupKind & EHCleanup); 258 return; 259 260 case SD_Dynamic: 261 llvm_unreachable("temporary cannot have dynamic storage duration"); 262 } 263 llvm_unreachable("unknown storage duration"); 264 } 265 } 266 267 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr; 268 if (const RecordType *RT = 269 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 270 // Get the destructor for the reference temporary. 271 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 272 if (!ClassDecl->hasTrivialDestructor()) 273 ReferenceTemporaryDtor = ClassDecl->getDestructor(); 274 } 275 276 if (!ReferenceTemporaryDtor) 277 return; 278 279 // Call the destructor for the temporary. 280 switch (M->getStorageDuration()) { 281 case SD_Static: 282 case SD_Thread: { 283 llvm::Constant *CleanupFn; 284 llvm::Constant *CleanupArg; 285 if (E->getType()->isArrayType()) { 286 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper( 287 ReferenceTemporary, E->getType(), 288 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions, 289 dyn_cast_or_null<VarDecl>(M->getExtendingDecl())); 290 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy); 291 } else { 292 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor, 293 StructorType::Complete); 294 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer()); 295 } 296 CGF.CGM.getCXXABI().registerGlobalDtor( 297 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg); 298 break; 299 } 300 301 case SD_FullExpression: 302 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(), 303 CodeGenFunction::destroyCXXObject, 304 CGF.getLangOpts().Exceptions); 305 break; 306 307 case SD_Automatic: 308 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup, 309 ReferenceTemporary, E->getType(), 310 CodeGenFunction::destroyCXXObject, 311 CGF.getLangOpts().Exceptions); 312 break; 313 314 case SD_Dynamic: 315 llvm_unreachable("temporary cannot have dynamic storage duration"); 316 } 317 } 318 319 static Address 320 createReferenceTemporary(CodeGenFunction &CGF, 321 const MaterializeTemporaryExpr *M, const Expr *Inner) { 322 switch (M->getStorageDuration()) { 323 case SD_FullExpression: 324 case SD_Automatic: { 325 // If we have a constant temporary array or record try to promote it into a 326 // constant global under the same rules a normal constant would've been 327 // promoted. This is easier on the optimizer and generally emits fewer 328 // instructions. 329 QualType Ty = Inner->getType(); 330 if (CGF.CGM.getCodeGenOpts().MergeAllConstants && 331 (Ty->isArrayType() || Ty->isRecordType()) && 332 CGF.CGM.isTypeConstant(Ty, true)) 333 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) { 334 auto *GV = new llvm::GlobalVariable( 335 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true, 336 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp"); 337 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty); 338 GV->setAlignment(alignment.getQuantity()); 339 // FIXME: Should we put the new global into a COMDAT? 340 return Address(GV, alignment); 341 } 342 return CGF.CreateMemTemp(Ty, "ref.tmp"); 343 } 344 case SD_Thread: 345 case SD_Static: 346 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner); 347 348 case SD_Dynamic: 349 llvm_unreachable("temporary can't have dynamic storage duration"); 350 } 351 llvm_unreachable("unknown storage duration"); 352 } 353 354 LValue CodeGenFunction:: 355 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) { 356 const Expr *E = M->GetTemporaryExpr(); 357 358 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so 359 // as that will cause the lifetime adjustment to be lost for ARC 360 auto ownership = M->getType().getObjCLifetime(); 361 if (ownership != Qualifiers::OCL_None && 362 ownership != Qualifiers::OCL_ExplicitNone) { 363 Address Object = createReferenceTemporary(*this, M, E); 364 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) { 365 Object = Address(llvm::ConstantExpr::getBitCast(Var, 366 ConvertTypeForMem(E->getType()) 367 ->getPointerTo(Object.getAddressSpace())), 368 Object.getAlignment()); 369 370 // createReferenceTemporary will promote the temporary to a global with a 371 // constant initializer if it can. It can only do this to a value of 372 // ARC-manageable type if the value is global and therefore "immune" to 373 // ref-counting operations. Therefore we have no need to emit either a 374 // dynamic initialization or a cleanup and we can just return the address 375 // of the temporary. 376 if (Var->hasInitializer()) 377 return MakeAddrLValue(Object, M->getType(), 378 LValueBaseInfo(AlignmentSource::Decl, false)); 379 380 Var->setInitializer(CGM.EmitNullConstant(E->getType())); 381 } 382 LValue RefTempDst = MakeAddrLValue(Object, M->getType(), 383 LValueBaseInfo(AlignmentSource::Decl, 384 false)); 385 386 switch (getEvaluationKind(E->getType())) { 387 default: llvm_unreachable("expected scalar or aggregate expression"); 388 case TEK_Scalar: 389 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false); 390 break; 391 case TEK_Aggregate: { 392 EmitAggExpr(E, AggValueSlot::forAddr(Object, 393 E->getType().getQualifiers(), 394 AggValueSlot::IsDestructed, 395 AggValueSlot::DoesNotNeedGCBarriers, 396 AggValueSlot::IsNotAliased)); 397 break; 398 } 399 } 400 401 pushTemporaryCleanup(*this, M, E, Object); 402 return RefTempDst; 403 } 404 405 SmallVector<const Expr *, 2> CommaLHSs; 406 SmallVector<SubobjectAdjustment, 2> Adjustments; 407 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 408 409 for (const auto &Ignored : CommaLHSs) 410 EmitIgnoredExpr(Ignored); 411 412 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) { 413 if (opaque->getType()->isRecordType()) { 414 assert(Adjustments.empty()); 415 return EmitOpaqueValueLValue(opaque); 416 } 417 } 418 419 // Create and initialize the reference temporary. 420 Address Object = createReferenceTemporary(*this, M, E); 421 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) { 422 Object = Address(llvm::ConstantExpr::getBitCast( 423 Var, ConvertTypeForMem(E->getType())->getPointerTo()), 424 Object.getAlignment()); 425 // If the temporary is a global and has a constant initializer or is a 426 // constant temporary that we promoted to a global, we may have already 427 // initialized it. 428 if (!Var->hasInitializer()) { 429 Var->setInitializer(CGM.EmitNullConstant(E->getType())); 430 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true); 431 } 432 } else { 433 switch (M->getStorageDuration()) { 434 case SD_Automatic: 435 case SD_FullExpression: 436 if (auto *Size = EmitLifetimeStart( 437 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()), 438 Object.getPointer())) { 439 if (M->getStorageDuration() == SD_Automatic) 440 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker, 441 Object, Size); 442 else 443 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object, 444 Size); 445 } 446 break; 447 default: 448 break; 449 } 450 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true); 451 } 452 pushTemporaryCleanup(*this, M, E, Object); 453 454 // Perform derived-to-base casts and/or field accesses, to get from the 455 // temporary object we created (and, potentially, for which we extended 456 // the lifetime) to the subobject we're binding the reference to. 457 for (unsigned I = Adjustments.size(); I != 0; --I) { 458 SubobjectAdjustment &Adjustment = Adjustments[I-1]; 459 switch (Adjustment.Kind) { 460 case SubobjectAdjustment::DerivedToBaseAdjustment: 461 Object = 462 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass, 463 Adjustment.DerivedToBase.BasePath->path_begin(), 464 Adjustment.DerivedToBase.BasePath->path_end(), 465 /*NullCheckValue=*/ false, E->getExprLoc()); 466 break; 467 468 case SubobjectAdjustment::FieldAdjustment: { 469 LValue LV = MakeAddrLValue(Object, E->getType(), 470 LValueBaseInfo(AlignmentSource::Decl, false)); 471 LV = EmitLValueForField(LV, Adjustment.Field); 472 assert(LV.isSimple() && 473 "materialized temporary field is not a simple lvalue"); 474 Object = LV.getAddress(); 475 break; 476 } 477 478 case SubobjectAdjustment::MemberPointerAdjustment: { 479 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS); 480 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr, 481 Adjustment.Ptr.MPT); 482 break; 483 } 484 } 485 } 486 487 return MakeAddrLValue(Object, M->getType(), 488 LValueBaseInfo(AlignmentSource::Decl, false)); 489 } 490 491 RValue 492 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) { 493 // Emit the expression as an lvalue. 494 LValue LV = EmitLValue(E); 495 assert(LV.isSimple()); 496 llvm::Value *Value = LV.getPointer(); 497 498 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) { 499 // C++11 [dcl.ref]p5 (as amended by core issue 453): 500 // If a glvalue to which a reference is directly bound designates neither 501 // an existing object or function of an appropriate type nor a region of 502 // storage of suitable size and alignment to contain an object of the 503 // reference's type, the behavior is undefined. 504 QualType Ty = E->getType(); 505 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty); 506 } 507 508 return RValue::get(Value); 509 } 510 511 512 /// getAccessedFieldNo - Given an encoded value and a result number, return the 513 /// input field number being accessed. 514 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 515 const llvm::Constant *Elts) { 516 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx)) 517 ->getZExtValue(); 518 } 519 520 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h. 521 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low, 522 llvm::Value *High) { 523 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL); 524 llvm::Value *K47 = Builder.getInt64(47); 525 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul); 526 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0); 527 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul); 528 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0); 529 return Builder.CreateMul(B1, KMul); 530 } 531 532 bool CodeGenFunction::sanitizePerformTypeCheck() const { 533 return SanOpts.has(SanitizerKind::Null) | 534 SanOpts.has(SanitizerKind::Alignment) | 535 SanOpts.has(SanitizerKind::ObjectSize) | 536 SanOpts.has(SanitizerKind::Vptr); 537 } 538 539 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, 540 llvm::Value *Ptr, QualType Ty, 541 CharUnits Alignment, 542 SanitizerSet SkippedChecks) { 543 if (!sanitizePerformTypeCheck()) 544 return; 545 546 // Don't check pointers outside the default address space. The null check 547 // isn't correct, the object-size check isn't supported by LLVM, and we can't 548 // communicate the addresses to the runtime handler for the vptr check. 549 if (Ptr->getType()->getPointerAddressSpace()) 550 return; 551 552 // Don't check pointers to volatile data. The behavior here is implementation- 553 // defined. 554 if (Ty.isVolatileQualified()) 555 return; 556 557 SanitizerScope SanScope(this); 558 559 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks; 560 llvm::BasicBlock *Done = nullptr; 561 562 // Quickly determine whether we have a pointer to an alloca. It's possible 563 // to skip null checks, and some alignment checks, for these pointers. This 564 // can reduce compile-time significantly. 565 auto PtrToAlloca = 566 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases()); 567 568 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast || 569 TCK == TCK_UpcastToVirtualBase; 570 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) && 571 !SkippedChecks.has(SanitizerKind::Null) && !PtrToAlloca) { 572 // The glvalue must not be an empty glvalue. 573 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr); 574 575 // The IR builder can constant-fold the null check if the pointer points to 576 // a constant. 577 bool PtrIsNonNull = 578 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext()); 579 580 // Skip the null check if the pointer is known to be non-null. 581 if (!PtrIsNonNull) { 582 if (AllowNullPointers) { 583 // When performing pointer casts, it's OK if the value is null. 584 // Skip the remaining checks in that case. 585 Done = createBasicBlock("null"); 586 llvm::BasicBlock *Rest = createBasicBlock("not.null"); 587 Builder.CreateCondBr(IsNonNull, Rest, Done); 588 EmitBlock(Rest); 589 } else { 590 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null)); 591 } 592 } 593 } 594 595 if (SanOpts.has(SanitizerKind::ObjectSize) && 596 !SkippedChecks.has(SanitizerKind::ObjectSize) && 597 !Ty->isIncompleteType()) { 598 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity(); 599 600 // The glvalue must refer to a large enough storage region. 601 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation 602 // to check this. 603 // FIXME: Get object address space 604 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy }; 605 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys); 606 llvm::Value *Min = Builder.getFalse(); 607 llvm::Value *NullIsUnknown = Builder.getFalse(); 608 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy); 609 llvm::Value *LargeEnough = Builder.CreateICmpUGE( 610 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}), 611 llvm::ConstantInt::get(IntPtrTy, Size)); 612 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize)); 613 } 614 615 uint64_t AlignVal = 0; 616 617 if (SanOpts.has(SanitizerKind::Alignment) && 618 !SkippedChecks.has(SanitizerKind::Alignment)) { 619 AlignVal = Alignment.getQuantity(); 620 if (!Ty->isIncompleteType() && !AlignVal) 621 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity(); 622 623 // The glvalue must be suitably aligned. 624 if (AlignVal > 1 && 625 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) { 626 llvm::Value *Align = 627 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy), 628 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1)); 629 llvm::Value *Aligned = 630 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0)); 631 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment)); 632 } 633 } 634 635 if (Checks.size() > 0) { 636 // Make sure we're not losing information. Alignment needs to be a power of 637 // 2 638 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal); 639 llvm::Constant *StaticData[] = { 640 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty), 641 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1), 642 llvm::ConstantInt::get(Int8Ty, TCK)}; 643 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr); 644 } 645 646 // If possible, check that the vptr indicates that there is a subobject of 647 // type Ty at offset zero within this object. 648 // 649 // C++11 [basic.life]p5,6: 650 // [For storage which does not refer to an object within its lifetime] 651 // The program has undefined behavior if: 652 // -- the [pointer or glvalue] is used to access a non-static data member 653 // or call a non-static member function 654 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 655 if (SanOpts.has(SanitizerKind::Vptr) && 656 !SkippedChecks.has(SanitizerKind::Vptr) && 657 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall || 658 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference || 659 TCK == TCK_UpcastToVirtualBase) && 660 RD && RD->hasDefinition() && RD->isDynamicClass()) { 661 // Compute a hash of the mangled name of the type. 662 // 663 // FIXME: This is not guaranteed to be deterministic! Move to a 664 // fingerprinting mechanism once LLVM provides one. For the time 665 // being the implementation happens to be deterministic. 666 SmallString<64> MangledName; 667 llvm::raw_svector_ostream Out(MangledName); 668 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(), 669 Out); 670 671 // Blacklist based on the mangled type. 672 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType( 673 Out.str())) { 674 llvm::hash_code TypeHash = hash_value(Out.str()); 675 676 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr). 677 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash); 678 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0); 679 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign()); 680 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr); 681 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty); 682 683 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High); 684 Hash = Builder.CreateTrunc(Hash, IntPtrTy); 685 686 // Look the hash up in our cache. 687 const int CacheSize = 128; 688 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize); 689 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable, 690 "__ubsan_vptr_type_cache"); 691 llvm::Value *Slot = Builder.CreateAnd(Hash, 692 llvm::ConstantInt::get(IntPtrTy, 693 CacheSize-1)); 694 llvm::Value *Indices[] = { Builder.getInt32(0), Slot }; 695 llvm::Value *CacheVal = 696 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices), 697 getPointerAlign()); 698 699 // If the hash isn't in the cache, call a runtime handler to perform the 700 // hard work of checking whether the vptr is for an object of the right 701 // type. This will either fill in the cache and return, or produce a 702 // diagnostic. 703 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash); 704 llvm::Constant *StaticData[] = { 705 EmitCheckSourceLocation(Loc), 706 EmitCheckTypeDescriptor(Ty), 707 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()), 708 llvm::ConstantInt::get(Int8Ty, TCK) 709 }; 710 llvm::Value *DynamicData[] = { Ptr, Hash }; 711 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr), 712 SanitizerHandler::DynamicTypeCacheMiss, StaticData, 713 DynamicData); 714 } 715 } 716 717 if (Done) { 718 Builder.CreateBr(Done); 719 EmitBlock(Done); 720 } 721 } 722 723 /// Determine whether this expression refers to a flexible array member in a 724 /// struct. We disable array bounds checks for such members. 725 static bool isFlexibleArrayMemberExpr(const Expr *E) { 726 // For compatibility with existing code, we treat arrays of length 0 or 727 // 1 as flexible array members. 728 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe(); 729 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 730 if (CAT->getSize().ugt(1)) 731 return false; 732 } else if (!isa<IncompleteArrayType>(AT)) 733 return false; 734 735 E = E->IgnoreParens(); 736 737 // A flexible array member must be the last member in the class. 738 if (const auto *ME = dyn_cast<MemberExpr>(E)) { 739 // FIXME: If the base type of the member expr is not FD->getParent(), 740 // this should not be treated as a flexible array member access. 741 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 742 RecordDecl::field_iterator FI( 743 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD))); 744 return ++FI == FD->getParent()->field_end(); 745 } 746 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) { 747 return IRE->getDecl()->getNextIvar() == nullptr; 748 } 749 750 return false; 751 } 752 753 /// If Base is known to point to the start of an array, return the length of 754 /// that array. Return 0 if the length cannot be determined. 755 static llvm::Value *getArrayIndexingBound( 756 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) { 757 // For the vector indexing extension, the bound is the number of elements. 758 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) { 759 IndexedType = Base->getType(); 760 return CGF.Builder.getInt32(VT->getNumElements()); 761 } 762 763 Base = Base->IgnoreParens(); 764 765 if (const auto *CE = dyn_cast<CastExpr>(Base)) { 766 if (CE->getCastKind() == CK_ArrayToPointerDecay && 767 !isFlexibleArrayMemberExpr(CE->getSubExpr())) { 768 IndexedType = CE->getSubExpr()->getType(); 769 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe(); 770 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 771 return CGF.Builder.getInt(CAT->getSize()); 772 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) 773 return CGF.getVLASize(VAT).first; 774 } 775 } 776 777 return nullptr; 778 } 779 780 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base, 781 llvm::Value *Index, QualType IndexType, 782 bool Accessed) { 783 assert(SanOpts.has(SanitizerKind::ArrayBounds) && 784 "should not be called unless adding bounds checks"); 785 SanitizerScope SanScope(this); 786 787 QualType IndexedType; 788 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType); 789 if (!Bound) 790 return; 791 792 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType(); 793 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned); 794 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false); 795 796 llvm::Constant *StaticData[] = { 797 EmitCheckSourceLocation(E->getExprLoc()), 798 EmitCheckTypeDescriptor(IndexedType), 799 EmitCheckTypeDescriptor(IndexType) 800 }; 801 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal) 802 : Builder.CreateICmpULE(IndexVal, BoundVal); 803 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), 804 SanitizerHandler::OutOfBounds, StaticData, Index); 805 } 806 807 808 CodeGenFunction::ComplexPairTy CodeGenFunction:: 809 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 810 bool isInc, bool isPre) { 811 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc()); 812 813 llvm::Value *NextVal; 814 if (isa<llvm::IntegerType>(InVal.first->getType())) { 815 uint64_t AmountVal = isInc ? 1 : -1; 816 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true); 817 818 // Add the inc/dec to the real part. 819 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 820 } else { 821 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType(); 822 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1); 823 if (!isInc) 824 FVal.changeSign(); 825 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal); 826 827 // Add the inc/dec to the real part. 828 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 829 } 830 831 ComplexPairTy IncVal(NextVal, InVal.second); 832 833 // Store the updated result through the lvalue. 834 EmitStoreOfComplex(IncVal, LV, /*init*/ false); 835 836 // If this is a postinc, return the value read from memory, otherwise use the 837 // updated value. 838 return isPre ? IncVal : InVal; 839 } 840 841 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E, 842 CodeGenFunction *CGF) { 843 // Bind VLAs in the cast type. 844 if (CGF && E->getType()->isVariablyModifiedType()) 845 CGF->EmitVariablyModifiedType(E->getType()); 846 847 if (CGDebugInfo *DI = getModuleDebugInfo()) 848 DI->EmitExplicitCastType(E->getType()); 849 } 850 851 //===----------------------------------------------------------------------===// 852 // LValue Expression Emission 853 //===----------------------------------------------------------------------===// 854 855 /// EmitPointerWithAlignment - Given an expression of pointer type, try to 856 /// derive a more accurate bound on the alignment of the pointer. 857 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E, 858 LValueBaseInfo *BaseInfo) { 859 // We allow this with ObjC object pointers because of fragile ABIs. 860 assert(E->getType()->isPointerType() || 861 E->getType()->isObjCObjectPointerType()); 862 E = E->IgnoreParens(); 863 864 // Casts: 865 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 866 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE)) 867 CGM.EmitExplicitCastExprType(ECE, this); 868 869 switch (CE->getCastKind()) { 870 // Non-converting casts (but not C's implicit conversion from void*). 871 case CK_BitCast: 872 case CK_NoOp: 873 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) { 874 if (PtrTy->getPointeeType()->isVoidType()) 875 break; 876 877 LValueBaseInfo InnerInfo; 878 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo); 879 if (BaseInfo) *BaseInfo = InnerInfo; 880 881 // If this is an explicit bitcast, and the source l-value is 882 // opaque, honor the alignment of the casted-to type. 883 if (isa<ExplicitCastExpr>(CE) && 884 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) { 885 LValueBaseInfo ExpInfo; 886 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), 887 &ExpInfo); 888 if (BaseInfo) 889 BaseInfo->mergeForCast(ExpInfo); 890 Addr = Address(Addr.getPointer(), Align); 891 } 892 893 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) && 894 CE->getCastKind() == CK_BitCast) { 895 if (auto PT = E->getType()->getAs<PointerType>()) 896 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(), 897 /*MayBeNull=*/true, 898 CodeGenFunction::CFITCK_UnrelatedCast, 899 CE->getLocStart()); 900 } 901 902 return Builder.CreateBitCast(Addr, ConvertType(E->getType())); 903 } 904 break; 905 906 // Array-to-pointer decay. 907 case CK_ArrayToPointerDecay: 908 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo); 909 910 // Derived-to-base conversions. 911 case CK_UncheckedDerivedToBase: 912 case CK_DerivedToBase: { 913 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo); 914 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl(); 915 return GetAddressOfBaseClass(Addr, Derived, 916 CE->path_begin(), CE->path_end(), 917 ShouldNullCheckClassCastValue(CE), 918 CE->getExprLoc()); 919 } 920 921 // TODO: Is there any reason to treat base-to-derived conversions 922 // specially? 923 default: 924 break; 925 } 926 } 927 928 // Unary &. 929 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 930 if (UO->getOpcode() == UO_AddrOf) { 931 LValue LV = EmitLValue(UO->getSubExpr()); 932 if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 933 return LV.getAddress(); 934 } 935 } 936 937 // TODO: conditional operators, comma. 938 939 // Otherwise, use the alignment of the type. 940 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo); 941 return Address(EmitScalarExpr(E), Align); 942 } 943 944 RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 945 if (Ty->isVoidType()) 946 return RValue::get(nullptr); 947 948 switch (getEvaluationKind(Ty)) { 949 case TEK_Complex: { 950 llvm::Type *EltTy = 951 ConvertType(Ty->castAs<ComplexType>()->getElementType()); 952 llvm::Value *U = llvm::UndefValue::get(EltTy); 953 return RValue::getComplex(std::make_pair(U, U)); 954 } 955 956 // If this is a use of an undefined aggregate type, the aggregate must have an 957 // identifiable address. Just because the contents of the value are undefined 958 // doesn't mean that the address can't be taken and compared. 959 case TEK_Aggregate: { 960 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp"); 961 return RValue::getAggregate(DestPtr); 962 } 963 964 case TEK_Scalar: 965 return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 966 } 967 llvm_unreachable("bad evaluation kind"); 968 } 969 970 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 971 const char *Name) { 972 ErrorUnsupported(E, Name); 973 return GetUndefRValue(E->getType()); 974 } 975 976 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 977 const char *Name) { 978 ErrorUnsupported(E, Name); 979 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 980 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()), 981 E->getType()); 982 } 983 984 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) { 985 const Expr *Base = Obj; 986 while (!isa<CXXThisExpr>(Base)) { 987 // The result of a dynamic_cast can be null. 988 if (isa<CXXDynamicCastExpr>(Base)) 989 return false; 990 991 if (const auto *CE = dyn_cast<CastExpr>(Base)) { 992 Base = CE->getSubExpr(); 993 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) { 994 Base = PE->getSubExpr(); 995 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) { 996 if (UO->getOpcode() == UO_Extension) 997 Base = UO->getSubExpr(); 998 else 999 return false; 1000 } else { 1001 return false; 1002 } 1003 } 1004 return true; 1005 } 1006 1007 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) { 1008 LValue LV; 1009 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E)) 1010 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true); 1011 else 1012 LV = EmitLValue(E); 1013 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) { 1014 SanitizerSet SkippedChecks; 1015 if (const auto *ME = dyn_cast<MemberExpr>(E)) { 1016 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase()); 1017 if (IsBaseCXXThis) 1018 SkippedChecks.set(SanitizerKind::Alignment, true); 1019 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase())) 1020 SkippedChecks.set(SanitizerKind::Null, true); 1021 } 1022 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(), 1023 E->getType(), LV.getAlignment(), SkippedChecks); 1024 } 1025 return LV; 1026 } 1027 1028 /// EmitLValue - Emit code to compute a designator that specifies the location 1029 /// of the expression. 1030 /// 1031 /// This can return one of two things: a simple address or a bitfield reference. 1032 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be 1033 /// an LLVM pointer type. 1034 /// 1035 /// If this returns a bitfield reference, nothing about the pointee type of the 1036 /// LLVM value is known: For example, it may not be a pointer to an integer. 1037 /// 1038 /// If this returns a normal address, and if the lvalue's C type is fixed size, 1039 /// this method guarantees that the returned pointer type will point to an LLVM 1040 /// type of the same size of the lvalue's type. If the lvalue has a variable 1041 /// length type, this is not possible. 1042 /// 1043 LValue CodeGenFunction::EmitLValue(const Expr *E) { 1044 ApplyDebugLocation DL(*this, E); 1045 switch (E->getStmtClass()) { 1046 default: return EmitUnsupportedLValue(E, "l-value expression"); 1047 1048 case Expr::ObjCPropertyRefExprClass: 1049 llvm_unreachable("cannot emit a property reference directly"); 1050 1051 case Expr::ObjCSelectorExprClass: 1052 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E)); 1053 case Expr::ObjCIsaExprClass: 1054 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E)); 1055 case Expr::BinaryOperatorClass: 1056 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 1057 case Expr::CompoundAssignOperatorClass: { 1058 QualType Ty = E->getType(); 1059 if (const AtomicType *AT = Ty->getAs<AtomicType>()) 1060 Ty = AT->getValueType(); 1061 if (!Ty->isAnyComplexType()) 1062 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 1063 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 1064 } 1065 case Expr::CallExprClass: 1066 case Expr::CXXMemberCallExprClass: 1067 case Expr::CXXOperatorCallExprClass: 1068 case Expr::UserDefinedLiteralClass: 1069 return EmitCallExprLValue(cast<CallExpr>(E)); 1070 case Expr::VAArgExprClass: 1071 return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 1072 case Expr::DeclRefExprClass: 1073 return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 1074 case Expr::ParenExprClass: 1075 return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 1076 case Expr::GenericSelectionExprClass: 1077 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr()); 1078 case Expr::PredefinedExprClass: 1079 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 1080 case Expr::StringLiteralClass: 1081 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 1082 case Expr::ObjCEncodeExprClass: 1083 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 1084 case Expr::PseudoObjectExprClass: 1085 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E)); 1086 case Expr::InitListExprClass: 1087 return EmitInitListLValue(cast<InitListExpr>(E)); 1088 case Expr::CXXTemporaryObjectExprClass: 1089 case Expr::CXXConstructExprClass: 1090 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 1091 case Expr::CXXBindTemporaryExprClass: 1092 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 1093 case Expr::CXXUuidofExprClass: 1094 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E)); 1095 case Expr::LambdaExprClass: 1096 return EmitLambdaLValue(cast<LambdaExpr>(E)); 1097 1098 case Expr::ExprWithCleanupsClass: { 1099 const auto *cleanups = cast<ExprWithCleanups>(E); 1100 enterFullExpression(cleanups); 1101 RunCleanupsScope Scope(*this); 1102 LValue LV = EmitLValue(cleanups->getSubExpr()); 1103 if (LV.isSimple()) { 1104 // Defend against branches out of gnu statement expressions surrounded by 1105 // cleanups. 1106 llvm::Value *V = LV.getPointer(); 1107 Scope.ForceCleanup({&V}); 1108 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(), 1109 getContext(), LV.getBaseInfo(), 1110 LV.getTBAAInfo()); 1111 } 1112 // FIXME: Is it possible to create an ExprWithCleanups that produces a 1113 // bitfield lvalue or some other non-simple lvalue? 1114 return LV; 1115 } 1116 1117 case Expr::CXXDefaultArgExprClass: 1118 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr()); 1119 case Expr::CXXDefaultInitExprClass: { 1120 CXXDefaultInitExprScope Scope(*this); 1121 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr()); 1122 } 1123 case Expr::CXXTypeidExprClass: 1124 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E)); 1125 1126 case Expr::ObjCMessageExprClass: 1127 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 1128 case Expr::ObjCIvarRefExprClass: 1129 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 1130 case Expr::StmtExprClass: 1131 return EmitStmtExprLValue(cast<StmtExpr>(E)); 1132 case Expr::UnaryOperatorClass: 1133 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 1134 case Expr::ArraySubscriptExprClass: 1135 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 1136 case Expr::OMPArraySectionExprClass: 1137 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E)); 1138 case Expr::ExtVectorElementExprClass: 1139 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 1140 case Expr::MemberExprClass: 1141 return EmitMemberExpr(cast<MemberExpr>(E)); 1142 case Expr::CompoundLiteralExprClass: 1143 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 1144 case Expr::ConditionalOperatorClass: 1145 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E)); 1146 case Expr::BinaryConditionalOperatorClass: 1147 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E)); 1148 case Expr::ChooseExprClass: 1149 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr()); 1150 case Expr::OpaqueValueExprClass: 1151 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E)); 1152 case Expr::SubstNonTypeTemplateParmExprClass: 1153 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement()); 1154 case Expr::ImplicitCastExprClass: 1155 case Expr::CStyleCastExprClass: 1156 case Expr::CXXFunctionalCastExprClass: 1157 case Expr::CXXStaticCastExprClass: 1158 case Expr::CXXDynamicCastExprClass: 1159 case Expr::CXXReinterpretCastExprClass: 1160 case Expr::CXXConstCastExprClass: 1161 case Expr::ObjCBridgedCastExprClass: 1162 return EmitCastLValue(cast<CastExpr>(E)); 1163 1164 case Expr::MaterializeTemporaryExprClass: 1165 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E)); 1166 1167 case Expr::CoawaitExprClass: 1168 return EmitCoawaitLValue(cast<CoawaitExpr>(E)); 1169 case Expr::CoyieldExprClass: 1170 return EmitCoyieldLValue(cast<CoyieldExpr>(E)); 1171 } 1172 } 1173 1174 /// Given an object of the given canonical type, can we safely copy a 1175 /// value out of it based on its initializer? 1176 static bool isConstantEmittableObjectType(QualType type) { 1177 assert(type.isCanonical()); 1178 assert(!type->isReferenceType()); 1179 1180 // Must be const-qualified but non-volatile. 1181 Qualifiers qs = type.getLocalQualifiers(); 1182 if (!qs.hasConst() || qs.hasVolatile()) return false; 1183 1184 // Otherwise, all object types satisfy this except C++ classes with 1185 // mutable subobjects or non-trivial copy/destroy behavior. 1186 if (const auto *RT = dyn_cast<RecordType>(type)) 1187 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 1188 if (RD->hasMutableFields() || !RD->isTrivial()) 1189 return false; 1190 1191 return true; 1192 } 1193 1194 /// Can we constant-emit a load of a reference to a variable of the 1195 /// given type? This is different from predicates like 1196 /// Decl::isUsableInConstantExpressions because we do want it to apply 1197 /// in situations that don't necessarily satisfy the language's rules 1198 /// for this (e.g. C++'s ODR-use rules). For example, we want to able 1199 /// to do this with const float variables even if those variables 1200 /// aren't marked 'constexpr'. 1201 enum ConstantEmissionKind { 1202 CEK_None, 1203 CEK_AsReferenceOnly, 1204 CEK_AsValueOrReference, 1205 CEK_AsValueOnly 1206 }; 1207 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) { 1208 type = type.getCanonicalType(); 1209 if (const auto *ref = dyn_cast<ReferenceType>(type)) { 1210 if (isConstantEmittableObjectType(ref->getPointeeType())) 1211 return CEK_AsValueOrReference; 1212 return CEK_AsReferenceOnly; 1213 } 1214 if (isConstantEmittableObjectType(type)) 1215 return CEK_AsValueOnly; 1216 return CEK_None; 1217 } 1218 1219 /// Try to emit a reference to the given value without producing it as 1220 /// an l-value. This is actually more than an optimization: we can't 1221 /// produce an l-value for variables that we never actually captured 1222 /// in a block or lambda, which means const int variables or constexpr 1223 /// literals or similar. 1224 CodeGenFunction::ConstantEmission 1225 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) { 1226 ValueDecl *value = refExpr->getDecl(); 1227 1228 // The value needs to be an enum constant or a constant variable. 1229 ConstantEmissionKind CEK; 1230 if (isa<ParmVarDecl>(value)) { 1231 CEK = CEK_None; 1232 } else if (auto *var = dyn_cast<VarDecl>(value)) { 1233 CEK = checkVarTypeForConstantEmission(var->getType()); 1234 } else if (isa<EnumConstantDecl>(value)) { 1235 CEK = CEK_AsValueOnly; 1236 } else { 1237 CEK = CEK_None; 1238 } 1239 if (CEK == CEK_None) return ConstantEmission(); 1240 1241 Expr::EvalResult result; 1242 bool resultIsReference; 1243 QualType resultType; 1244 1245 // It's best to evaluate all the way as an r-value if that's permitted. 1246 if (CEK != CEK_AsReferenceOnly && 1247 refExpr->EvaluateAsRValue(result, getContext())) { 1248 resultIsReference = false; 1249 resultType = refExpr->getType(); 1250 1251 // Otherwise, try to evaluate as an l-value. 1252 } else if (CEK != CEK_AsValueOnly && 1253 refExpr->EvaluateAsLValue(result, getContext())) { 1254 resultIsReference = true; 1255 resultType = value->getType(); 1256 1257 // Failure. 1258 } else { 1259 return ConstantEmission(); 1260 } 1261 1262 // In any case, if the initializer has side-effects, abandon ship. 1263 if (result.HasSideEffects) 1264 return ConstantEmission(); 1265 1266 // Emit as a constant. 1267 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this); 1268 1269 // Make sure we emit a debug reference to the global variable. 1270 // This should probably fire even for 1271 if (isa<VarDecl>(value)) { 1272 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value))) 1273 EmitDeclRefExprDbgValue(refExpr, result.Val); 1274 } else { 1275 assert(isa<EnumConstantDecl>(value)); 1276 EmitDeclRefExprDbgValue(refExpr, result.Val); 1277 } 1278 1279 // If we emitted a reference constant, we need to dereference that. 1280 if (resultIsReference) 1281 return ConstantEmission::forReference(C); 1282 1283 return ConstantEmission::forValue(C); 1284 } 1285 1286 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue, 1287 SourceLocation Loc) { 1288 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(), 1289 lvalue.getType(), Loc, lvalue.getBaseInfo(), 1290 lvalue.getTBAAInfo(), 1291 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(), 1292 lvalue.isNontemporal()); 1293 } 1294 1295 static bool hasBooleanRepresentation(QualType Ty) { 1296 if (Ty->isBooleanType()) 1297 return true; 1298 1299 if (const EnumType *ET = Ty->getAs<EnumType>()) 1300 return ET->getDecl()->getIntegerType()->isBooleanType(); 1301 1302 if (const AtomicType *AT = Ty->getAs<AtomicType>()) 1303 return hasBooleanRepresentation(AT->getValueType()); 1304 1305 return false; 1306 } 1307 1308 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, 1309 llvm::APInt &Min, llvm::APInt &End, 1310 bool StrictEnums, bool IsBool) { 1311 const EnumType *ET = Ty->getAs<EnumType>(); 1312 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums && 1313 ET && !ET->getDecl()->isFixed(); 1314 if (!IsBool && !IsRegularCPlusPlusEnum) 1315 return false; 1316 1317 if (IsBool) { 1318 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0); 1319 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2); 1320 } else { 1321 const EnumDecl *ED = ET->getDecl(); 1322 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType()); 1323 unsigned Bitwidth = LTy->getScalarSizeInBits(); 1324 unsigned NumNegativeBits = ED->getNumNegativeBits(); 1325 unsigned NumPositiveBits = ED->getNumPositiveBits(); 1326 1327 if (NumNegativeBits) { 1328 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1); 1329 assert(NumBits <= Bitwidth); 1330 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1); 1331 Min = -End; 1332 } else { 1333 assert(NumPositiveBits <= Bitwidth); 1334 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits; 1335 Min = llvm::APInt(Bitwidth, 0); 1336 } 1337 } 1338 return true; 1339 } 1340 1341 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) { 1342 llvm::APInt Min, End; 1343 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums, 1344 hasBooleanRepresentation(Ty))) 1345 return nullptr; 1346 1347 llvm::MDBuilder MDHelper(getLLVMContext()); 1348 return MDHelper.createRange(Min, End); 1349 } 1350 1351 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, 1352 SourceLocation Loc) { 1353 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool); 1354 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum); 1355 if (!HasBoolCheck && !HasEnumCheck) 1356 return false; 1357 1358 bool IsBool = hasBooleanRepresentation(Ty) || 1359 NSAPI(CGM.getContext()).isObjCBOOLType(Ty); 1360 bool NeedsBoolCheck = HasBoolCheck && IsBool; 1361 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>(); 1362 if (!NeedsBoolCheck && !NeedsEnumCheck) 1363 return false; 1364 1365 // Single-bit booleans don't need to be checked. Special-case this to avoid 1366 // a bit width mismatch when handling bitfield values. This is handled by 1367 // EmitFromMemory for the non-bitfield case. 1368 if (IsBool && 1369 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1) 1370 return false; 1371 1372 llvm::APInt Min, End; 1373 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool)) 1374 return true; 1375 1376 SanitizerScope SanScope(this); 1377 llvm::Value *Check; 1378 --End; 1379 if (!Min) { 1380 Check = Builder.CreateICmpULE( 1381 Value, llvm::ConstantInt::get(getLLVMContext(), End)); 1382 } else { 1383 llvm::Value *Upper = Builder.CreateICmpSLE( 1384 Value, llvm::ConstantInt::get(getLLVMContext(), End)); 1385 llvm::Value *Lower = Builder.CreateICmpSGE( 1386 Value, llvm::ConstantInt::get(getLLVMContext(), Min)); 1387 Check = Builder.CreateAnd(Upper, Lower); 1388 } 1389 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc), 1390 EmitCheckTypeDescriptor(Ty)}; 1391 SanitizerMask Kind = 1392 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool; 1393 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue, 1394 StaticArgs, EmitCheckValue(Value)); 1395 return true; 1396 } 1397 1398 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile, 1399 QualType Ty, 1400 SourceLocation Loc, 1401 LValueBaseInfo BaseInfo, 1402 llvm::MDNode *TBAAInfo, 1403 QualType TBAABaseType, 1404 uint64_t TBAAOffset, 1405 bool isNontemporal) { 1406 if (!CGM.getCodeGenOpts().PreserveVec3Type) { 1407 // For better performance, handle vector loads differently. 1408 if (Ty->isVectorType()) { 1409 const llvm::Type *EltTy = Addr.getElementType(); 1410 1411 const auto *VTy = cast<llvm::VectorType>(EltTy); 1412 1413 // Handle vectors of size 3 like size 4 for better performance. 1414 if (VTy->getNumElements() == 3) { 1415 1416 // Bitcast to vec4 type. 1417 llvm::VectorType *vec4Ty = 1418 llvm::VectorType::get(VTy->getElementType(), 4); 1419 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4"); 1420 // Now load value. 1421 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4"); 1422 1423 // Shuffle vector to get vec3. 1424 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty), 1425 {0, 1, 2}, "extractVec"); 1426 return EmitFromMemory(V, Ty); 1427 } 1428 } 1429 } 1430 1431 // Atomic operations have to be done on integral types. 1432 LValue AtomicLValue = 1433 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo); 1434 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) { 1435 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal(); 1436 } 1437 1438 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile); 1439 if (isNontemporal) { 1440 llvm::MDNode *Node = llvm::MDNode::get( 1441 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1442 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1443 } 1444 if (TBAAInfo) { 1445 bool MayAlias = BaseInfo.getMayAlias(); 1446 llvm::MDNode *TBAA = MayAlias 1447 ? CGM.getTBAAInfo(getContext().CharTy) 1448 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset); 1449 if (TBAA) 1450 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias); 1451 } 1452 1453 if (EmitScalarRangeCheck(Load, Ty, Loc)) { 1454 // In order to prevent the optimizer from throwing away the check, don't 1455 // attach range metadata to the load. 1456 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0) 1457 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) 1458 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo); 1459 1460 return EmitFromMemory(Load, Ty); 1461 } 1462 1463 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 1464 // Bool has a different representation in memory than in registers. 1465 if (hasBooleanRepresentation(Ty)) { 1466 // This should really always be an i1, but sometimes it's already 1467 // an i8, and it's awkward to track those cases down. 1468 if (Value->getType()->isIntegerTy(1)) 1469 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool"); 1470 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1471 "wrong value rep of bool"); 1472 } 1473 1474 return Value; 1475 } 1476 1477 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 1478 // Bool has a different representation in memory than in registers. 1479 if (hasBooleanRepresentation(Ty)) { 1480 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1481 "wrong value rep of bool"); 1482 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool"); 1483 } 1484 1485 return Value; 1486 } 1487 1488 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr, 1489 bool Volatile, QualType Ty, 1490 LValueBaseInfo BaseInfo, 1491 llvm::MDNode *TBAAInfo, 1492 bool isInit, QualType TBAABaseType, 1493 uint64_t TBAAOffset, 1494 bool isNontemporal) { 1495 1496 if (!CGM.getCodeGenOpts().PreserveVec3Type) { 1497 // Handle vectors differently to get better performance. 1498 if (Ty->isVectorType()) { 1499 llvm::Type *SrcTy = Value->getType(); 1500 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy); 1501 // Handle vec3 special. 1502 if (VecTy && VecTy->getNumElements() == 3) { 1503 // Our source is a vec3, do a shuffle vector to make it a vec4. 1504 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1), 1505 Builder.getInt32(2), 1506 llvm::UndefValue::get(Builder.getInt32Ty())}; 1507 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1508 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy), 1509 MaskV, "extractVec"); 1510 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4); 1511 } 1512 if (Addr.getElementType() != SrcTy) { 1513 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp"); 1514 } 1515 } 1516 } 1517 1518 Value = EmitToMemory(Value, Ty); 1519 1520 LValue AtomicLValue = 1521 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo); 1522 if (Ty->isAtomicType() || 1523 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) { 1524 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit); 1525 return; 1526 } 1527 1528 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 1529 if (isNontemporal) { 1530 llvm::MDNode *Node = 1531 llvm::MDNode::get(Store->getContext(), 1532 llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1533 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1534 } 1535 if (TBAAInfo) { 1536 bool MayAlias = BaseInfo.getMayAlias(); 1537 llvm::MDNode *TBAA = MayAlias 1538 ? CGM.getTBAAInfo(getContext().CharTy) 1539 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset); 1540 if (TBAA) 1541 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias); 1542 } 1543 } 1544 1545 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue, 1546 bool isInit) { 1547 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(), 1548 lvalue.getType(), lvalue.getBaseInfo(), 1549 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(), 1550 lvalue.getTBAAOffset(), lvalue.isNontemporal()); 1551 } 1552 1553 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 1554 /// method emits the address of the lvalue, then loads the result as an rvalue, 1555 /// returning the rvalue. 1556 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 1557 if (LV.isObjCWeak()) { 1558 // load of a __weak object. 1559 Address AddrWeakObj = LV.getAddress(); 1560 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 1561 AddrWeakObj)); 1562 } 1563 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 1564 // In MRC mode, we do a load+autorelease. 1565 if (!getLangOpts().ObjCAutoRefCount) { 1566 return RValue::get(EmitARCLoadWeak(LV.getAddress())); 1567 } 1568 1569 // In ARC mode, we load retained and then consume the value. 1570 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress()); 1571 Object = EmitObjCConsumeObject(LV.getType(), Object); 1572 return RValue::get(Object); 1573 } 1574 1575 if (LV.isSimple()) { 1576 assert(!LV.getType()->isFunctionType()); 1577 1578 // Everything needs a load. 1579 return RValue::get(EmitLoadOfScalar(LV, Loc)); 1580 } 1581 1582 if (LV.isVectorElt()) { 1583 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(), 1584 LV.isVolatileQualified()); 1585 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(), 1586 "vecext")); 1587 } 1588 1589 // If this is a reference to a subset of the elements of a vector, either 1590 // shuffle the input or extract/insert them as appropriate. 1591 if (LV.isExtVectorElt()) 1592 return EmitLoadOfExtVectorElementLValue(LV); 1593 1594 // Global Register variables always invoke intrinsics 1595 if (LV.isGlobalReg()) 1596 return EmitLoadOfGlobalRegLValue(LV); 1597 1598 assert(LV.isBitField() && "Unknown LValue type!"); 1599 return EmitLoadOfBitfieldLValue(LV, Loc); 1600 } 1601 1602 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 1603 SourceLocation Loc) { 1604 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 1605 1606 // Get the output type. 1607 llvm::Type *ResLTy = ConvertType(LV.getType()); 1608 1609 Address Ptr = LV.getBitFieldAddress(); 1610 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load"); 1611 1612 if (Info.IsSigned) { 1613 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize); 1614 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size; 1615 if (HighBits) 1616 Val = Builder.CreateShl(Val, HighBits, "bf.shl"); 1617 if (Info.Offset + HighBits) 1618 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr"); 1619 } else { 1620 if (Info.Offset) 1621 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr"); 1622 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize) 1623 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize, 1624 Info.Size), 1625 "bf.clear"); 1626 } 1627 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast"); 1628 EmitScalarRangeCheck(Val, LV.getType(), Loc); 1629 return RValue::get(Val); 1630 } 1631 1632 // If this is a reference to a subset of the elements of a vector, create an 1633 // appropriate shufflevector. 1634 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) { 1635 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(), 1636 LV.isVolatileQualified()); 1637 1638 const llvm::Constant *Elts = LV.getExtVectorElts(); 1639 1640 // If the result of the expression is a non-vector type, we must be extracting 1641 // a single element. Just codegen as an extractelement. 1642 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1643 if (!ExprVT) { 1644 unsigned InIdx = getAccessedFieldNo(0, Elts); 1645 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 1646 return RValue::get(Builder.CreateExtractElement(Vec, Elt)); 1647 } 1648 1649 // Always use shuffle vector to try to retain the original program structure 1650 unsigned NumResultElts = ExprVT->getNumElements(); 1651 1652 SmallVector<llvm::Constant*, 4> Mask; 1653 for (unsigned i = 0; i != NumResultElts; ++i) 1654 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts))); 1655 1656 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1657 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), 1658 MaskV); 1659 return RValue::get(Vec); 1660 } 1661 1662 /// @brief Generates lvalue for partial ext_vector access. 1663 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) { 1664 Address VectorAddress = LV.getExtVectorAddress(); 1665 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1666 QualType EQT = ExprVT->getElementType(); 1667 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT); 1668 1669 Address CastToPointerElement = 1670 Builder.CreateElementBitCast(VectorAddress, VectorElementTy, 1671 "conv.ptr.element"); 1672 1673 const llvm::Constant *Elts = LV.getExtVectorElts(); 1674 unsigned ix = getAccessedFieldNo(0, Elts); 1675 1676 Address VectorBasePtrPlusIx = 1677 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix, 1678 getContext().getTypeSizeInChars(EQT), 1679 "vector.elt"); 1680 1681 return VectorBasePtrPlusIx; 1682 } 1683 1684 /// @brief Load of global gamed gegisters are always calls to intrinsics. 1685 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) { 1686 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) && 1687 "Bad type for register variable"); 1688 llvm::MDNode *RegName = cast<llvm::MDNode>( 1689 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata()); 1690 1691 // We accept integer and pointer types only 1692 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType()); 1693 llvm::Type *Ty = OrigTy; 1694 if (OrigTy->isPointerTy()) 1695 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 1696 llvm::Type *Types[] = { Ty }; 1697 1698 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types); 1699 llvm::Value *Call = Builder.CreateCall( 1700 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName)); 1701 if (OrigTy->isPointerTy()) 1702 Call = Builder.CreateIntToPtr(Call, OrigTy); 1703 return RValue::get(Call); 1704 } 1705 1706 1707 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1708 /// lvalue, where both are guaranteed to the have the same type, and that type 1709 /// is 'Ty'. 1710 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 1711 bool isInit) { 1712 if (!Dst.isSimple()) { 1713 if (Dst.isVectorElt()) { 1714 // Read/modify/write the vector, inserting the new element. 1715 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(), 1716 Dst.isVolatileQualified()); 1717 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 1718 Dst.getVectorIdx(), "vecins"); 1719 Builder.CreateStore(Vec, Dst.getVectorAddress(), 1720 Dst.isVolatileQualified()); 1721 return; 1722 } 1723 1724 // If this is an update of extended vector elements, insert them as 1725 // appropriate. 1726 if (Dst.isExtVectorElt()) 1727 return EmitStoreThroughExtVectorComponentLValue(Src, Dst); 1728 1729 if (Dst.isGlobalReg()) 1730 return EmitStoreThroughGlobalRegLValue(Src, Dst); 1731 1732 assert(Dst.isBitField() && "Unknown LValue type"); 1733 return EmitStoreThroughBitfieldLValue(Src, Dst); 1734 } 1735 1736 // There's special magic for assigning into an ARC-qualified l-value. 1737 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) { 1738 switch (Lifetime) { 1739 case Qualifiers::OCL_None: 1740 llvm_unreachable("present but none"); 1741 1742 case Qualifiers::OCL_ExplicitNone: 1743 // nothing special 1744 break; 1745 1746 case Qualifiers::OCL_Strong: 1747 if (isInit) { 1748 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal())); 1749 break; 1750 } 1751 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true); 1752 return; 1753 1754 case Qualifiers::OCL_Weak: 1755 if (isInit) 1756 // Initialize and then skip the primitive store. 1757 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal()); 1758 else 1759 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true); 1760 return; 1761 1762 case Qualifiers::OCL_Autoreleasing: 1763 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(), 1764 Src.getScalarVal())); 1765 // fall into the normal path 1766 break; 1767 } 1768 } 1769 1770 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 1771 // load of a __weak object. 1772 Address LvalueDst = Dst.getAddress(); 1773 llvm::Value *src = Src.getScalarVal(); 1774 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 1775 return; 1776 } 1777 1778 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 1779 // load of a __strong object. 1780 Address LvalueDst = Dst.getAddress(); 1781 llvm::Value *src = Src.getScalarVal(); 1782 if (Dst.isObjCIvar()) { 1783 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 1784 llvm::Type *ResultType = IntPtrTy; 1785 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp()); 1786 llvm::Value *RHS = dst.getPointer(); 1787 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1788 llvm::Value *LHS = 1789 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType, 1790 "sub.ptr.lhs.cast"); 1791 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 1792 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 1793 BytesBetween); 1794 } else if (Dst.isGlobalObjCRef()) { 1795 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 1796 Dst.isThreadLocalRef()); 1797 } 1798 else 1799 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 1800 return; 1801 } 1802 1803 assert(Src.isScalar() && "Can't emit an agg store with this method"); 1804 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit); 1805 } 1806 1807 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 1808 llvm::Value **Result) { 1809 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 1810 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType()); 1811 Address Ptr = Dst.getBitFieldAddress(); 1812 1813 // Get the source value, truncated to the width of the bit-field. 1814 llvm::Value *SrcVal = Src.getScalarVal(); 1815 1816 // Cast the source to the storage type and shift it into place. 1817 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(), 1818 /*IsSigned=*/false); 1819 llvm::Value *MaskedVal = SrcVal; 1820 1821 // See if there are other bits in the bitfield's storage we'll need to load 1822 // and mask together with source before storing. 1823 if (Info.StorageSize != Info.Size) { 1824 assert(Info.StorageSize > Info.Size && "Invalid bitfield size."); 1825 llvm::Value *Val = 1826 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load"); 1827 1828 // Mask the source value as needed. 1829 if (!hasBooleanRepresentation(Dst.getType())) 1830 SrcVal = Builder.CreateAnd(SrcVal, 1831 llvm::APInt::getLowBitsSet(Info.StorageSize, 1832 Info.Size), 1833 "bf.value"); 1834 MaskedVal = SrcVal; 1835 if (Info.Offset) 1836 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl"); 1837 1838 // Mask out the original value. 1839 Val = Builder.CreateAnd(Val, 1840 ~llvm::APInt::getBitsSet(Info.StorageSize, 1841 Info.Offset, 1842 Info.Offset + Info.Size), 1843 "bf.clear"); 1844 1845 // Or together the unchanged values and the source value. 1846 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set"); 1847 } else { 1848 assert(Info.Offset == 0); 1849 } 1850 1851 // Write the new value back out. 1852 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified()); 1853 1854 // Return the new value of the bit-field, if requested. 1855 if (Result) { 1856 llvm::Value *ResultVal = MaskedVal; 1857 1858 // Sign extend the value if needed. 1859 if (Info.IsSigned) { 1860 assert(Info.Size <= Info.StorageSize); 1861 unsigned HighBits = Info.StorageSize - Info.Size; 1862 if (HighBits) { 1863 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl"); 1864 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr"); 1865 } 1866 } 1867 1868 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned, 1869 "bf.result.cast"); 1870 *Result = EmitFromMemory(ResultVal, Dst.getType()); 1871 } 1872 } 1873 1874 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 1875 LValue Dst) { 1876 // This access turns into a read/modify/write of the vector. Load the input 1877 // value now. 1878 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(), 1879 Dst.isVolatileQualified()); 1880 const llvm::Constant *Elts = Dst.getExtVectorElts(); 1881 1882 llvm::Value *SrcVal = Src.getScalarVal(); 1883 1884 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) { 1885 unsigned NumSrcElts = VTy->getNumElements(); 1886 unsigned NumDstElts = Vec->getType()->getVectorNumElements(); 1887 if (NumDstElts == NumSrcElts) { 1888 // Use shuffle vector is the src and destination are the same number of 1889 // elements and restore the vector mask since it is on the side it will be 1890 // stored. 1891 SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 1892 for (unsigned i = 0; i != NumSrcElts; ++i) 1893 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i); 1894 1895 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1896 Vec = Builder.CreateShuffleVector(SrcVal, 1897 llvm::UndefValue::get(Vec->getType()), 1898 MaskV); 1899 } else if (NumDstElts > NumSrcElts) { 1900 // Extended the source vector to the same length and then shuffle it 1901 // into the destination. 1902 // FIXME: since we're shuffling with undef, can we just use the indices 1903 // into that? This could be simpler. 1904 SmallVector<llvm::Constant*, 4> ExtMask; 1905 for (unsigned i = 0; i != NumSrcElts; ++i) 1906 ExtMask.push_back(Builder.getInt32(i)); 1907 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty)); 1908 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask); 1909 llvm::Value *ExtSrcVal = 1910 Builder.CreateShuffleVector(SrcVal, 1911 llvm::UndefValue::get(SrcVal->getType()), 1912 ExtMaskV); 1913 // build identity 1914 SmallVector<llvm::Constant*, 4> Mask; 1915 for (unsigned i = 0; i != NumDstElts; ++i) 1916 Mask.push_back(Builder.getInt32(i)); 1917 1918 // When the vector size is odd and .odd or .hi is used, the last element 1919 // of the Elts constant array will be one past the size of the vector. 1920 // Ignore the last element here, if it is greater than the mask size. 1921 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size()) 1922 NumSrcElts--; 1923 1924 // modify when what gets shuffled in 1925 for (unsigned i = 0; i != NumSrcElts; ++i) 1926 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts); 1927 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1928 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV); 1929 } else { 1930 // We should never shorten the vector 1931 llvm_unreachable("unexpected shorten vector length"); 1932 } 1933 } else { 1934 // If the Src is a scalar (not a vector) it must be updating one element. 1935 unsigned InIdx = getAccessedFieldNo(0, Elts); 1936 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 1937 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt); 1938 } 1939 1940 Builder.CreateStore(Vec, Dst.getExtVectorAddress(), 1941 Dst.isVolatileQualified()); 1942 } 1943 1944 /// @brief Store of global named registers are always calls to intrinsics. 1945 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) { 1946 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) && 1947 "Bad type for register variable"); 1948 llvm::MDNode *RegName = cast<llvm::MDNode>( 1949 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata()); 1950 assert(RegName && "Register LValue is not metadata"); 1951 1952 // We accept integer and pointer types only 1953 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType()); 1954 llvm::Type *Ty = OrigTy; 1955 if (OrigTy->isPointerTy()) 1956 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 1957 llvm::Type *Types[] = { Ty }; 1958 1959 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types); 1960 llvm::Value *Value = Src.getScalarVal(); 1961 if (OrigTy->isPointerTy()) 1962 Value = Builder.CreatePtrToInt(Value, Ty); 1963 Builder.CreateCall( 1964 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value}); 1965 } 1966 1967 // setObjCGCLValueClass - sets class of the lvalue for the purpose of 1968 // generating write-barries API. It is currently a global, ivar, 1969 // or neither. 1970 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 1971 LValue &LV, 1972 bool IsMemberAccess=false) { 1973 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC) 1974 return; 1975 1976 if (isa<ObjCIvarRefExpr>(E)) { 1977 QualType ExpTy = E->getType(); 1978 if (IsMemberAccess && ExpTy->isPointerType()) { 1979 // If ivar is a structure pointer, assigning to field of 1980 // this struct follows gcc's behavior and makes it a non-ivar 1981 // writer-barrier conservatively. 1982 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1983 if (ExpTy->isRecordType()) { 1984 LV.setObjCIvar(false); 1985 return; 1986 } 1987 } 1988 LV.setObjCIvar(true); 1989 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E)); 1990 LV.setBaseIvarExp(Exp->getBase()); 1991 LV.setObjCArray(E->getType()->isArrayType()); 1992 return; 1993 } 1994 1995 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) { 1996 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 1997 if (VD->hasGlobalStorage()) { 1998 LV.setGlobalObjCRef(true); 1999 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None); 2000 } 2001 } 2002 LV.setObjCArray(E->getType()->isArrayType()); 2003 return; 2004 } 2005 2006 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) { 2007 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2008 return; 2009 } 2010 2011 if (const auto *Exp = dyn_cast<ParenExpr>(E)) { 2012 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2013 if (LV.isObjCIvar()) { 2014 // If cast is to a structure pointer, follow gcc's behavior and make it 2015 // a non-ivar write-barrier. 2016 QualType ExpTy = E->getType(); 2017 if (ExpTy->isPointerType()) 2018 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 2019 if (ExpTy->isRecordType()) 2020 LV.setObjCIvar(false); 2021 } 2022 return; 2023 } 2024 2025 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) { 2026 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV); 2027 return; 2028 } 2029 2030 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) { 2031 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2032 return; 2033 } 2034 2035 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) { 2036 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2037 return; 2038 } 2039 2040 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) { 2041 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2042 return; 2043 } 2044 2045 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 2046 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 2047 if (LV.isObjCIvar() && !LV.isObjCArray()) 2048 // Using array syntax to assigning to what an ivar points to is not 2049 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 2050 LV.setObjCIvar(false); 2051 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 2052 // Using array syntax to assigning to what global points to is not 2053 // same as assigning to the global itself. {id *G;} G[i] = 0; 2054 LV.setGlobalObjCRef(false); 2055 return; 2056 } 2057 2058 if (const auto *Exp = dyn_cast<MemberExpr>(E)) { 2059 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true); 2060 // We don't know if member is an 'ivar', but this flag is looked at 2061 // only in the context of LV.isObjCIvar(). 2062 LV.setObjCArray(E->getType()->isArrayType()); 2063 return; 2064 } 2065 } 2066 2067 static llvm::Value * 2068 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, 2069 llvm::Value *V, llvm::Type *IRType, 2070 StringRef Name = StringRef()) { 2071 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace(); 2072 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name); 2073 } 2074 2075 static LValue EmitThreadPrivateVarDeclLValue( 2076 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, 2077 llvm::Type *RealVarTy, SourceLocation Loc) { 2078 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc); 2079 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy); 2080 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2081 return CGF.MakeAddrLValue(Addr, T, BaseInfo); 2082 } 2083 2084 Address CodeGenFunction::EmitLoadOfReference(Address Addr, 2085 const ReferenceType *RefTy, 2086 LValueBaseInfo *BaseInfo) { 2087 llvm::Value *Ptr = Builder.CreateLoad(Addr); 2088 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(), 2089 BaseInfo, /*forPointee*/ true)); 2090 } 2091 2092 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr, 2093 const ReferenceType *RefTy) { 2094 LValueBaseInfo BaseInfo; 2095 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo); 2096 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo); 2097 } 2098 2099 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr, 2100 const PointerType *PtrTy, 2101 LValueBaseInfo *BaseInfo) { 2102 llvm::Value *Addr = Builder.CreateLoad(Ptr); 2103 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), 2104 BaseInfo, 2105 /*forPointeeType=*/true)); 2106 } 2107 2108 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr, 2109 const PointerType *PtrTy) { 2110 LValueBaseInfo BaseInfo; 2111 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo); 2112 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo); 2113 } 2114 2115 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 2116 const Expr *E, const VarDecl *VD) { 2117 QualType T = E->getType(); 2118 2119 // If it's thread_local, emit a call to its wrapper function instead. 2120 if (VD->getTLSKind() == VarDecl::TLS_Dynamic && 2121 CGF.CGM.getCXXABI().usesThreadWrapperFunction()) 2122 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T); 2123 2124 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 2125 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType()); 2126 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy); 2127 CharUnits Alignment = CGF.getContext().getDeclAlign(VD); 2128 Address Addr(V, Alignment); 2129 LValue LV; 2130 // Emit reference to the private copy of the variable if it is an OpenMP 2131 // threadprivate variable. 2132 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) 2133 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy, 2134 E->getExprLoc()); 2135 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) { 2136 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy); 2137 } else { 2138 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2139 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo); 2140 } 2141 setObjCGCLValueClass(CGF.getContext(), E, LV); 2142 return LV; 2143 } 2144 2145 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM, 2146 const FunctionDecl *FD) { 2147 if (FD->hasAttr<WeakRefAttr>()) { 2148 ConstantAddress aliasee = CGM.GetWeakRefReference(FD); 2149 return aliasee.getPointer(); 2150 } 2151 2152 llvm::Constant *V = CGM.GetAddrOfFunction(FD); 2153 if (!FD->hasPrototype()) { 2154 if (const FunctionProtoType *Proto = 2155 FD->getType()->getAs<FunctionProtoType>()) { 2156 // Ugly case: for a K&R-style definition, the type of the definition 2157 // isn't the same as the type of a use. Correct for this with a 2158 // bitcast. 2159 QualType NoProtoType = 2160 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType()); 2161 NoProtoType = CGM.getContext().getPointerType(NoProtoType); 2162 V = llvm::ConstantExpr::getBitCast(V, 2163 CGM.getTypes().ConvertType(NoProtoType)); 2164 } 2165 } 2166 return V; 2167 } 2168 2169 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, 2170 const Expr *E, const FunctionDecl *FD) { 2171 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD); 2172 CharUnits Alignment = CGF.getContext().getDeclAlign(FD); 2173 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2174 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo); 2175 } 2176 2177 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, 2178 llvm::Value *ThisValue) { 2179 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent()); 2180 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType); 2181 return CGF.EmitLValueForField(LV, FD); 2182 } 2183 2184 /// Named Registers are named metadata pointing to the register name 2185 /// which will be read from/written to as an argument to the intrinsic 2186 /// @llvm.read/write_register. 2187 /// So far, only the name is being passed down, but other options such as 2188 /// register type, allocation type or even optimization options could be 2189 /// passed down via the metadata node. 2190 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) { 2191 SmallString<64> Name("llvm.named.register."); 2192 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>(); 2193 assert(Asm->getLabel().size() < 64-Name.size() && 2194 "Register name too big"); 2195 Name.append(Asm->getLabel()); 2196 llvm::NamedMDNode *M = 2197 CGM.getModule().getOrInsertNamedMetadata(Name); 2198 if (M->getNumOperands() == 0) { 2199 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(), 2200 Asm->getLabel()); 2201 llvm::Metadata *Ops[] = {Str}; 2202 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2203 } 2204 2205 CharUnits Alignment = CGM.getContext().getDeclAlign(VD); 2206 2207 llvm::Value *Ptr = 2208 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)); 2209 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType()); 2210 } 2211 2212 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 2213 const NamedDecl *ND = E->getDecl(); 2214 QualType T = E->getType(); 2215 2216 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2217 // Global Named registers access via intrinsics only 2218 if (VD->getStorageClass() == SC_Register && 2219 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl()) 2220 return EmitGlobalNamedRegister(VD, CGM); 2221 2222 // A DeclRefExpr for a reference initialized by a constant expression can 2223 // appear without being odr-used. Directly emit the constant initializer. 2224 const Expr *Init = VD->getAnyInitializer(VD); 2225 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() && 2226 VD->isUsableInConstantExpressions(getContext()) && 2227 VD->checkInitIsICE() && 2228 // Do not emit if it is private OpenMP variable. 2229 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo && 2230 LocalDeclMap.count(VD))) { 2231 llvm::Constant *Val = 2232 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this); 2233 assert(Val && "failed to emit reference constant expression"); 2234 // FIXME: Eventually we will want to emit vector element references. 2235 2236 // Should we be using the alignment of the constant pointer we emitted? 2237 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr, 2238 /*pointee*/ true); 2239 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2240 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo); 2241 } 2242 2243 // Check for captured variables. 2244 if (E->refersToEnclosingVariableOrCapture()) { 2245 if (auto *FD = LambdaCaptureFields.lookup(VD)) 2246 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue); 2247 else if (CapturedStmtInfo) { 2248 auto I = LocalDeclMap.find(VD); 2249 if (I != LocalDeclMap.end()) { 2250 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) 2251 return EmitLoadOfReferenceLValue(I->second, RefTy); 2252 return MakeAddrLValue(I->second, T); 2253 } 2254 LValue CapLVal = 2255 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD), 2256 CapturedStmtInfo->getContextValue()); 2257 bool MayAlias = CapLVal.getBaseInfo().getMayAlias(); 2258 return MakeAddrLValue( 2259 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)), 2260 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias)); 2261 } 2262 2263 assert(isa<BlockDecl>(CurCodeDecl)); 2264 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>()); 2265 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2266 return MakeAddrLValue(addr, T, BaseInfo); 2267 } 2268 } 2269 2270 // FIXME: We should be able to assert this for FunctionDecls as well! 2271 // FIXME: We should be able to assert this for all DeclRefExprs, not just 2272 // those with a valid source location. 2273 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || 2274 !E->getLocation().isValid()) && 2275 "Should not use decl without marking it used!"); 2276 2277 if (ND->hasAttr<WeakRefAttr>()) { 2278 const auto *VD = cast<ValueDecl>(ND); 2279 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD); 2280 return MakeAddrLValue(Aliasee, T, 2281 LValueBaseInfo(AlignmentSource::Decl, false)); 2282 } 2283 2284 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2285 // Check if this is a global variable. 2286 if (VD->hasLinkage() || VD->isStaticDataMember()) 2287 return EmitGlobalVarDeclLValue(*this, E, VD); 2288 2289 Address addr = Address::invalid(); 2290 2291 // The variable should generally be present in the local decl map. 2292 auto iter = LocalDeclMap.find(VD); 2293 if (iter != LocalDeclMap.end()) { 2294 addr = iter->second; 2295 2296 // Otherwise, it might be static local we haven't emitted yet for 2297 // some reason; most likely, because it's in an outer function. 2298 } else if (VD->isStaticLocal()) { 2299 addr = Address(CGM.getOrCreateStaticVarDecl( 2300 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)), 2301 getContext().getDeclAlign(VD)); 2302 2303 // No other cases for now. 2304 } else { 2305 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?"); 2306 } 2307 2308 2309 // Check for OpenMP threadprivate variables. 2310 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 2311 return EmitThreadPrivateVarDeclLValue( 2312 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()), 2313 E->getExprLoc()); 2314 } 2315 2316 // Drill into block byref variables. 2317 bool isBlockByref = VD->hasAttr<BlocksAttr>(); 2318 if (isBlockByref) { 2319 addr = emitBlockByrefAddress(addr, VD); 2320 } 2321 2322 // Drill into reference types. 2323 LValue LV; 2324 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) { 2325 LV = EmitLoadOfReferenceLValue(addr, RefTy); 2326 } else { 2327 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2328 LV = MakeAddrLValue(addr, T, BaseInfo); 2329 } 2330 2331 bool isLocalStorage = VD->hasLocalStorage(); 2332 2333 bool NonGCable = isLocalStorage && 2334 !VD->getType()->isReferenceType() && 2335 !isBlockByref; 2336 if (NonGCable) { 2337 LV.getQuals().removeObjCGCAttr(); 2338 LV.setNonGC(true); 2339 } 2340 2341 bool isImpreciseLifetime = 2342 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>()); 2343 if (isImpreciseLifetime) 2344 LV.setARCPreciseLifetime(ARCImpreciseLifetime); 2345 setObjCGCLValueClass(getContext(), E, LV); 2346 return LV; 2347 } 2348 2349 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 2350 return EmitFunctionDeclLValue(*this, E, FD); 2351 2352 // FIXME: While we're emitting a binding from an enclosing scope, all other 2353 // DeclRefExprs we see should be implicitly treated as if they also refer to 2354 // an enclosing scope. 2355 if (const auto *BD = dyn_cast<BindingDecl>(ND)) 2356 return EmitLValue(BD->getBinding()); 2357 2358 llvm_unreachable("Unhandled DeclRefExpr"); 2359 } 2360 2361 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 2362 // __extension__ doesn't affect lvalue-ness. 2363 if (E->getOpcode() == UO_Extension) 2364 return EmitLValue(E->getSubExpr()); 2365 2366 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 2367 switch (E->getOpcode()) { 2368 default: llvm_unreachable("Unknown unary operator lvalue!"); 2369 case UO_Deref: { 2370 QualType T = E->getSubExpr()->getType()->getPointeeType(); 2371 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 2372 2373 LValueBaseInfo BaseInfo; 2374 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo); 2375 LValue LV = MakeAddrLValue(Addr, T, BaseInfo); 2376 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 2377 2378 // We should not generate __weak write barrier on indirect reference 2379 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 2380 // But, we continue to generate __strong write barrier on indirect write 2381 // into a pointer to object. 2382 if (getLangOpts().ObjC1 && 2383 getLangOpts().getGC() != LangOptions::NonGC && 2384 LV.isObjCWeak()) 2385 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 2386 return LV; 2387 } 2388 case UO_Real: 2389 case UO_Imag: { 2390 LValue LV = EmitLValue(E->getSubExpr()); 2391 assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 2392 2393 // __real is valid on scalars. This is a faster way of testing that. 2394 // __imag can only produce an rvalue on scalars. 2395 if (E->getOpcode() == UO_Real && 2396 !LV.getAddress().getElementType()->isStructTy()) { 2397 assert(E->getSubExpr()->getType()->isArithmeticType()); 2398 return LV; 2399 } 2400 2401 QualType T = ExprTy->castAs<ComplexType>()->getElementType(); 2402 2403 Address Component = 2404 (E->getOpcode() == UO_Real 2405 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType()) 2406 : emitAddrOfImagComponent(LV.getAddress(), LV.getType())); 2407 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo()); 2408 ElemLV.getQuals().addQualifiers(LV.getQuals()); 2409 return ElemLV; 2410 } 2411 case UO_PreInc: 2412 case UO_PreDec: { 2413 LValue LV = EmitLValue(E->getSubExpr()); 2414 bool isInc = E->getOpcode() == UO_PreInc; 2415 2416 if (E->getType()->isAnyComplexType()) 2417 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 2418 else 2419 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 2420 return LV; 2421 } 2422 } 2423 } 2424 2425 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 2426 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 2427 E->getType(), 2428 LValueBaseInfo(AlignmentSource::Decl, false)); 2429 } 2430 2431 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 2432 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 2433 E->getType(), 2434 LValueBaseInfo(AlignmentSource::Decl, false)); 2435 } 2436 2437 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 2438 auto SL = E->getFunctionName(); 2439 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr"); 2440 StringRef FnName = CurFn->getName(); 2441 if (FnName.startswith("\01")) 2442 FnName = FnName.substr(1); 2443 StringRef NameItems[] = { 2444 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName}; 2445 std::string GVName = llvm::join(NameItems, NameItems + 2, "."); 2446 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 2447 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) { 2448 std::string Name = SL->getString(); 2449 if (!Name.empty()) { 2450 unsigned Discriminator = 2451 CGM.getCXXABI().getMangleContext().getBlockId(BD, true); 2452 if (Discriminator) 2453 Name += "_" + Twine(Discriminator + 1).str(); 2454 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str()); 2455 return MakeAddrLValue(C, E->getType(), BaseInfo); 2456 } else { 2457 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str()); 2458 return MakeAddrLValue(C, E->getType(), BaseInfo); 2459 } 2460 } 2461 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName); 2462 return MakeAddrLValue(C, E->getType(), BaseInfo); 2463 } 2464 2465 /// Emit a type description suitable for use by a runtime sanitizer library. The 2466 /// format of a type descriptor is 2467 /// 2468 /// \code 2469 /// { i16 TypeKind, i16 TypeInfo } 2470 /// \endcode 2471 /// 2472 /// followed by an array of i8 containing the type name. TypeKind is 0 for an 2473 /// integer, 1 for a floating point value, and -1 for anything else. 2474 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) { 2475 // Only emit each type's descriptor once. 2476 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T)) 2477 return C; 2478 2479 uint16_t TypeKind = -1; 2480 uint16_t TypeInfo = 0; 2481 2482 if (T->isIntegerType()) { 2483 TypeKind = 0; 2484 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) | 2485 (T->isSignedIntegerType() ? 1 : 0); 2486 } else if (T->isFloatingType()) { 2487 TypeKind = 1; 2488 TypeInfo = getContext().getTypeSize(T); 2489 } 2490 2491 // Format the type name as if for a diagnostic, including quotes and 2492 // optionally an 'aka'. 2493 SmallString<32> Buffer; 2494 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype, 2495 (intptr_t)T.getAsOpaquePtr(), 2496 StringRef(), StringRef(), None, Buffer, 2497 None); 2498 2499 llvm::Constant *Components[] = { 2500 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo), 2501 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer) 2502 }; 2503 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components); 2504 2505 auto *GV = new llvm::GlobalVariable( 2506 CGM.getModule(), Descriptor->getType(), 2507 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor); 2508 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2509 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV); 2510 2511 // Remember the descriptor for this type. 2512 CGM.setTypeDescriptorInMap(T, GV); 2513 2514 return GV; 2515 } 2516 2517 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) { 2518 llvm::Type *TargetTy = IntPtrTy; 2519 2520 // Floating-point types which fit into intptr_t are bitcast to integers 2521 // and then passed directly (after zero-extension, if necessary). 2522 if (V->getType()->isFloatingPointTy()) { 2523 unsigned Bits = V->getType()->getPrimitiveSizeInBits(); 2524 if (Bits <= TargetTy->getIntegerBitWidth()) 2525 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(), 2526 Bits)); 2527 } 2528 2529 // Integers which fit in intptr_t are zero-extended and passed directly. 2530 if (V->getType()->isIntegerTy() && 2531 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()) 2532 return Builder.CreateZExt(V, TargetTy); 2533 2534 // Pointers are passed directly, everything else is passed by address. 2535 if (!V->getType()->isPointerTy()) { 2536 Address Ptr = CreateDefaultAlignTempAlloca(V->getType()); 2537 Builder.CreateStore(V, Ptr); 2538 V = Ptr.getPointer(); 2539 } 2540 return Builder.CreatePtrToInt(V, TargetTy); 2541 } 2542 2543 /// \brief Emit a representation of a SourceLocation for passing to a handler 2544 /// in a sanitizer runtime library. The format for this data is: 2545 /// \code 2546 /// struct SourceLocation { 2547 /// const char *Filename; 2548 /// int32_t Line, Column; 2549 /// }; 2550 /// \endcode 2551 /// For an invalid SourceLocation, the Filename pointer is null. 2552 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) { 2553 llvm::Constant *Filename; 2554 int Line, Column; 2555 2556 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); 2557 if (PLoc.isValid()) { 2558 StringRef FilenameString = PLoc.getFilename(); 2559 2560 int PathComponentsToStrip = 2561 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip; 2562 if (PathComponentsToStrip < 0) { 2563 assert(PathComponentsToStrip != INT_MIN); 2564 int PathComponentsToKeep = -PathComponentsToStrip; 2565 auto I = llvm::sys::path::rbegin(FilenameString); 2566 auto E = llvm::sys::path::rend(FilenameString); 2567 while (I != E && --PathComponentsToKeep) 2568 ++I; 2569 2570 FilenameString = FilenameString.substr(I - E); 2571 } else if (PathComponentsToStrip > 0) { 2572 auto I = llvm::sys::path::begin(FilenameString); 2573 auto E = llvm::sys::path::end(FilenameString); 2574 while (I != E && PathComponentsToStrip--) 2575 ++I; 2576 2577 if (I != E) 2578 FilenameString = 2579 FilenameString.substr(I - llvm::sys::path::begin(FilenameString)); 2580 else 2581 FilenameString = llvm::sys::path::filename(FilenameString); 2582 } 2583 2584 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src"); 2585 CGM.getSanitizerMetadata()->disableSanitizerForGlobal( 2586 cast<llvm::GlobalVariable>(FilenameGV.getPointer())); 2587 Filename = FilenameGV.getPointer(); 2588 Line = PLoc.getLine(); 2589 Column = PLoc.getColumn(); 2590 } else { 2591 Filename = llvm::Constant::getNullValue(Int8PtrTy); 2592 Line = Column = 0; 2593 } 2594 2595 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line), 2596 Builder.getInt32(Column)}; 2597 2598 return llvm::ConstantStruct::getAnon(Data); 2599 } 2600 2601 namespace { 2602 /// \brief Specify under what conditions this check can be recovered 2603 enum class CheckRecoverableKind { 2604 /// Always terminate program execution if this check fails. 2605 Unrecoverable, 2606 /// Check supports recovering, runtime has both fatal (noreturn) and 2607 /// non-fatal handlers for this check. 2608 Recoverable, 2609 /// Runtime conditionally aborts, always need to support recovery. 2610 AlwaysRecoverable 2611 }; 2612 } 2613 2614 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) { 2615 assert(llvm::countPopulation(Kind) == 1); 2616 switch (Kind) { 2617 case SanitizerKind::Vptr: 2618 return CheckRecoverableKind::AlwaysRecoverable; 2619 case SanitizerKind::Return: 2620 case SanitizerKind::Unreachable: 2621 return CheckRecoverableKind::Unrecoverable; 2622 default: 2623 return CheckRecoverableKind::Recoverable; 2624 } 2625 } 2626 2627 namespace { 2628 struct SanitizerHandlerInfo { 2629 char const *const Name; 2630 unsigned Version; 2631 }; 2632 } 2633 2634 const SanitizerHandlerInfo SanitizerHandlers[] = { 2635 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version}, 2636 LIST_SANITIZER_CHECKS 2637 #undef SANITIZER_CHECK 2638 }; 2639 2640 static void emitCheckHandlerCall(CodeGenFunction &CGF, 2641 llvm::FunctionType *FnType, 2642 ArrayRef<llvm::Value *> FnArgs, 2643 SanitizerHandler CheckHandler, 2644 CheckRecoverableKind RecoverKind, bool IsFatal, 2645 llvm::BasicBlock *ContBB) { 2646 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable); 2647 bool NeedsAbortSuffix = 2648 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable; 2649 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler]; 2650 const StringRef CheckName = CheckInfo.Name; 2651 std::string FnName = 2652 ("__ubsan_handle_" + CheckName + 2653 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") + 2654 (NeedsAbortSuffix ? "_abort" : "")) 2655 .str(); 2656 bool MayReturn = 2657 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable; 2658 2659 llvm::AttrBuilder B; 2660 if (!MayReturn) { 2661 B.addAttribute(llvm::Attribute::NoReturn) 2662 .addAttribute(llvm::Attribute::NoUnwind); 2663 } 2664 B.addAttribute(llvm::Attribute::UWTable); 2665 2666 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction( 2667 FnType, FnName, 2668 llvm::AttributeList::get(CGF.getLLVMContext(), 2669 llvm::AttributeList::FunctionIndex, B), 2670 /*Local=*/true); 2671 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs); 2672 if (!MayReturn) { 2673 HandlerCall->setDoesNotReturn(); 2674 CGF.Builder.CreateUnreachable(); 2675 } else { 2676 CGF.Builder.CreateBr(ContBB); 2677 } 2678 } 2679 2680 void CodeGenFunction::EmitCheck( 2681 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 2682 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs, 2683 ArrayRef<llvm::Value *> DynamicArgs) { 2684 assert(IsSanitizerScope); 2685 assert(Checked.size() > 0); 2686 assert(CheckHandler >= 0 && 2687 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers)); 2688 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name; 2689 2690 llvm::Value *FatalCond = nullptr; 2691 llvm::Value *RecoverableCond = nullptr; 2692 llvm::Value *TrapCond = nullptr; 2693 for (int i = 0, n = Checked.size(); i < n; ++i) { 2694 llvm::Value *Check = Checked[i].first; 2695 // -fsanitize-trap= overrides -fsanitize-recover=. 2696 llvm::Value *&Cond = 2697 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second) 2698 ? TrapCond 2699 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second) 2700 ? RecoverableCond 2701 : FatalCond; 2702 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check; 2703 } 2704 2705 if (TrapCond) 2706 EmitTrapCheck(TrapCond); 2707 if (!FatalCond && !RecoverableCond) 2708 return; 2709 2710 llvm::Value *JointCond; 2711 if (FatalCond && RecoverableCond) 2712 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond); 2713 else 2714 JointCond = FatalCond ? FatalCond : RecoverableCond; 2715 assert(JointCond); 2716 2717 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second); 2718 assert(SanOpts.has(Checked[0].second)); 2719 #ifndef NDEBUG 2720 for (int i = 1, n = Checked.size(); i < n; ++i) { 2721 assert(RecoverKind == getRecoverableKind(Checked[i].second) && 2722 "All recoverable kinds in a single check must be same!"); 2723 assert(SanOpts.has(Checked[i].second)); 2724 } 2725 #endif 2726 2727 llvm::BasicBlock *Cont = createBasicBlock("cont"); 2728 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName); 2729 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers); 2730 // Give hint that we very much don't expect to execute the handler 2731 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp 2732 llvm::MDBuilder MDHelper(getLLVMContext()); 2733 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 2734 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node); 2735 EmitBlock(Handlers); 2736 2737 // Handler functions take an i8* pointing to the (handler-specific) static 2738 // information block, followed by a sequence of intptr_t arguments 2739 // representing operand values. 2740 SmallVector<llvm::Value *, 4> Args; 2741 SmallVector<llvm::Type *, 4> ArgTypes; 2742 Args.reserve(DynamicArgs.size() + 1); 2743 ArgTypes.reserve(DynamicArgs.size() + 1); 2744 2745 // Emit handler arguments and create handler function type. 2746 if (!StaticArgs.empty()) { 2747 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 2748 auto *InfoPtr = 2749 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 2750 llvm::GlobalVariable::PrivateLinkage, Info); 2751 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2752 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 2753 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy)); 2754 ArgTypes.push_back(Int8PtrTy); 2755 } 2756 2757 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) { 2758 Args.push_back(EmitCheckValue(DynamicArgs[i])); 2759 ArgTypes.push_back(IntPtrTy); 2760 } 2761 2762 llvm::FunctionType *FnType = 2763 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false); 2764 2765 if (!FatalCond || !RecoverableCond) { 2766 // Simple case: we need to generate a single handler call, either 2767 // fatal, or non-fatal. 2768 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, 2769 (FatalCond != nullptr), Cont); 2770 } else { 2771 // Emit two handler calls: first one for set of unrecoverable checks, 2772 // another one for recoverable. 2773 llvm::BasicBlock *NonFatalHandlerBB = 2774 createBasicBlock("non_fatal." + CheckName); 2775 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName); 2776 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB); 2777 EmitBlock(FatalHandlerBB); 2778 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true, 2779 NonFatalHandlerBB); 2780 EmitBlock(NonFatalHandlerBB); 2781 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false, 2782 Cont); 2783 } 2784 2785 EmitBlock(Cont); 2786 } 2787 2788 void CodeGenFunction::EmitCfiSlowPathCheck( 2789 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId, 2790 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) { 2791 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont"); 2792 2793 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath"); 2794 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB); 2795 2796 llvm::MDBuilder MDHelper(getLLVMContext()); 2797 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 2798 BI->setMetadata(llvm::LLVMContext::MD_prof, Node); 2799 2800 EmitBlock(CheckBB); 2801 2802 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind); 2803 2804 llvm::CallInst *CheckCall; 2805 if (WithDiag) { 2806 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 2807 auto *InfoPtr = 2808 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 2809 llvm::GlobalVariable::PrivateLinkage, Info); 2810 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2811 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 2812 2813 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction( 2814 "__cfi_slowpath_diag", 2815 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, 2816 false)); 2817 CheckCall = Builder.CreateCall( 2818 SlowPathDiagFn, 2819 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)}); 2820 } else { 2821 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction( 2822 "__cfi_slowpath", 2823 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false)); 2824 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr}); 2825 } 2826 2827 CheckCall->setDoesNotThrow(); 2828 2829 EmitBlock(Cont); 2830 } 2831 2832 // Emit a stub for __cfi_check function so that the linker knows about this 2833 // symbol in LTO mode. 2834 void CodeGenFunction::EmitCfiCheckStub() { 2835 llvm::Module *M = &CGM.getModule(); 2836 auto &Ctx = M->getContext(); 2837 llvm::Function *F = llvm::Function::Create( 2838 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false), 2839 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M); 2840 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F); 2841 // FIXME: consider emitting an intrinsic call like 2842 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2) 2843 // which can be lowered in CrossDSOCFI pass to the actual contents of 2844 // __cfi_check. This would allow inlining of __cfi_check calls. 2845 llvm::CallInst::Create( 2846 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB); 2847 llvm::ReturnInst::Create(Ctx, nullptr, BB); 2848 } 2849 2850 // This function is basically a switch over the CFI failure kind, which is 2851 // extracted from CFICheckFailData (1st function argument). Each case is either 2852 // llvm.trap or a call to one of the two runtime handlers, based on 2853 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid 2854 // failure kind) traps, but this should really never happen. CFICheckFailData 2855 // can be nullptr if the calling module has -fsanitize-trap behavior for this 2856 // check kind; in this case __cfi_check_fail traps as well. 2857 void CodeGenFunction::EmitCfiCheckFail() { 2858 SanitizerScope SanScope(this); 2859 FunctionArgList Args; 2860 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy, 2861 ImplicitParamDecl::Other); 2862 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy, 2863 ImplicitParamDecl::Other); 2864 Args.push_back(&ArgData); 2865 Args.push_back(&ArgAddr); 2866 2867 const CGFunctionInfo &FI = 2868 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args); 2869 2870 llvm::Function *F = llvm::Function::Create( 2871 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false), 2872 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule()); 2873 F->setVisibility(llvm::GlobalValue::HiddenVisibility); 2874 2875 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args, 2876 SourceLocation()); 2877 2878 llvm::Value *Data = 2879 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false, 2880 CGM.getContext().VoidPtrTy, ArgData.getLocation()); 2881 llvm::Value *Addr = 2882 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false, 2883 CGM.getContext().VoidPtrTy, ArgAddr.getLocation()); 2884 2885 // Data == nullptr means the calling module has trap behaviour for this check. 2886 llvm::Value *DataIsNotNullPtr = 2887 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy)); 2888 EmitTrapCheck(DataIsNotNullPtr); 2889 2890 llvm::StructType *SourceLocationTy = 2891 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty); 2892 llvm::StructType *CfiCheckFailDataTy = 2893 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy); 2894 2895 llvm::Value *V = Builder.CreateConstGEP2_32( 2896 CfiCheckFailDataTy, 2897 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0, 2898 0); 2899 Address CheckKindAddr(V, getIntAlign()); 2900 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr); 2901 2902 llvm::Value *AllVtables = llvm::MetadataAsValue::get( 2903 CGM.getLLVMContext(), 2904 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 2905 llvm::Value *ValidVtable = Builder.CreateZExt( 2906 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), 2907 {Addr, AllVtables}), 2908 IntPtrTy); 2909 2910 const std::pair<int, SanitizerMask> CheckKinds[] = { 2911 {CFITCK_VCall, SanitizerKind::CFIVCall}, 2912 {CFITCK_NVCall, SanitizerKind::CFINVCall}, 2913 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast}, 2914 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast}, 2915 {CFITCK_ICall, SanitizerKind::CFIICall}}; 2916 2917 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks; 2918 for (auto CheckKindMaskPair : CheckKinds) { 2919 int Kind = CheckKindMaskPair.first; 2920 SanitizerMask Mask = CheckKindMaskPair.second; 2921 llvm::Value *Cond = 2922 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind)); 2923 if (CGM.getLangOpts().Sanitize.has(Mask)) 2924 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {}, 2925 {Data, Addr, ValidVtable}); 2926 else 2927 EmitTrapCheck(Cond); 2928 } 2929 2930 FinishFunction(); 2931 // The only reference to this function will be created during LTO link. 2932 // Make sure it survives until then. 2933 CGM.addUsedGlobal(F); 2934 } 2935 2936 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) { 2937 llvm::BasicBlock *Cont = createBasicBlock("cont"); 2938 2939 // If we're optimizing, collapse all calls to trap down to just one per 2940 // function to save on code size. 2941 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) { 2942 TrapBB = createBasicBlock("trap"); 2943 Builder.CreateCondBr(Checked, Cont, TrapBB); 2944 EmitBlock(TrapBB); 2945 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 2946 TrapCall->setDoesNotReturn(); 2947 TrapCall->setDoesNotThrow(); 2948 Builder.CreateUnreachable(); 2949 } else { 2950 Builder.CreateCondBr(Checked, Cont, TrapBB); 2951 } 2952 2953 EmitBlock(Cont); 2954 } 2955 2956 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) { 2957 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID)); 2958 2959 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) { 2960 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name", 2961 CGM.getCodeGenOpts().TrapFuncName); 2962 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A); 2963 } 2964 2965 return TrapCall; 2966 } 2967 2968 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E, 2969 LValueBaseInfo *BaseInfo) { 2970 assert(E->getType()->isArrayType() && 2971 "Array to pointer decay must have array source type!"); 2972 2973 // Expressions of array type can't be bitfields or vector elements. 2974 LValue LV = EmitLValue(E); 2975 Address Addr = LV.getAddress(); 2976 if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 2977 2978 // If the array type was an incomplete type, we need to make sure 2979 // the decay ends up being the right type. 2980 llvm::Type *NewTy = ConvertType(E->getType()); 2981 Addr = Builder.CreateElementBitCast(Addr, NewTy); 2982 2983 // Note that VLA pointers are always decayed, so we don't need to do 2984 // anything here. 2985 if (!E->getType()->isVariableArrayType()) { 2986 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 2987 "Expected pointer to array"); 2988 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay"); 2989 } 2990 2991 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType(); 2992 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType)); 2993 } 2994 2995 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 2996 /// array to pointer, return the array subexpression. 2997 static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 2998 // If this isn't just an array->pointer decay, bail out. 2999 const auto *CE = dyn_cast<CastExpr>(E); 3000 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay) 3001 return nullptr; 3002 3003 // If this is a decay from variable width array, bail out. 3004 const Expr *SubExpr = CE->getSubExpr(); 3005 if (SubExpr->getType()->isVariableArrayType()) 3006 return nullptr; 3007 3008 return SubExpr; 3009 } 3010 3011 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF, 3012 llvm::Value *ptr, 3013 ArrayRef<llvm::Value*> indices, 3014 bool inbounds, 3015 bool signedIndices, 3016 SourceLocation loc, 3017 const llvm::Twine &name = "arrayidx") { 3018 if (inbounds) { 3019 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices, loc, name); 3020 } else { 3021 return CGF.Builder.CreateGEP(ptr, indices, name); 3022 } 3023 } 3024 3025 static CharUnits getArrayElementAlign(CharUnits arrayAlign, 3026 llvm::Value *idx, 3027 CharUnits eltSize) { 3028 // If we have a constant index, we can use the exact offset of the 3029 // element we're accessing. 3030 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) { 3031 CharUnits offset = constantIdx->getZExtValue() * eltSize; 3032 return arrayAlign.alignmentAtOffset(offset); 3033 3034 // Otherwise, use the worst-case alignment for any element. 3035 } else { 3036 return arrayAlign.alignmentOfArrayElement(eltSize); 3037 } 3038 } 3039 3040 static QualType getFixedSizeElementType(const ASTContext &ctx, 3041 const VariableArrayType *vla) { 3042 QualType eltType; 3043 do { 3044 eltType = vla->getElementType(); 3045 } while ((vla = ctx.getAsVariableArrayType(eltType))); 3046 return eltType; 3047 } 3048 3049 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, 3050 ArrayRef<llvm::Value *> indices, 3051 QualType eltType, bool inbounds, 3052 bool signedIndices, SourceLocation loc, 3053 const llvm::Twine &name = "arrayidx") { 3054 // All the indices except that last must be zero. 3055 #ifndef NDEBUG 3056 for (auto idx : indices.drop_back()) 3057 assert(isa<llvm::ConstantInt>(idx) && 3058 cast<llvm::ConstantInt>(idx)->isZero()); 3059 #endif 3060 3061 // Determine the element size of the statically-sized base. This is 3062 // the thing that the indices are expressed in terms of. 3063 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) { 3064 eltType = getFixedSizeElementType(CGF.getContext(), vla); 3065 } 3066 3067 // We can use that to compute the best alignment of the element. 3068 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 3069 CharUnits eltAlign = 3070 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize); 3071 3072 llvm::Value *eltPtr = emitArraySubscriptGEP( 3073 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name); 3074 return Address(eltPtr, eltAlign); 3075 } 3076 3077 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 3078 bool Accessed) { 3079 // The index must always be an integer, which is not an aggregate. Emit it 3080 // in lexical order (this complexity is, sadly, required by C++17). 3081 llvm::Value *IdxPre = 3082 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr; 3083 bool SignedIndices = false; 3084 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * { 3085 auto *Idx = IdxPre; 3086 if (E->getLHS() != E->getIdx()) { 3087 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS"); 3088 Idx = EmitScalarExpr(E->getIdx()); 3089 } 3090 3091 QualType IdxTy = E->getIdx()->getType(); 3092 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType(); 3093 SignedIndices |= IdxSigned; 3094 3095 if (SanOpts.has(SanitizerKind::ArrayBounds)) 3096 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed); 3097 3098 // Extend or truncate the index type to 32 or 64-bits. 3099 if (Promote && Idx->getType() != IntPtrTy) 3100 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 3101 3102 return Idx; 3103 }; 3104 IdxPre = nullptr; 3105 3106 // If the base is a vector type, then we are forming a vector element lvalue 3107 // with this subscript. 3108 if (E->getBase()->getType()->isVectorType() && 3109 !isa<ExtVectorElementExpr>(E->getBase())) { 3110 // Emit the vector as an lvalue to get its address. 3111 LValue LHS = EmitLValue(E->getBase()); 3112 auto *Idx = EmitIdxAfterBase(/*Promote*/false); 3113 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 3114 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 3115 E->getBase()->getType(), 3116 LHS.getBaseInfo()); 3117 } 3118 3119 // All the other cases basically behave like simple offsetting. 3120 3121 // Handle the extvector case we ignored above. 3122 if (isa<ExtVectorElementExpr>(E->getBase())) { 3123 LValue LV = EmitLValue(E->getBase()); 3124 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3125 Address Addr = EmitExtVectorElementLValue(LV); 3126 3127 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType(); 3128 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true, 3129 SignedIndices, E->getExprLoc()); 3130 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo()); 3131 } 3132 3133 LValueBaseInfo BaseInfo; 3134 Address Addr = Address::invalid(); 3135 if (const VariableArrayType *vla = 3136 getContext().getAsVariableArrayType(E->getType())) { 3137 // The base must be a pointer, which is not an aggregate. Emit 3138 // it. It needs to be emitted first in case it's what captures 3139 // the VLA bounds. 3140 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo); 3141 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3142 3143 // The element count here is the total number of non-VLA elements. 3144 llvm::Value *numElements = getVLASize(vla).first; 3145 3146 // Effectively, the multiply by the VLA size is part of the GEP. 3147 // GEP indexes are signed, and scaling an index isn't permitted to 3148 // signed-overflow, so we use the same semantics for our explicit 3149 // multiply. We suppress this if overflow is not undefined behavior. 3150 if (getLangOpts().isSignedOverflowDefined()) { 3151 Idx = Builder.CreateMul(Idx, numElements); 3152 } else { 3153 Idx = Builder.CreateNSWMul(Idx, numElements); 3154 } 3155 3156 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(), 3157 !getLangOpts().isSignedOverflowDefined(), 3158 SignedIndices, E->getExprLoc()); 3159 3160 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 3161 // Indexing over an interface, as in "NSString *P; P[4];" 3162 3163 // Emit the base pointer. 3164 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo); 3165 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3166 3167 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT); 3168 llvm::Value *InterfaceSizeVal = 3169 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity()); 3170 3171 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal); 3172 3173 // We don't necessarily build correct LLVM struct types for ObjC 3174 // interfaces, so we can't rely on GEP to do this scaling 3175 // correctly, so we need to cast to i8*. FIXME: is this actually 3176 // true? A lot of other things in the fragile ABI would break... 3177 llvm::Type *OrigBaseTy = Addr.getType(); 3178 Addr = Builder.CreateElementBitCast(Addr, Int8Ty); 3179 3180 // Do the GEP. 3181 CharUnits EltAlign = 3182 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize); 3183 llvm::Value *EltPtr = 3184 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false, 3185 SignedIndices, E->getExprLoc()); 3186 Addr = Address(EltPtr, EltAlign); 3187 3188 // Cast back. 3189 Addr = Builder.CreateBitCast(Addr, OrigBaseTy); 3190 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3191 // If this is A[i] where A is an array, the frontend will have decayed the 3192 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3193 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3194 // "gep x, i" here. Emit one "gep A, 0, i". 3195 assert(Array->getType()->isArrayType() && 3196 "Array to pointer decay must have array source type!"); 3197 LValue ArrayLV; 3198 // For simple multidimensional array indexing, set the 'accessed' flag for 3199 // better bounds-checking of the base expression. 3200 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3201 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3202 else 3203 ArrayLV = EmitLValue(Array); 3204 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3205 3206 // Propagate the alignment from the array itself to the result. 3207 Addr = emitArraySubscriptGEP( 3208 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx}, 3209 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, 3210 E->getExprLoc()); 3211 BaseInfo = ArrayLV.getBaseInfo(); 3212 } else { 3213 // The base must be a pointer; emit it with an estimate of its alignment. 3214 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo); 3215 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3216 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(), 3217 !getLangOpts().isSignedOverflowDefined(), 3218 SignedIndices, E->getExprLoc()); 3219 } 3220 3221 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo); 3222 3223 // TODO: Preserve/extend path TBAA metadata? 3224 3225 if (getLangOpts().ObjC1 && 3226 getLangOpts().getGC() != LangOptions::NonGC) { 3227 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 3228 setObjCGCLValueClass(getContext(), E, LV); 3229 } 3230 return LV; 3231 } 3232 3233 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, 3234 LValueBaseInfo &BaseInfo, 3235 QualType BaseTy, QualType ElTy, 3236 bool IsLowerBound) { 3237 LValue BaseLVal; 3238 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) { 3239 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound); 3240 if (BaseTy->isArrayType()) { 3241 Address Addr = BaseLVal.getAddress(); 3242 BaseInfo = BaseLVal.getBaseInfo(); 3243 3244 // If the array type was an incomplete type, we need to make sure 3245 // the decay ends up being the right type. 3246 llvm::Type *NewTy = CGF.ConvertType(BaseTy); 3247 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy); 3248 3249 // Note that VLA pointers are always decayed, so we don't need to do 3250 // anything here. 3251 if (!BaseTy->isVariableArrayType()) { 3252 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 3253 "Expected pointer to array"); 3254 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), 3255 "arraydecay"); 3256 } 3257 3258 return CGF.Builder.CreateElementBitCast(Addr, 3259 CGF.ConvertTypeForMem(ElTy)); 3260 } 3261 LValueBaseInfo TypeInfo; 3262 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo); 3263 BaseInfo.mergeForCast(TypeInfo); 3264 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align); 3265 } 3266 return CGF.EmitPointerWithAlignment(Base, &BaseInfo); 3267 } 3268 3269 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3270 bool IsLowerBound) { 3271 QualType BaseTy; 3272 if (auto *ASE = 3273 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts())) 3274 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE); 3275 else 3276 BaseTy = E->getBase()->getType(); 3277 QualType ResultExprTy; 3278 if (auto *AT = getContext().getAsArrayType(BaseTy)) 3279 ResultExprTy = AT->getElementType(); 3280 else 3281 ResultExprTy = BaseTy->getPointeeType(); 3282 llvm::Value *Idx = nullptr; 3283 if (IsLowerBound || E->getColonLoc().isInvalid()) { 3284 // Requesting lower bound or upper bound, but without provided length and 3285 // without ':' symbol for the default length -> length = 1. 3286 // Idx = LowerBound ?: 0; 3287 if (auto *LowerBound = E->getLowerBound()) { 3288 Idx = Builder.CreateIntCast( 3289 EmitScalarExpr(LowerBound), IntPtrTy, 3290 LowerBound->getType()->hasSignedIntegerRepresentation()); 3291 } else 3292 Idx = llvm::ConstantInt::getNullValue(IntPtrTy); 3293 } else { 3294 // Try to emit length or lower bound as constant. If this is possible, 1 3295 // is subtracted from constant length or lower bound. Otherwise, emit LLVM 3296 // IR (LB + Len) - 1. 3297 auto &C = CGM.getContext(); 3298 auto *Length = E->getLength(); 3299 llvm::APSInt ConstLength; 3300 if (Length) { 3301 // Idx = LowerBound + Length - 1; 3302 if (Length->isIntegerConstantExpr(ConstLength, C)) { 3303 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3304 Length = nullptr; 3305 } 3306 auto *LowerBound = E->getLowerBound(); 3307 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false); 3308 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) { 3309 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits); 3310 LowerBound = nullptr; 3311 } 3312 if (!Length) 3313 --ConstLength; 3314 else if (!LowerBound) 3315 --ConstLowerBound; 3316 3317 if (Length || LowerBound) { 3318 auto *LowerBoundVal = 3319 LowerBound 3320 ? Builder.CreateIntCast( 3321 EmitScalarExpr(LowerBound), IntPtrTy, 3322 LowerBound->getType()->hasSignedIntegerRepresentation()) 3323 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound); 3324 auto *LengthVal = 3325 Length 3326 ? Builder.CreateIntCast( 3327 EmitScalarExpr(Length), IntPtrTy, 3328 Length->getType()->hasSignedIntegerRepresentation()) 3329 : llvm::ConstantInt::get(IntPtrTy, ConstLength); 3330 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len", 3331 /*HasNUW=*/false, 3332 !getLangOpts().isSignedOverflowDefined()); 3333 if (Length && LowerBound) { 3334 Idx = Builder.CreateSub( 3335 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1", 3336 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3337 } 3338 } else 3339 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound); 3340 } else { 3341 // Idx = ArraySize - 1; 3342 QualType ArrayTy = BaseTy->isPointerType() 3343 ? E->getBase()->IgnoreParenImpCasts()->getType() 3344 : BaseTy; 3345 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) { 3346 Length = VAT->getSizeExpr(); 3347 if (Length->isIntegerConstantExpr(ConstLength, C)) 3348 Length = nullptr; 3349 } else { 3350 auto *CAT = C.getAsConstantArrayType(ArrayTy); 3351 ConstLength = CAT->getSize(); 3352 } 3353 if (Length) { 3354 auto *LengthVal = Builder.CreateIntCast( 3355 EmitScalarExpr(Length), IntPtrTy, 3356 Length->getType()->hasSignedIntegerRepresentation()); 3357 Idx = Builder.CreateSub( 3358 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1", 3359 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3360 } else { 3361 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3362 --ConstLength; 3363 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength); 3364 } 3365 } 3366 } 3367 assert(Idx); 3368 3369 Address EltPtr = Address::invalid(); 3370 LValueBaseInfo BaseInfo; 3371 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) { 3372 // The base must be a pointer, which is not an aggregate. Emit 3373 // it. It needs to be emitted first in case it's what captures 3374 // the VLA bounds. 3375 Address Base = 3376 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy, 3377 VLA->getElementType(), IsLowerBound); 3378 // The element count here is the total number of non-VLA elements. 3379 llvm::Value *NumElements = getVLASize(VLA).first; 3380 3381 // Effectively, the multiply by the VLA size is part of the GEP. 3382 // GEP indexes are signed, and scaling an index isn't permitted to 3383 // signed-overflow, so we use the same semantics for our explicit 3384 // multiply. We suppress this if overflow is not undefined behavior. 3385 if (getLangOpts().isSignedOverflowDefined()) 3386 Idx = Builder.CreateMul(Idx, NumElements); 3387 else 3388 Idx = Builder.CreateNSWMul(Idx, NumElements); 3389 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(), 3390 !getLangOpts().isSignedOverflowDefined(), 3391 /*SignedIndices=*/false, E->getExprLoc()); 3392 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3393 // If this is A[i] where A is an array, the frontend will have decayed the 3394 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3395 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3396 // "gep x, i" here. Emit one "gep A, 0, i". 3397 assert(Array->getType()->isArrayType() && 3398 "Array to pointer decay must have array source type!"); 3399 LValue ArrayLV; 3400 // For simple multidimensional array indexing, set the 'accessed' flag for 3401 // better bounds-checking of the base expression. 3402 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3403 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3404 else 3405 ArrayLV = EmitLValue(Array); 3406 3407 // Propagate the alignment from the array itself to the result. 3408 EltPtr = emitArraySubscriptGEP( 3409 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx}, 3410 ResultExprTy, !getLangOpts().isSignedOverflowDefined(), 3411 /*SignedIndices=*/false, E->getExprLoc()); 3412 BaseInfo = ArrayLV.getBaseInfo(); 3413 } else { 3414 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, 3415 BaseTy, ResultExprTy, IsLowerBound); 3416 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy, 3417 !getLangOpts().isSignedOverflowDefined(), 3418 /*SignedIndices=*/false, E->getExprLoc()); 3419 } 3420 3421 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo); 3422 } 3423 3424 LValue CodeGenFunction:: 3425 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 3426 // Emit the base vector as an l-value. 3427 LValue Base; 3428 3429 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 3430 if (E->isArrow()) { 3431 // If it is a pointer to a vector, emit the address and form an lvalue with 3432 // it. 3433 LValueBaseInfo BaseInfo; 3434 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo); 3435 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 3436 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo); 3437 Base.getQuals().removeObjCGCAttr(); 3438 } else if (E->getBase()->isGLValue()) { 3439 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 3440 // emit the base as an lvalue. 3441 assert(E->getBase()->getType()->isVectorType()); 3442 Base = EmitLValue(E->getBase()); 3443 } else { 3444 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 3445 assert(E->getBase()->getType()->isVectorType() && 3446 "Result must be a vector"); 3447 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 3448 3449 // Store the vector to memory (because LValue wants an address). 3450 Address VecMem = CreateMemTemp(E->getBase()->getType()); 3451 Builder.CreateStore(Vec, VecMem); 3452 Base = MakeAddrLValue(VecMem, E->getBase()->getType(), 3453 LValueBaseInfo(AlignmentSource::Decl, false)); 3454 } 3455 3456 QualType type = 3457 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers()); 3458 3459 // Encode the element access list into a vector of unsigned indices. 3460 SmallVector<uint32_t, 4> Indices; 3461 E->getEncodedElementAccess(Indices); 3462 3463 if (Base.isSimple()) { 3464 llvm::Constant *CV = 3465 llvm::ConstantDataVector::get(getLLVMContext(), Indices); 3466 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type, 3467 Base.getBaseInfo()); 3468 } 3469 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 3470 3471 llvm::Constant *BaseElts = Base.getExtVectorElts(); 3472 SmallVector<llvm::Constant *, 4> CElts; 3473 3474 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 3475 CElts.push_back(BaseElts->getAggregateElement(Indices[i])); 3476 llvm::Constant *CV = llvm::ConstantVector::get(CElts); 3477 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type, 3478 Base.getBaseInfo()); 3479 } 3480 3481 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 3482 Expr *BaseExpr = E->getBase(); 3483 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 3484 LValue BaseLV; 3485 if (E->isArrow()) { 3486 LValueBaseInfo BaseInfo; 3487 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo); 3488 QualType PtrTy = BaseExpr->getType()->getPointeeType(); 3489 SanitizerSet SkippedChecks; 3490 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr); 3491 if (IsBaseCXXThis) 3492 SkippedChecks.set(SanitizerKind::Alignment, true); 3493 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr)) 3494 SkippedChecks.set(SanitizerKind::Null, true); 3495 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy, 3496 /*Alignment=*/CharUnits::Zero(), SkippedChecks); 3497 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo); 3498 } else 3499 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess); 3500 3501 NamedDecl *ND = E->getMemberDecl(); 3502 if (auto *Field = dyn_cast<FieldDecl>(ND)) { 3503 LValue LV = EmitLValueForField(BaseLV, Field); 3504 setObjCGCLValueClass(getContext(), E, LV); 3505 return LV; 3506 } 3507 3508 if (auto *VD = dyn_cast<VarDecl>(ND)) 3509 return EmitGlobalVarDeclLValue(*this, E, VD); 3510 3511 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 3512 return EmitFunctionDeclLValue(*this, E, FD); 3513 3514 llvm_unreachable("Unhandled member declaration!"); 3515 } 3516 3517 /// Given that we are currently emitting a lambda, emit an l-value for 3518 /// one of its members. 3519 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) { 3520 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda()); 3521 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent()); 3522 QualType LambdaTagType = 3523 getContext().getTagDeclType(Field->getParent()); 3524 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType); 3525 return EmitLValueForField(LambdaLV, Field); 3526 } 3527 3528 /// Drill down to the storage of a field without walking into 3529 /// reference types. 3530 /// 3531 /// The resulting address doesn't necessarily have the right type. 3532 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, 3533 const FieldDecl *field) { 3534 const RecordDecl *rec = field->getParent(); 3535 3536 unsigned idx = 3537 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 3538 3539 CharUnits offset; 3540 // Adjust the alignment down to the given offset. 3541 // As a special case, if the LLVM field index is 0, we know that this 3542 // is zero. 3543 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec) 3544 .getFieldOffset(field->getFieldIndex()) == 0) && 3545 "LLVM field at index zero had non-zero offset?"); 3546 if (idx != 0) { 3547 auto &recLayout = CGF.getContext().getASTRecordLayout(rec); 3548 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex()); 3549 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits); 3550 } 3551 3552 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName()); 3553 } 3554 3555 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) { 3556 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl(); 3557 if (!RD) 3558 return false; 3559 3560 if (RD->isDynamicClass()) 3561 return true; 3562 3563 for (const auto &Base : RD->bases()) 3564 if (hasAnyVptr(Base.getType(), Context)) 3565 return true; 3566 3567 for (const FieldDecl *Field : RD->fields()) 3568 if (hasAnyVptr(Field->getType(), Context)) 3569 return true; 3570 3571 return false; 3572 } 3573 3574 LValue CodeGenFunction::EmitLValueForField(LValue base, 3575 const FieldDecl *field) { 3576 LValueBaseInfo BaseInfo = base.getBaseInfo(); 3577 AlignmentSource fieldAlignSource = 3578 getFieldAlignmentSource(BaseInfo.getAlignmentSource()); 3579 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias()); 3580 3581 const RecordDecl *rec = field->getParent(); 3582 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>()) 3583 FieldBaseInfo.setMayAlias(true); 3584 bool mayAlias = FieldBaseInfo.getMayAlias(); 3585 3586 if (field->isBitField()) { 3587 const CGRecordLayout &RL = 3588 CGM.getTypes().getCGRecordLayout(field->getParent()); 3589 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field); 3590 Address Addr = base.getAddress(); 3591 unsigned Idx = RL.getLLVMFieldNo(field); 3592 if (Idx != 0) 3593 // For structs, we GEP to the field that the record layout suggests. 3594 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset, 3595 field->getName()); 3596 // Get the access type. 3597 llvm::Type *FieldIntTy = 3598 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize); 3599 if (Addr.getElementType() != FieldIntTy) 3600 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy); 3601 3602 QualType fieldType = 3603 field->getType().withCVRQualifiers(base.getVRQualifiers()); 3604 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo); 3605 } 3606 3607 QualType type = field->getType(); 3608 Address addr = base.getAddress(); 3609 unsigned cvr = base.getVRQualifiers(); 3610 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA; 3611 if (rec->isUnion()) { 3612 // For unions, there is no pointer adjustment. 3613 assert(!type->isReferenceType() && "union has reference member"); 3614 // TODO: handle path-aware TBAA for union. 3615 TBAAPath = false; 3616 3617 const auto FieldType = field->getType(); 3618 if (CGM.getCodeGenOpts().StrictVTablePointers && 3619 hasAnyVptr(FieldType, getContext())) 3620 // Because unions can easily skip invariant.barriers, we need to add 3621 // a barrier every time CXXRecord field with vptr is referenced. 3622 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()), 3623 addr.getAlignment()); 3624 } else { 3625 // For structs, we GEP to the field that the record layout suggests. 3626 addr = emitAddrOfFieldStorage(*this, addr, field); 3627 3628 // If this is a reference field, load the reference right now. 3629 if (const ReferenceType *refType = type->getAs<ReferenceType>()) { 3630 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref"); 3631 if (cvr & Qualifiers::Volatile) load->setVolatile(true); 3632 3633 // Loading the reference will disable path-aware TBAA. 3634 TBAAPath = false; 3635 if (CGM.shouldUseTBAA()) { 3636 llvm::MDNode *tbaa; 3637 if (mayAlias) 3638 tbaa = CGM.getTBAAInfo(getContext().CharTy); 3639 else 3640 tbaa = CGM.getTBAAInfo(type); 3641 if (tbaa) 3642 CGM.DecorateInstructionWithTBAA(load, tbaa); 3643 } 3644 3645 mayAlias = false; 3646 type = refType->getPointeeType(); 3647 3648 CharUnits alignment = 3649 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true); 3650 FieldBaseInfo.setMayAlias(false); 3651 addr = Address(load, alignment); 3652 3653 // Qualifiers on the struct don't apply to the referencee, and 3654 // we'll pick up CVR from the actual type later, so reset these 3655 // additional qualifiers now. 3656 cvr = 0; 3657 } 3658 } 3659 3660 // Make sure that the address is pointing to the right type. This is critical 3661 // for both unions and structs. A union needs a bitcast, a struct element 3662 // will need a bitcast if the LLVM type laid out doesn't match the desired 3663 // type. 3664 addr = Builder.CreateElementBitCast(addr, 3665 CGM.getTypes().ConvertTypeForMem(type), 3666 field->getName()); 3667 3668 if (field->hasAttr<AnnotateAttr>()) 3669 addr = EmitFieldAnnotations(field, addr); 3670 3671 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo); 3672 LV.getQuals().addCVRQualifiers(cvr); 3673 if (TBAAPath) { 3674 const ASTRecordLayout &Layout = 3675 getContext().getASTRecordLayout(field->getParent()); 3676 // Set the base type to be the base type of the base LValue and 3677 // update offset to be relative to the base type. 3678 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType()); 3679 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() + 3680 Layout.getFieldOffset(field->getFieldIndex()) / 3681 getContext().getCharWidth()); 3682 } 3683 3684 // __weak attribute on a field is ignored. 3685 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 3686 LV.getQuals().removeObjCGCAttr(); 3687 3688 // Fields of may_alias structs act like 'char' for TBAA purposes. 3689 // FIXME: this should get propagated down through anonymous structs 3690 // and unions. 3691 if (mayAlias && LV.getTBAAInfo()) 3692 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy)); 3693 3694 return LV; 3695 } 3696 3697 LValue 3698 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base, 3699 const FieldDecl *Field) { 3700 QualType FieldType = Field->getType(); 3701 3702 if (!FieldType->isReferenceType()) 3703 return EmitLValueForField(Base, Field); 3704 3705 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field); 3706 3707 // Make sure that the address is pointing to the right type. 3708 llvm::Type *llvmType = ConvertTypeForMem(FieldType); 3709 V = Builder.CreateElementBitCast(V, llvmType, Field->getName()); 3710 3711 // TODO: access-path TBAA? 3712 LValueBaseInfo BaseInfo = Base.getBaseInfo(); 3713 LValueBaseInfo FieldBaseInfo( 3714 getFieldAlignmentSource(BaseInfo.getAlignmentSource()), 3715 BaseInfo.getMayAlias()); 3716 return MakeAddrLValue(V, FieldType, FieldBaseInfo); 3717 } 3718 3719 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 3720 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 3721 if (E->isFileScope()) { 3722 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E); 3723 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo); 3724 } 3725 if (E->getType()->isVariablyModifiedType()) 3726 // make sure to emit the VLA size. 3727 EmitVariablyModifiedType(E->getType()); 3728 3729 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 3730 const Expr *InitExpr = E->getInitializer(); 3731 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo); 3732 3733 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(), 3734 /*Init*/ true); 3735 3736 return Result; 3737 } 3738 3739 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { 3740 if (!E->isGLValue()) 3741 // Initializing an aggregate temporary in C++11: T{...}. 3742 return EmitAggExprToLValue(E); 3743 3744 // An lvalue initializer list must be initializing a reference. 3745 assert(E->isTransparent() && "non-transparent glvalue init list"); 3746 return EmitLValue(E->getInit(0)); 3747 } 3748 3749 /// Emit the operand of a glvalue conditional operator. This is either a glvalue 3750 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no 3751 /// LValue is returned and the current block has been terminated. 3752 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, 3753 const Expr *Operand) { 3754 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) { 3755 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false); 3756 return None; 3757 } 3758 3759 return CGF.EmitLValue(Operand); 3760 } 3761 3762 LValue CodeGenFunction:: 3763 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) { 3764 if (!expr->isGLValue()) { 3765 // ?: here should be an aggregate. 3766 assert(hasAggregateEvaluationKind(expr->getType()) && 3767 "Unexpected conditional operator!"); 3768 return EmitAggExprToLValue(expr); 3769 } 3770 3771 OpaqueValueMapping binding(*this, expr); 3772 3773 const Expr *condExpr = expr->getCond(); 3774 bool CondExprBool; 3775 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 3776 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr(); 3777 if (!CondExprBool) std::swap(live, dead); 3778 3779 if (!ContainsLabel(dead)) { 3780 // If the true case is live, we need to track its region. 3781 if (CondExprBool) 3782 incrementProfileCounter(expr); 3783 return EmitLValue(live); 3784 } 3785 } 3786 3787 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true"); 3788 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false"); 3789 llvm::BasicBlock *contBlock = createBasicBlock("cond.end"); 3790 3791 ConditionalEvaluation eval(*this); 3792 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr)); 3793 3794 // Any temporaries created here are conditional. 3795 EmitBlock(lhsBlock); 3796 incrementProfileCounter(expr); 3797 eval.begin(*this); 3798 Optional<LValue> lhs = 3799 EmitLValueOrThrowExpression(*this, expr->getTrueExpr()); 3800 eval.end(*this); 3801 3802 if (lhs && !lhs->isSimple()) 3803 return EmitUnsupportedLValue(expr, "conditional operator"); 3804 3805 lhsBlock = Builder.GetInsertBlock(); 3806 if (lhs) 3807 Builder.CreateBr(contBlock); 3808 3809 // Any temporaries created here are conditional. 3810 EmitBlock(rhsBlock); 3811 eval.begin(*this); 3812 Optional<LValue> rhs = 3813 EmitLValueOrThrowExpression(*this, expr->getFalseExpr()); 3814 eval.end(*this); 3815 if (rhs && !rhs->isSimple()) 3816 return EmitUnsupportedLValue(expr, "conditional operator"); 3817 rhsBlock = Builder.GetInsertBlock(); 3818 3819 EmitBlock(contBlock); 3820 3821 if (lhs && rhs) { 3822 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(), 3823 2, "cond-lvalue"); 3824 phi->addIncoming(lhs->getPointer(), lhsBlock); 3825 phi->addIncoming(rhs->getPointer(), rhsBlock); 3826 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment())); 3827 AlignmentSource alignSource = 3828 std::max(lhs->getBaseInfo().getAlignmentSource(), 3829 rhs->getBaseInfo().getAlignmentSource()); 3830 bool MayAlias = lhs->getBaseInfo().getMayAlias() || 3831 rhs->getBaseInfo().getMayAlias(); 3832 return MakeAddrLValue(result, expr->getType(), 3833 LValueBaseInfo(alignSource, MayAlias)); 3834 } else { 3835 assert((lhs || rhs) && 3836 "both operands of glvalue conditional are throw-expressions?"); 3837 return lhs ? *lhs : *rhs; 3838 } 3839 } 3840 3841 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference 3842 /// type. If the cast is to a reference, we can have the usual lvalue result, 3843 /// otherwise if a cast is needed by the code generator in an lvalue context, 3844 /// then it must mean that we need the address of an aggregate in order to 3845 /// access one of its members. This can happen for all the reasons that casts 3846 /// are permitted with aggregate result, including noop aggregate casts, and 3847 /// cast from scalar to union. 3848 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 3849 switch (E->getCastKind()) { 3850 case CK_ToVoid: 3851 case CK_BitCast: 3852 case CK_ArrayToPointerDecay: 3853 case CK_FunctionToPointerDecay: 3854 case CK_NullToMemberPointer: 3855 case CK_NullToPointer: 3856 case CK_IntegralToPointer: 3857 case CK_PointerToIntegral: 3858 case CK_PointerToBoolean: 3859 case CK_VectorSplat: 3860 case CK_IntegralCast: 3861 case CK_BooleanToSignedIntegral: 3862 case CK_IntegralToBoolean: 3863 case CK_IntegralToFloating: 3864 case CK_FloatingToIntegral: 3865 case CK_FloatingToBoolean: 3866 case CK_FloatingCast: 3867 case CK_FloatingRealToComplex: 3868 case CK_FloatingComplexToReal: 3869 case CK_FloatingComplexToBoolean: 3870 case CK_FloatingComplexCast: 3871 case CK_FloatingComplexToIntegralComplex: 3872 case CK_IntegralRealToComplex: 3873 case CK_IntegralComplexToReal: 3874 case CK_IntegralComplexToBoolean: 3875 case CK_IntegralComplexCast: 3876 case CK_IntegralComplexToFloatingComplex: 3877 case CK_DerivedToBaseMemberPointer: 3878 case CK_BaseToDerivedMemberPointer: 3879 case CK_MemberPointerToBoolean: 3880 case CK_ReinterpretMemberPointer: 3881 case CK_AnyPointerToBlockPointerCast: 3882 case CK_ARCProduceObject: 3883 case CK_ARCConsumeObject: 3884 case CK_ARCReclaimReturnedObject: 3885 case CK_ARCExtendBlockObject: 3886 case CK_CopyAndAutoreleaseBlockObject: 3887 case CK_AddressSpaceConversion: 3888 case CK_IntToOCLSampler: 3889 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 3890 3891 case CK_Dependent: 3892 llvm_unreachable("dependent cast kind in IR gen!"); 3893 3894 case CK_BuiltinFnToFnPtr: 3895 llvm_unreachable("builtin functions are handled elsewhere"); 3896 3897 // These are never l-values; just use the aggregate emission code. 3898 case CK_NonAtomicToAtomic: 3899 case CK_AtomicToNonAtomic: 3900 return EmitAggExprToLValue(E); 3901 3902 case CK_Dynamic: { 3903 LValue LV = EmitLValue(E->getSubExpr()); 3904 Address V = LV.getAddress(); 3905 const auto *DCE = cast<CXXDynamicCastExpr>(E); 3906 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 3907 } 3908 3909 case CK_ConstructorConversion: 3910 case CK_UserDefinedConversion: 3911 case CK_CPointerToObjCPointerCast: 3912 case CK_BlockPointerToObjCPointerCast: 3913 case CK_NoOp: 3914 case CK_LValueToRValue: 3915 return EmitLValue(E->getSubExpr()); 3916 3917 case CK_UncheckedDerivedToBase: 3918 case CK_DerivedToBase: { 3919 const RecordType *DerivedClassTy = 3920 E->getSubExpr()->getType()->getAs<RecordType>(); 3921 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 3922 3923 LValue LV = EmitLValue(E->getSubExpr()); 3924 Address This = LV.getAddress(); 3925 3926 // Perform the derived-to-base conversion 3927 Address Base = GetAddressOfBaseClass( 3928 This, DerivedClassDecl, E->path_begin(), E->path_end(), 3929 /*NullCheckValue=*/false, E->getExprLoc()); 3930 3931 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo()); 3932 } 3933 case CK_ToUnion: 3934 return EmitAggExprToLValue(E); 3935 case CK_BaseToDerived: { 3936 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>(); 3937 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 3938 3939 LValue LV = EmitLValue(E->getSubExpr()); 3940 3941 // Perform the base-to-derived conversion 3942 Address Derived = 3943 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 3944 E->path_begin(), E->path_end(), 3945 /*NullCheckValue=*/false); 3946 3947 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is 3948 // performed and the object is not of the derived type. 3949 if (sanitizePerformTypeCheck()) 3950 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(), 3951 Derived.getPointer(), E->getType()); 3952 3953 if (SanOpts.has(SanitizerKind::CFIDerivedCast)) 3954 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(), 3955 /*MayBeNull=*/false, 3956 CFITCK_DerivedCast, E->getLocStart()); 3957 3958 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo()); 3959 } 3960 case CK_LValueBitCast: { 3961 // This must be a reinterpret_cast (or c-style equivalent). 3962 const auto *CE = cast<ExplicitCastExpr>(E); 3963 3964 CGM.EmitExplicitCastExprType(CE, this); 3965 LValue LV = EmitLValue(E->getSubExpr()); 3966 Address V = Builder.CreateBitCast(LV.getAddress(), 3967 ConvertType(CE->getTypeAsWritten())); 3968 3969 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) 3970 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(), 3971 /*MayBeNull=*/false, 3972 CFITCK_UnrelatedCast, E->getLocStart()); 3973 3974 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo()); 3975 } 3976 case CK_ObjCObjectLValueCast: { 3977 LValue LV = EmitLValue(E->getSubExpr()); 3978 Address V = Builder.CreateElementBitCast(LV.getAddress(), 3979 ConvertType(E->getType())); 3980 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo()); 3981 } 3982 case CK_ZeroToOCLQueue: 3983 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid"); 3984 case CK_ZeroToOCLEvent: 3985 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid"); 3986 } 3987 3988 llvm_unreachable("Unhandled lvalue cast kind?"); 3989 } 3990 3991 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 3992 assert(OpaqueValueMappingData::shouldBindAsLValue(e)); 3993 return getOpaqueLValueMapping(e); 3994 } 3995 3996 RValue CodeGenFunction::EmitRValueForField(LValue LV, 3997 const FieldDecl *FD, 3998 SourceLocation Loc) { 3999 QualType FT = FD->getType(); 4000 LValue FieldLV = EmitLValueForField(LV, FD); 4001 switch (getEvaluationKind(FT)) { 4002 case TEK_Complex: 4003 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc)); 4004 case TEK_Aggregate: 4005 return FieldLV.asAggregateRValue(); 4006 case TEK_Scalar: 4007 // This routine is used to load fields one-by-one to perform a copy, so 4008 // don't load reference fields. 4009 if (FD->getType()->isReferenceType()) 4010 return RValue::get(FieldLV.getPointer()); 4011 return EmitLoadOfLValue(FieldLV, Loc); 4012 } 4013 llvm_unreachable("bad evaluation kind"); 4014 } 4015 4016 //===--------------------------------------------------------------------===// 4017 // Expression Emission 4018 //===--------------------------------------------------------------------===// 4019 4020 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 4021 ReturnValueSlot ReturnValue) { 4022 // Builtins never have block type. 4023 if (E->getCallee()->getType()->isBlockPointerType()) 4024 return EmitBlockCallExpr(E, ReturnValue); 4025 4026 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E)) 4027 return EmitCXXMemberCallExpr(CE, ReturnValue); 4028 4029 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E)) 4030 return EmitCUDAKernelCallExpr(CE, ReturnValue); 4031 4032 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E)) 4033 if (const CXXMethodDecl *MD = 4034 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) 4035 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 4036 4037 CGCallee callee = EmitCallee(E->getCallee()); 4038 4039 if (callee.isBuiltin()) { 4040 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(), 4041 E, ReturnValue); 4042 } 4043 4044 if (callee.isPseudoDestructor()) { 4045 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr()); 4046 } 4047 4048 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue); 4049 } 4050 4051 /// Emit a CallExpr without considering whether it might be a subclass. 4052 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E, 4053 ReturnValueSlot ReturnValue) { 4054 CGCallee Callee = EmitCallee(E->getCallee()); 4055 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue); 4056 } 4057 4058 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) { 4059 if (auto builtinID = FD->getBuiltinID()) { 4060 return CGCallee::forBuiltin(builtinID, FD); 4061 } 4062 4063 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD); 4064 return CGCallee::forDirect(calleePtr, FD); 4065 } 4066 4067 CGCallee CodeGenFunction::EmitCallee(const Expr *E) { 4068 E = E->IgnoreParens(); 4069 4070 // Look through function-to-pointer decay. 4071 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) { 4072 if (ICE->getCastKind() == CK_FunctionToPointerDecay || 4073 ICE->getCastKind() == CK_BuiltinFnToFnPtr) { 4074 return EmitCallee(ICE->getSubExpr()); 4075 } 4076 4077 // Resolve direct calls. 4078 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) { 4079 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 4080 return EmitDirectCallee(*this, FD); 4081 } 4082 } else if (auto ME = dyn_cast<MemberExpr>(E)) { 4083 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) { 4084 EmitIgnoredExpr(ME->getBase()); 4085 return EmitDirectCallee(*this, FD); 4086 } 4087 4088 // Look through template substitutions. 4089 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 4090 return EmitCallee(NTTP->getReplacement()); 4091 4092 // Treat pseudo-destructor calls differently. 4093 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) { 4094 return CGCallee::forPseudoDestructor(PDE); 4095 } 4096 4097 // Otherwise, we have an indirect reference. 4098 llvm::Value *calleePtr; 4099 QualType functionType; 4100 if (auto ptrType = E->getType()->getAs<PointerType>()) { 4101 calleePtr = EmitScalarExpr(E); 4102 functionType = ptrType->getPointeeType(); 4103 } else { 4104 functionType = E->getType(); 4105 calleePtr = EmitLValue(E).getPointer(); 4106 } 4107 assert(functionType->isFunctionType()); 4108 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), 4109 E->getReferencedDeclOfCallee()); 4110 CGCallee callee(calleeInfo, calleePtr); 4111 return callee; 4112 } 4113 4114 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 4115 // Comma expressions just emit their LHS then their RHS as an l-value. 4116 if (E->getOpcode() == BO_Comma) { 4117 EmitIgnoredExpr(E->getLHS()); 4118 EnsureInsertPoint(); 4119 return EmitLValue(E->getRHS()); 4120 } 4121 4122 if (E->getOpcode() == BO_PtrMemD || 4123 E->getOpcode() == BO_PtrMemI) 4124 return EmitPointerToDataMemberBinaryExpr(E); 4125 4126 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 4127 4128 // Note that in all of these cases, __block variables need the RHS 4129 // evaluated first just in case the variable gets moved by the RHS. 4130 4131 switch (getEvaluationKind(E->getType())) { 4132 case TEK_Scalar: { 4133 switch (E->getLHS()->getType().getObjCLifetime()) { 4134 case Qualifiers::OCL_Strong: 4135 return EmitARCStoreStrong(E, /*ignored*/ false).first; 4136 4137 case Qualifiers::OCL_Autoreleasing: 4138 return EmitARCStoreAutoreleasing(E).first; 4139 4140 // No reason to do any of these differently. 4141 case Qualifiers::OCL_None: 4142 case Qualifiers::OCL_ExplicitNone: 4143 case Qualifiers::OCL_Weak: 4144 break; 4145 } 4146 4147 RValue RV = EmitAnyExpr(E->getRHS()); 4148 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); 4149 if (RV.isScalar()) 4150 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc()); 4151 EmitStoreThroughLValue(RV, LV); 4152 return LV; 4153 } 4154 4155 case TEK_Complex: 4156 return EmitComplexAssignmentLValue(E); 4157 4158 case TEK_Aggregate: 4159 return EmitAggExprToLValue(E); 4160 } 4161 llvm_unreachable("bad evaluation kind"); 4162 } 4163 4164 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 4165 RValue RV = EmitCallExpr(E); 4166 4167 if (!RV.isScalar()) 4168 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4169 LValueBaseInfo(AlignmentSource::Decl, false)); 4170 4171 assert(E->getCallReturnType(getContext())->isReferenceType() && 4172 "Can't have a scalar return unless the return type is a " 4173 "reference type!"); 4174 4175 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 4176 } 4177 4178 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 4179 // FIXME: This shouldn't require another copy. 4180 return EmitAggExprToLValue(E); 4181 } 4182 4183 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 4184 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 4185 && "binding l-value to type which needs a temporary"); 4186 AggValueSlot Slot = CreateAggTemp(E->getType()); 4187 EmitCXXConstructExpr(E, Slot); 4188 return MakeAddrLValue(Slot.getAddress(), E->getType(), 4189 LValueBaseInfo(AlignmentSource::Decl, false)); 4190 } 4191 4192 LValue 4193 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 4194 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 4195 } 4196 4197 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) { 4198 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E), 4199 ConvertType(E->getType())); 4200 } 4201 4202 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) { 4203 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(), 4204 LValueBaseInfo(AlignmentSource::Decl, false)); 4205 } 4206 4207 LValue 4208 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 4209 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 4210 Slot.setExternallyDestructed(); 4211 EmitAggExpr(E->getSubExpr(), Slot); 4212 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress()); 4213 return MakeAddrLValue(Slot.getAddress(), E->getType(), 4214 LValueBaseInfo(AlignmentSource::Decl, false)); 4215 } 4216 4217 LValue 4218 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) { 4219 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 4220 EmitLambdaExpr(E, Slot); 4221 return MakeAddrLValue(Slot.getAddress(), E->getType(), 4222 LValueBaseInfo(AlignmentSource::Decl, false)); 4223 } 4224 4225 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 4226 RValue RV = EmitObjCMessageExpr(E); 4227 4228 if (!RV.isScalar()) 4229 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4230 LValueBaseInfo(AlignmentSource::Decl, false)); 4231 4232 assert(E->getMethodDecl()->getReturnType()->isReferenceType() && 4233 "Can't have a scalar return unless the return type is a " 4234 "reference type!"); 4235 4236 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 4237 } 4238 4239 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 4240 Address V = 4241 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector()); 4242 return MakeAddrLValue(V, E->getType(), 4243 LValueBaseInfo(AlignmentSource::Decl, false)); 4244 } 4245 4246 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 4247 const ObjCIvarDecl *Ivar) { 4248 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 4249 } 4250 4251 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 4252 llvm::Value *BaseValue, 4253 const ObjCIvarDecl *Ivar, 4254 unsigned CVRQualifiers) { 4255 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 4256 Ivar, CVRQualifiers); 4257 } 4258 4259 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 4260 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 4261 llvm::Value *BaseValue = nullptr; 4262 const Expr *BaseExpr = E->getBase(); 4263 Qualifiers BaseQuals; 4264 QualType ObjectTy; 4265 if (E->isArrow()) { 4266 BaseValue = EmitScalarExpr(BaseExpr); 4267 ObjectTy = BaseExpr->getType()->getPointeeType(); 4268 BaseQuals = ObjectTy.getQualifiers(); 4269 } else { 4270 LValue BaseLV = EmitLValue(BaseExpr); 4271 BaseValue = BaseLV.getPointer(); 4272 ObjectTy = BaseExpr->getType(); 4273 BaseQuals = ObjectTy.getQualifiers(); 4274 } 4275 4276 LValue LV = 4277 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 4278 BaseQuals.getCVRQualifiers()); 4279 setObjCGCLValueClass(getContext(), E, LV); 4280 return LV; 4281 } 4282 4283 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 4284 // Can only get l-value for message expression returning aggregate type 4285 RValue RV = EmitAnyExprToTemp(E); 4286 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4287 LValueBaseInfo(AlignmentSource::Decl, false)); 4288 } 4289 4290 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee, 4291 const CallExpr *E, ReturnValueSlot ReturnValue, 4292 llvm::Value *Chain) { 4293 // Get the actual function type. The callee type will always be a pointer to 4294 // function type or a block pointer type. 4295 assert(CalleeType->isFunctionPointerType() && 4296 "Call must have function pointer type!"); 4297 4298 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl(); 4299 4300 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 4301 // We can only guarantee that a function is called from the correct 4302 // context/function based on the appropriate target attributes, 4303 // so only check in the case where we have both always_inline and target 4304 // since otherwise we could be making a conditional call after a check for 4305 // the proper cpu features (and it won't cause code generation issues due to 4306 // function based code generation). 4307 if (TargetDecl->hasAttr<AlwaysInlineAttr>() && 4308 TargetDecl->hasAttr<TargetAttr>()) 4309 checkTargetFeatures(E, FD); 4310 4311 CalleeType = getContext().getCanonicalType(CalleeType); 4312 4313 const auto *FnType = 4314 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType()); 4315 4316 CGCallee Callee = OrigCallee; 4317 4318 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) && 4319 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 4320 if (llvm::Constant *PrefixSig = 4321 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 4322 SanitizerScope SanScope(this); 4323 llvm::Constant *FTRTTIConst = 4324 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true); 4325 llvm::Type *PrefixStructTyElems[] = { 4326 PrefixSig->getType(), 4327 FTRTTIConst->getType() 4328 }; 4329 llvm::StructType *PrefixStructTy = llvm::StructType::get( 4330 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true); 4331 4332 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 4333 4334 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast( 4335 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy)); 4336 llvm::Value *CalleeSigPtr = 4337 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0); 4338 llvm::Value *CalleeSig = 4339 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign()); 4340 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig); 4341 4342 llvm::BasicBlock *Cont = createBasicBlock("cont"); 4343 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck"); 4344 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont); 4345 4346 EmitBlock(TypeCheck); 4347 llvm::Value *CalleeRTTIPtr = 4348 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1); 4349 llvm::Value *CalleeRTTI = 4350 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign()); 4351 llvm::Value *CalleeRTTIMatch = 4352 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst); 4353 llvm::Constant *StaticData[] = { 4354 EmitCheckSourceLocation(E->getLocStart()), 4355 EmitCheckTypeDescriptor(CalleeType) 4356 }; 4357 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function), 4358 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr); 4359 4360 Builder.CreateBr(Cont); 4361 EmitBlock(Cont); 4362 } 4363 } 4364 4365 // If we are checking indirect calls and this call is indirect, check that the 4366 // function pointer is a member of the bit set for the function type. 4367 if (SanOpts.has(SanitizerKind::CFIICall) && 4368 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 4369 SanitizerScope SanScope(this); 4370 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall); 4371 4372 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)); 4373 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD); 4374 4375 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 4376 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy); 4377 llvm::Value *TypeTest = Builder.CreateCall( 4378 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId}); 4379 4380 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD); 4381 llvm::Constant *StaticData[] = { 4382 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall), 4383 EmitCheckSourceLocation(E->getLocStart()), 4384 EmitCheckTypeDescriptor(QualType(FnType, 0)), 4385 }; 4386 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) { 4387 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId, 4388 CastedCallee, StaticData); 4389 } else { 4390 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall), 4391 SanitizerHandler::CFICheckFail, StaticData, 4392 {CastedCallee, llvm::UndefValue::get(IntPtrTy)}); 4393 } 4394 } 4395 4396 CallArgList Args; 4397 if (Chain) 4398 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)), 4399 CGM.getContext().VoidPtrTy); 4400 4401 // C++17 requires that we evaluate arguments to a call using assignment syntax 4402 // right-to-left, and that we evaluate arguments to certain other operators 4403 // left-to-right. Note that we allow this to override the order dictated by 4404 // the calling convention on the MS ABI, which means that parameter 4405 // destruction order is not necessarily reverse construction order. 4406 // FIXME: Revisit this based on C++ committee response to unimplementability. 4407 EvaluationOrder Order = EvaluationOrder::Default; 4408 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 4409 if (OCE->isAssignmentOp()) 4410 Order = EvaluationOrder::ForceRightToLeft; 4411 else { 4412 switch (OCE->getOperator()) { 4413 case OO_LessLess: 4414 case OO_GreaterGreater: 4415 case OO_AmpAmp: 4416 case OO_PipePipe: 4417 case OO_Comma: 4418 case OO_ArrowStar: 4419 Order = EvaluationOrder::ForceLeftToRight; 4420 break; 4421 default: 4422 break; 4423 } 4424 } 4425 } 4426 4427 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(), 4428 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order); 4429 4430 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall( 4431 Args, FnType, /*isChainCall=*/Chain); 4432 4433 // C99 6.5.2.2p6: 4434 // If the expression that denotes the called function has a type 4435 // that does not include a prototype, [the default argument 4436 // promotions are performed]. If the number of arguments does not 4437 // equal the number of parameters, the behavior is undefined. If 4438 // the function is defined with a type that includes a prototype, 4439 // and either the prototype ends with an ellipsis (, ...) or the 4440 // types of the arguments after promotion are not compatible with 4441 // the types of the parameters, the behavior is undefined. If the 4442 // function is defined with a type that does not include a 4443 // prototype, and the types of the arguments after promotion are 4444 // not compatible with those of the parameters after promotion, 4445 // the behavior is undefined [except in some trivial cases]. 4446 // That is, in the general case, we should assume that a call 4447 // through an unprototyped function type works like a *non-variadic* 4448 // call. The way we make this work is to cast to the exact type 4449 // of the promoted arguments. 4450 // 4451 // Chain calls use this same code path to add the invisible chain parameter 4452 // to the function type. 4453 if (isa<FunctionNoProtoType>(FnType) || Chain) { 4454 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo); 4455 CalleeTy = CalleeTy->getPointerTo(); 4456 4457 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 4458 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast"); 4459 Callee.setFunctionPointer(CalleePtr); 4460 } 4461 4462 return EmitCall(FnInfo, Callee, ReturnValue, Args); 4463 } 4464 4465 LValue CodeGenFunction:: 4466 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 4467 Address BaseAddr = Address::invalid(); 4468 if (E->getOpcode() == BO_PtrMemI) { 4469 BaseAddr = EmitPointerWithAlignment(E->getLHS()); 4470 } else { 4471 BaseAddr = EmitLValue(E->getLHS()).getAddress(); 4472 } 4473 4474 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 4475 4476 const MemberPointerType *MPT 4477 = E->getRHS()->getType()->getAs<MemberPointerType>(); 4478 4479 LValueBaseInfo BaseInfo; 4480 Address MemberAddr = 4481 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo); 4482 4483 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo); 4484 } 4485 4486 /// Given the address of a temporary variable, produce an r-value of 4487 /// its type. 4488 RValue CodeGenFunction::convertTempToRValue(Address addr, 4489 QualType type, 4490 SourceLocation loc) { 4491 LValue lvalue = MakeAddrLValue(addr, type, 4492 LValueBaseInfo(AlignmentSource::Decl, false)); 4493 switch (getEvaluationKind(type)) { 4494 case TEK_Complex: 4495 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc)); 4496 case TEK_Aggregate: 4497 return lvalue.asAggregateRValue(); 4498 case TEK_Scalar: 4499 return RValue::get(EmitLoadOfScalar(lvalue, loc)); 4500 } 4501 llvm_unreachable("bad evaluation kind"); 4502 } 4503 4504 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) { 4505 assert(Val->getType()->isFPOrFPVectorTy()); 4506 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val)) 4507 return; 4508 4509 llvm::MDBuilder MDHelper(getLLVMContext()); 4510 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy); 4511 4512 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node); 4513 } 4514 4515 namespace { 4516 struct LValueOrRValue { 4517 LValue LV; 4518 RValue RV; 4519 }; 4520 } 4521 4522 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, 4523 const PseudoObjectExpr *E, 4524 bool forLValue, 4525 AggValueSlot slot) { 4526 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 4527 4528 // Find the result expression, if any. 4529 const Expr *resultExpr = E->getResultExpr(); 4530 LValueOrRValue result; 4531 4532 for (PseudoObjectExpr::const_semantics_iterator 4533 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 4534 const Expr *semantic = *i; 4535 4536 // If this semantic expression is an opaque value, bind it 4537 // to the result of its source expression. 4538 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 4539 4540 // If this is the result expression, we may need to evaluate 4541 // directly into the slot. 4542 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 4543 OVMA opaqueData; 4544 if (ov == resultExpr && ov->isRValue() && !forLValue && 4545 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) { 4546 CGF.EmitAggExpr(ov->getSourceExpr(), slot); 4547 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false); 4548 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(), 4549 BaseInfo); 4550 opaqueData = OVMA::bind(CGF, ov, LV); 4551 result.RV = slot.asRValue(); 4552 4553 // Otherwise, emit as normal. 4554 } else { 4555 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 4556 4557 // If this is the result, also evaluate the result now. 4558 if (ov == resultExpr) { 4559 if (forLValue) 4560 result.LV = CGF.EmitLValue(ov); 4561 else 4562 result.RV = CGF.EmitAnyExpr(ov, slot); 4563 } 4564 } 4565 4566 opaques.push_back(opaqueData); 4567 4568 // Otherwise, if the expression is the result, evaluate it 4569 // and remember the result. 4570 } else if (semantic == resultExpr) { 4571 if (forLValue) 4572 result.LV = CGF.EmitLValue(semantic); 4573 else 4574 result.RV = CGF.EmitAnyExpr(semantic, slot); 4575 4576 // Otherwise, evaluate the expression in an ignored context. 4577 } else { 4578 CGF.EmitIgnoredExpr(semantic); 4579 } 4580 } 4581 4582 // Unbind all the opaques now. 4583 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 4584 opaques[i].unbind(CGF); 4585 4586 return result; 4587 } 4588 4589 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E, 4590 AggValueSlot slot) { 4591 return emitPseudoObjectExpr(*this, E, false, slot).RV; 4592 } 4593 4594 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) { 4595 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV; 4596 } 4597