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