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