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