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