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