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