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