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