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 const ConstantExpr *CE = cast<ConstantExpr>(E); 1307 if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) { 1308 QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit()) 1309 ->getCallReturnType(getContext()); 1310 return MakeNaturalAlignAddrLValue(Result, RetType); 1311 } 1312 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr()); 1313 } 1314 case Expr::ParenExprClass: 1315 return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 1316 case Expr::GenericSelectionExprClass: 1317 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr()); 1318 case Expr::PredefinedExprClass: 1319 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 1320 case Expr::StringLiteralClass: 1321 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 1322 case Expr::ObjCEncodeExprClass: 1323 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 1324 case Expr::PseudoObjectExprClass: 1325 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E)); 1326 case Expr::InitListExprClass: 1327 return EmitInitListLValue(cast<InitListExpr>(E)); 1328 case Expr::CXXTemporaryObjectExprClass: 1329 case Expr::CXXConstructExprClass: 1330 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 1331 case Expr::CXXBindTemporaryExprClass: 1332 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 1333 case Expr::CXXUuidofExprClass: 1334 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E)); 1335 case Expr::LambdaExprClass: 1336 return EmitAggExprToLValue(E); 1337 1338 case Expr::ExprWithCleanupsClass: { 1339 const auto *cleanups = cast<ExprWithCleanups>(E); 1340 RunCleanupsScope Scope(*this); 1341 LValue LV = EmitLValue(cleanups->getSubExpr()); 1342 if (LV.isSimple()) { 1343 // Defend against branches out of gnu statement expressions surrounded by 1344 // cleanups. 1345 llvm::Value *V = LV.getPointer(*this); 1346 Scope.ForceCleanup({&V}); 1347 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(), 1348 getContext(), LV.getBaseInfo(), LV.getTBAAInfo()); 1349 } 1350 // FIXME: Is it possible to create an ExprWithCleanups that produces a 1351 // bitfield lvalue or some other non-simple lvalue? 1352 return LV; 1353 } 1354 1355 case Expr::CXXDefaultArgExprClass: { 1356 auto *DAE = cast<CXXDefaultArgExpr>(E); 1357 CXXDefaultArgExprScope Scope(*this, DAE); 1358 return EmitLValue(DAE->getExpr()); 1359 } 1360 case Expr::CXXDefaultInitExprClass: { 1361 auto *DIE = cast<CXXDefaultInitExpr>(E); 1362 CXXDefaultInitExprScope Scope(*this, DIE); 1363 return EmitLValue(DIE->getExpr()); 1364 } 1365 case Expr::CXXTypeidExprClass: 1366 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E)); 1367 1368 case Expr::ObjCMessageExprClass: 1369 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 1370 case Expr::ObjCIvarRefExprClass: 1371 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 1372 case Expr::StmtExprClass: 1373 return EmitStmtExprLValue(cast<StmtExpr>(E)); 1374 case Expr::UnaryOperatorClass: 1375 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 1376 case Expr::ArraySubscriptExprClass: 1377 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 1378 case Expr::MatrixSubscriptExprClass: 1379 return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E)); 1380 case Expr::OMPArraySectionExprClass: 1381 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E)); 1382 case Expr::ExtVectorElementExprClass: 1383 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 1384 case Expr::MemberExprClass: 1385 return EmitMemberExpr(cast<MemberExpr>(E)); 1386 case Expr::CompoundLiteralExprClass: 1387 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 1388 case Expr::ConditionalOperatorClass: 1389 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E)); 1390 case Expr::BinaryConditionalOperatorClass: 1391 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E)); 1392 case Expr::ChooseExprClass: 1393 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr()); 1394 case Expr::OpaqueValueExprClass: 1395 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E)); 1396 case Expr::SubstNonTypeTemplateParmExprClass: 1397 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement()); 1398 case Expr::ImplicitCastExprClass: 1399 case Expr::CStyleCastExprClass: 1400 case Expr::CXXFunctionalCastExprClass: 1401 case Expr::CXXStaticCastExprClass: 1402 case Expr::CXXDynamicCastExprClass: 1403 case Expr::CXXReinterpretCastExprClass: 1404 case Expr::CXXConstCastExprClass: 1405 case Expr::CXXAddrspaceCastExprClass: 1406 case Expr::ObjCBridgedCastExprClass: 1407 return EmitCastLValue(cast<CastExpr>(E)); 1408 1409 case Expr::MaterializeTemporaryExprClass: 1410 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E)); 1411 1412 case Expr::CoawaitExprClass: 1413 return EmitCoawaitLValue(cast<CoawaitExpr>(E)); 1414 case Expr::CoyieldExprClass: 1415 return EmitCoyieldLValue(cast<CoyieldExpr>(E)); 1416 } 1417 } 1418 1419 /// Given an object of the given canonical type, can we safely copy a 1420 /// value out of it based on its initializer? 1421 static bool isConstantEmittableObjectType(QualType type) { 1422 assert(type.isCanonical()); 1423 assert(!type->isReferenceType()); 1424 1425 // Must be const-qualified but non-volatile. 1426 Qualifiers qs = type.getLocalQualifiers(); 1427 if (!qs.hasConst() || qs.hasVolatile()) return false; 1428 1429 // Otherwise, all object types satisfy this except C++ classes with 1430 // mutable subobjects or non-trivial copy/destroy behavior. 1431 if (const auto *RT = dyn_cast<RecordType>(type)) 1432 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 1433 if (RD->hasMutableFields() || !RD->isTrivial()) 1434 return false; 1435 1436 return true; 1437 } 1438 1439 /// Can we constant-emit a load of a reference to a variable of the 1440 /// given type? This is different from predicates like 1441 /// Decl::mightBeUsableInConstantExpressions because we do want it to apply 1442 /// in situations that don't necessarily satisfy the language's rules 1443 /// for this (e.g. C++'s ODR-use rules). For example, we want to able 1444 /// to do this with const float variables even if those variables 1445 /// aren't marked 'constexpr'. 1446 enum ConstantEmissionKind { 1447 CEK_None, 1448 CEK_AsReferenceOnly, 1449 CEK_AsValueOrReference, 1450 CEK_AsValueOnly 1451 }; 1452 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) { 1453 type = type.getCanonicalType(); 1454 if (const auto *ref = dyn_cast<ReferenceType>(type)) { 1455 if (isConstantEmittableObjectType(ref->getPointeeType())) 1456 return CEK_AsValueOrReference; 1457 return CEK_AsReferenceOnly; 1458 } 1459 if (isConstantEmittableObjectType(type)) 1460 return CEK_AsValueOnly; 1461 return CEK_None; 1462 } 1463 1464 /// Try to emit a reference to the given value without producing it as 1465 /// an l-value. This is just an optimization, but it avoids us needing 1466 /// to emit global copies of variables if they're named without triggering 1467 /// a formal use in a context where we can't emit a direct reference to them, 1468 /// for instance if a block or lambda or a member of a local class uses a 1469 /// const int variable or constexpr variable from an enclosing function. 1470 CodeGenFunction::ConstantEmission 1471 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) { 1472 ValueDecl *value = refExpr->getDecl(); 1473 1474 // The value needs to be an enum constant or a constant variable. 1475 ConstantEmissionKind CEK; 1476 if (isa<ParmVarDecl>(value)) { 1477 CEK = CEK_None; 1478 } else if (auto *var = dyn_cast<VarDecl>(value)) { 1479 CEK = checkVarTypeForConstantEmission(var->getType()); 1480 } else if (isa<EnumConstantDecl>(value)) { 1481 CEK = CEK_AsValueOnly; 1482 } else { 1483 CEK = CEK_None; 1484 } 1485 if (CEK == CEK_None) return ConstantEmission(); 1486 1487 Expr::EvalResult result; 1488 bool resultIsReference; 1489 QualType resultType; 1490 1491 // It's best to evaluate all the way as an r-value if that's permitted. 1492 if (CEK != CEK_AsReferenceOnly && 1493 refExpr->EvaluateAsRValue(result, getContext())) { 1494 resultIsReference = false; 1495 resultType = refExpr->getType(); 1496 1497 // Otherwise, try to evaluate as an l-value. 1498 } else if (CEK != CEK_AsValueOnly && 1499 refExpr->EvaluateAsLValue(result, getContext())) { 1500 resultIsReference = true; 1501 resultType = value->getType(); 1502 1503 // Failure. 1504 } else { 1505 return ConstantEmission(); 1506 } 1507 1508 // In any case, if the initializer has side-effects, abandon ship. 1509 if (result.HasSideEffects) 1510 return ConstantEmission(); 1511 1512 // Emit as a constant. 1513 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(), 1514 result.Val, resultType); 1515 1516 // Make sure we emit a debug reference to the global variable. 1517 // This should probably fire even for 1518 if (isa<VarDecl>(value)) { 1519 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value))) 1520 EmitDeclRefExprDbgValue(refExpr, result.Val); 1521 } else { 1522 assert(isa<EnumConstantDecl>(value)); 1523 EmitDeclRefExprDbgValue(refExpr, result.Val); 1524 } 1525 1526 // If we emitted a reference constant, we need to dereference that. 1527 if (resultIsReference) 1528 return ConstantEmission::forReference(C); 1529 1530 return ConstantEmission::forValue(C); 1531 } 1532 1533 static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF, 1534 const MemberExpr *ME) { 1535 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) { 1536 // Try to emit static variable member expressions as DREs. 1537 return DeclRefExpr::Create( 1538 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD, 1539 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(), 1540 ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse()); 1541 } 1542 return nullptr; 1543 } 1544 1545 CodeGenFunction::ConstantEmission 1546 CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) { 1547 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME)) 1548 return tryEmitAsConstant(DRE); 1549 return ConstantEmission(); 1550 } 1551 1552 llvm::Value *CodeGenFunction::emitScalarConstant( 1553 const CodeGenFunction::ConstantEmission &Constant, Expr *E) { 1554 assert(Constant && "not a constant"); 1555 if (Constant.isReference()) 1556 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E), 1557 E->getExprLoc()) 1558 .getScalarVal(); 1559 return Constant.getValue(); 1560 } 1561 1562 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue, 1563 SourceLocation Loc) { 1564 return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(), 1565 lvalue.getType(), Loc, lvalue.getBaseInfo(), 1566 lvalue.getTBAAInfo(), lvalue.isNontemporal()); 1567 } 1568 1569 static bool hasBooleanRepresentation(QualType Ty) { 1570 if (Ty->isBooleanType()) 1571 return true; 1572 1573 if (const EnumType *ET = Ty->getAs<EnumType>()) 1574 return ET->getDecl()->getIntegerType()->isBooleanType(); 1575 1576 if (const AtomicType *AT = Ty->getAs<AtomicType>()) 1577 return hasBooleanRepresentation(AT->getValueType()); 1578 1579 return false; 1580 } 1581 1582 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, 1583 llvm::APInt &Min, llvm::APInt &End, 1584 bool StrictEnums, bool IsBool) { 1585 const EnumType *ET = Ty->getAs<EnumType>(); 1586 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums && 1587 ET && !ET->getDecl()->isFixed(); 1588 if (!IsBool && !IsRegularCPlusPlusEnum) 1589 return false; 1590 1591 if (IsBool) { 1592 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0); 1593 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2); 1594 } else { 1595 const EnumDecl *ED = ET->getDecl(); 1596 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType()); 1597 unsigned Bitwidth = LTy->getScalarSizeInBits(); 1598 unsigned NumNegativeBits = ED->getNumNegativeBits(); 1599 unsigned NumPositiveBits = ED->getNumPositiveBits(); 1600 1601 if (NumNegativeBits) { 1602 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1); 1603 assert(NumBits <= Bitwidth); 1604 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1); 1605 Min = -End; 1606 } else { 1607 assert(NumPositiveBits <= Bitwidth); 1608 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits; 1609 Min = llvm::APInt(Bitwidth, 0); 1610 } 1611 } 1612 return true; 1613 } 1614 1615 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) { 1616 llvm::APInt Min, End; 1617 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums, 1618 hasBooleanRepresentation(Ty))) 1619 return nullptr; 1620 1621 llvm::MDBuilder MDHelper(getLLVMContext()); 1622 return MDHelper.createRange(Min, End); 1623 } 1624 1625 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, 1626 SourceLocation Loc) { 1627 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool); 1628 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum); 1629 if (!HasBoolCheck && !HasEnumCheck) 1630 return false; 1631 1632 bool IsBool = hasBooleanRepresentation(Ty) || 1633 NSAPI(CGM.getContext()).isObjCBOOLType(Ty); 1634 bool NeedsBoolCheck = HasBoolCheck && IsBool; 1635 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>(); 1636 if (!NeedsBoolCheck && !NeedsEnumCheck) 1637 return false; 1638 1639 // Single-bit booleans don't need to be checked. Special-case this to avoid 1640 // a bit width mismatch when handling bitfield values. This is handled by 1641 // EmitFromMemory for the non-bitfield case. 1642 if (IsBool && 1643 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1) 1644 return false; 1645 1646 llvm::APInt Min, End; 1647 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool)) 1648 return true; 1649 1650 auto &Ctx = getLLVMContext(); 1651 SanitizerScope SanScope(this); 1652 llvm::Value *Check; 1653 --End; 1654 if (!Min) { 1655 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End)); 1656 } else { 1657 llvm::Value *Upper = 1658 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End)); 1659 llvm::Value *Lower = 1660 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min)); 1661 Check = Builder.CreateAnd(Upper, Lower); 1662 } 1663 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc), 1664 EmitCheckTypeDescriptor(Ty)}; 1665 SanitizerMask Kind = 1666 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool; 1667 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue, 1668 StaticArgs, EmitCheckValue(Value)); 1669 return true; 1670 } 1671 1672 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile, 1673 QualType Ty, 1674 SourceLocation Loc, 1675 LValueBaseInfo BaseInfo, 1676 TBAAAccessInfo TBAAInfo, 1677 bool isNontemporal) { 1678 if (!CGM.getCodeGenOpts().PreserveVec3Type) { 1679 // For better performance, handle vector loads differently. 1680 if (Ty->isVectorType()) { 1681 const llvm::Type *EltTy = Addr.getElementType(); 1682 1683 const auto *VTy = cast<llvm::VectorType>(EltTy); 1684 1685 // Handle vectors of size 3 like size 4 for better performance. 1686 if (VTy->getNumElements() == 3) { 1687 1688 // Bitcast to vec4 type. 1689 auto *vec4Ty = llvm::FixedVectorType::get(VTy->getElementType(), 4); 1690 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4"); 1691 // Now load value. 1692 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4"); 1693 1694 // Shuffle vector to get vec3. 1695 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty), 1696 ArrayRef<int>{0, 1, 2}, "extractVec"); 1697 return EmitFromMemory(V, Ty); 1698 } 1699 } 1700 } 1701 1702 // Atomic operations have to be done on integral types. 1703 LValue AtomicLValue = 1704 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo); 1705 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) { 1706 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal(); 1707 } 1708 1709 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile); 1710 if (isNontemporal) { 1711 llvm::MDNode *Node = llvm::MDNode::get( 1712 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1713 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1714 } 1715 1716 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo); 1717 1718 if (EmitScalarRangeCheck(Load, Ty, Loc)) { 1719 // In order to prevent the optimizer from throwing away the check, don't 1720 // attach range metadata to the load. 1721 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0) 1722 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) 1723 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo); 1724 1725 return EmitFromMemory(Load, Ty); 1726 } 1727 1728 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 1729 // Bool has a different representation in memory than in registers. 1730 if (hasBooleanRepresentation(Ty)) { 1731 // This should really always be an i1, but sometimes it's already 1732 // an i8, and it's awkward to track those cases down. 1733 if (Value->getType()->isIntegerTy(1)) 1734 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool"); 1735 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1736 "wrong value rep of bool"); 1737 } 1738 1739 return Value; 1740 } 1741 1742 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 1743 // Bool has a different representation in memory than in registers. 1744 if (hasBooleanRepresentation(Ty)) { 1745 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1746 "wrong value rep of bool"); 1747 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool"); 1748 } 1749 1750 return Value; 1751 } 1752 1753 // Convert the pointer of \p Addr to a pointer to a vector (the value type of 1754 // MatrixType), if it points to a array (the memory type of MatrixType). 1755 static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF, 1756 bool IsVector = true) { 1757 auto *ArrayTy = dyn_cast<llvm::ArrayType>( 1758 cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType()); 1759 if (ArrayTy && IsVector) { 1760 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(), 1761 ArrayTy->getNumElements()); 1762 1763 return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy)); 1764 } 1765 auto *VectorTy = dyn_cast<llvm::VectorType>( 1766 cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType()); 1767 if (VectorTy && !IsVector) { 1768 auto *ArrayTy = llvm::ArrayType::get(VectorTy->getElementType(), 1769 VectorTy->getNumElements()); 1770 1771 return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy)); 1772 } 1773 1774 return Addr; 1775 } 1776 1777 // Emit a store of a matrix LValue. This may require casting the original 1778 // pointer to memory address (ArrayType) to a pointer to the value type 1779 // (VectorType). 1780 static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, 1781 bool isInit, CodeGenFunction &CGF) { 1782 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF, 1783 value->getType()->isVectorTy()); 1784 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(), 1785 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit, 1786 lvalue.isNontemporal()); 1787 } 1788 1789 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr, 1790 bool Volatile, QualType Ty, 1791 LValueBaseInfo BaseInfo, 1792 TBAAAccessInfo TBAAInfo, 1793 bool isInit, bool isNontemporal) { 1794 if (!CGM.getCodeGenOpts().PreserveVec3Type) { 1795 // Handle vectors differently to get better performance. 1796 if (Ty->isVectorType()) { 1797 llvm::Type *SrcTy = Value->getType(); 1798 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy); 1799 // Handle vec3 special. 1800 if (VecTy && VecTy->getNumElements() == 3) { 1801 // Our source is a vec3, do a shuffle vector to make it a vec4. 1802 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy), 1803 ArrayRef<int>{0, 1, 2, -1}, 1804 "extractVec"); 1805 SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4); 1806 } 1807 if (Addr.getElementType() != SrcTy) { 1808 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp"); 1809 } 1810 } 1811 } 1812 1813 Value = EmitToMemory(Value, Ty); 1814 1815 LValue AtomicLValue = 1816 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo); 1817 if (Ty->isAtomicType() || 1818 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) { 1819 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit); 1820 return; 1821 } 1822 1823 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 1824 if (isNontemporal) { 1825 llvm::MDNode *Node = 1826 llvm::MDNode::get(Store->getContext(), 1827 llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1828 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1829 } 1830 1831 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo); 1832 } 1833 1834 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue, 1835 bool isInit) { 1836 if (lvalue.getType()->isConstantMatrixType()) { 1837 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this); 1838 return; 1839 } 1840 1841 EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(), 1842 lvalue.getType(), lvalue.getBaseInfo(), 1843 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal()); 1844 } 1845 1846 // Emit a load of a LValue of matrix type. This may require casting the pointer 1847 // to memory address (ArrayType) to a pointer to the value type (VectorType). 1848 static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, 1849 CodeGenFunction &CGF) { 1850 assert(LV.getType()->isConstantMatrixType()); 1851 Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF); 1852 LV.setAddress(Addr); 1853 return RValue::get(CGF.EmitLoadOfScalar(LV, Loc)); 1854 } 1855 1856 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 1857 /// method emits the address of the lvalue, then loads the result as an rvalue, 1858 /// returning the rvalue. 1859 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 1860 if (LV.isObjCWeak()) { 1861 // load of a __weak object. 1862 Address AddrWeakObj = LV.getAddress(*this); 1863 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 1864 AddrWeakObj)); 1865 } 1866 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 1867 // In MRC mode, we do a load+autorelease. 1868 if (!getLangOpts().ObjCAutoRefCount) { 1869 return RValue::get(EmitARCLoadWeak(LV.getAddress(*this))); 1870 } 1871 1872 // In ARC mode, we load retained and then consume the value. 1873 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this)); 1874 Object = EmitObjCConsumeObject(LV.getType(), Object); 1875 return RValue::get(Object); 1876 } 1877 1878 if (LV.isSimple()) { 1879 assert(!LV.getType()->isFunctionType()); 1880 1881 if (LV.getType()->isConstantMatrixType()) 1882 return EmitLoadOfMatrixLValue(LV, Loc, *this); 1883 1884 // Everything needs a load. 1885 return RValue::get(EmitLoadOfScalar(LV, Loc)); 1886 } 1887 1888 if (LV.isVectorElt()) { 1889 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(), 1890 LV.isVolatileQualified()); 1891 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(), 1892 "vecext")); 1893 } 1894 1895 // If this is a reference to a subset of the elements of a vector, either 1896 // shuffle the input or extract/insert them as appropriate. 1897 if (LV.isExtVectorElt()) { 1898 return EmitLoadOfExtVectorElementLValue(LV); 1899 } 1900 1901 // Global Register variables always invoke intrinsics 1902 if (LV.isGlobalReg()) 1903 return EmitLoadOfGlobalRegLValue(LV); 1904 1905 if (LV.isMatrixElt()) { 1906 llvm::LoadInst *Load = 1907 Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified()); 1908 return RValue::get( 1909 Builder.CreateExtractElement(Load, LV.getMatrixIdx(), "matrixext")); 1910 } 1911 1912 assert(LV.isBitField() && "Unknown LValue type!"); 1913 return EmitLoadOfBitfieldLValue(LV, Loc); 1914 } 1915 1916 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 1917 SourceLocation Loc) { 1918 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 1919 1920 // Get the output type. 1921 llvm::Type *ResLTy = ConvertType(LV.getType()); 1922 1923 Address Ptr = LV.getBitFieldAddress(); 1924 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load"); 1925 1926 if (Info.IsSigned) { 1927 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize); 1928 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size; 1929 if (HighBits) 1930 Val = Builder.CreateShl(Val, HighBits, "bf.shl"); 1931 if (Info.Offset + HighBits) 1932 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr"); 1933 } else { 1934 if (Info.Offset) 1935 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr"); 1936 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize) 1937 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize, 1938 Info.Size), 1939 "bf.clear"); 1940 } 1941 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast"); 1942 EmitScalarRangeCheck(Val, LV.getType(), Loc); 1943 return RValue::get(Val); 1944 } 1945 1946 // If this is a reference to a subset of the elements of a vector, create an 1947 // appropriate shufflevector. 1948 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) { 1949 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(), 1950 LV.isVolatileQualified()); 1951 1952 const llvm::Constant *Elts = LV.getExtVectorElts(); 1953 1954 // If the result of the expression is a non-vector type, we must be extracting 1955 // a single element. Just codegen as an extractelement. 1956 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1957 if (!ExprVT) { 1958 unsigned InIdx = getAccessedFieldNo(0, Elts); 1959 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 1960 return RValue::get(Builder.CreateExtractElement(Vec, Elt)); 1961 } 1962 1963 // Always use shuffle vector to try to retain the original program structure 1964 unsigned NumResultElts = ExprVT->getNumElements(); 1965 1966 SmallVector<int, 4> Mask; 1967 for (unsigned i = 0; i != NumResultElts; ++i) 1968 Mask.push_back(getAccessedFieldNo(i, Elts)); 1969 1970 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), 1971 Mask); 1972 return RValue::get(Vec); 1973 } 1974 1975 /// Generates lvalue for partial ext_vector access. 1976 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) { 1977 Address VectorAddress = LV.getExtVectorAddress(); 1978 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType(); 1979 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT); 1980 1981 Address CastToPointerElement = 1982 Builder.CreateElementBitCast(VectorAddress, VectorElementTy, 1983 "conv.ptr.element"); 1984 1985 const llvm::Constant *Elts = LV.getExtVectorElts(); 1986 unsigned ix = getAccessedFieldNo(0, Elts); 1987 1988 Address VectorBasePtrPlusIx = 1989 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix, 1990 "vector.elt"); 1991 1992 return VectorBasePtrPlusIx; 1993 } 1994 1995 /// Load of global gamed gegisters are always calls to intrinsics. 1996 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) { 1997 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) && 1998 "Bad type for register variable"); 1999 llvm::MDNode *RegName = cast<llvm::MDNode>( 2000 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata()); 2001 2002 // We accept integer and pointer types only 2003 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType()); 2004 llvm::Type *Ty = OrigTy; 2005 if (OrigTy->isPointerTy()) 2006 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 2007 llvm::Type *Types[] = { Ty }; 2008 2009 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types); 2010 llvm::Value *Call = Builder.CreateCall( 2011 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName)); 2012 if (OrigTy->isPointerTy()) 2013 Call = Builder.CreateIntToPtr(Call, OrigTy); 2014 return RValue::get(Call); 2015 } 2016 2017 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 2018 /// lvalue, where both are guaranteed to the have the same type, and that type 2019 /// is 'Ty'. 2020 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 2021 bool isInit) { 2022 if (!Dst.isSimple()) { 2023 if (Dst.isVectorElt()) { 2024 // Read/modify/write the vector, inserting the new element. 2025 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(), 2026 Dst.isVolatileQualified()); 2027 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 2028 Dst.getVectorIdx(), "vecins"); 2029 Builder.CreateStore(Vec, Dst.getVectorAddress(), 2030 Dst.isVolatileQualified()); 2031 return; 2032 } 2033 2034 // If this is an update of extended vector elements, insert them as 2035 // appropriate. 2036 if (Dst.isExtVectorElt()) 2037 return EmitStoreThroughExtVectorComponentLValue(Src, Dst); 2038 2039 if (Dst.isGlobalReg()) 2040 return EmitStoreThroughGlobalRegLValue(Src, Dst); 2041 2042 if (Dst.isMatrixElt()) { 2043 llvm::Value *Vec = Builder.CreateLoad(Dst.getMatrixAddress()); 2044 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 2045 Dst.getMatrixIdx(), "matins"); 2046 Builder.CreateStore(Vec, Dst.getMatrixAddress(), 2047 Dst.isVolatileQualified()); 2048 return; 2049 } 2050 2051 assert(Dst.isBitField() && "Unknown LValue type"); 2052 return EmitStoreThroughBitfieldLValue(Src, Dst); 2053 } 2054 2055 // There's special magic for assigning into an ARC-qualified l-value. 2056 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) { 2057 switch (Lifetime) { 2058 case Qualifiers::OCL_None: 2059 llvm_unreachable("present but none"); 2060 2061 case Qualifiers::OCL_ExplicitNone: 2062 // nothing special 2063 break; 2064 2065 case Qualifiers::OCL_Strong: 2066 if (isInit) { 2067 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal())); 2068 break; 2069 } 2070 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true); 2071 return; 2072 2073 case Qualifiers::OCL_Weak: 2074 if (isInit) 2075 // Initialize and then skip the primitive store. 2076 EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal()); 2077 else 2078 EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(), 2079 /*ignore*/ true); 2080 return; 2081 2082 case Qualifiers::OCL_Autoreleasing: 2083 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(), 2084 Src.getScalarVal())); 2085 // fall into the normal path 2086 break; 2087 } 2088 } 2089 2090 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 2091 // load of a __weak object. 2092 Address LvalueDst = Dst.getAddress(*this); 2093 llvm::Value *src = Src.getScalarVal(); 2094 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 2095 return; 2096 } 2097 2098 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 2099 // load of a __strong object. 2100 Address LvalueDst = Dst.getAddress(*this); 2101 llvm::Value *src = Src.getScalarVal(); 2102 if (Dst.isObjCIvar()) { 2103 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 2104 llvm::Type *ResultType = IntPtrTy; 2105 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp()); 2106 llvm::Value *RHS = dst.getPointer(); 2107 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 2108 llvm::Value *LHS = 2109 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType, 2110 "sub.ptr.lhs.cast"); 2111 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 2112 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 2113 BytesBetween); 2114 } else if (Dst.isGlobalObjCRef()) { 2115 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 2116 Dst.isThreadLocalRef()); 2117 } 2118 else 2119 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 2120 return; 2121 } 2122 2123 assert(Src.isScalar() && "Can't emit an agg store with this method"); 2124 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit); 2125 } 2126 2127 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 2128 llvm::Value **Result) { 2129 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 2130 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType()); 2131 Address Ptr = Dst.getBitFieldAddress(); 2132 2133 // Get the source value, truncated to the width of the bit-field. 2134 llvm::Value *SrcVal = Src.getScalarVal(); 2135 2136 // Cast the source to the storage type and shift it into place. 2137 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(), 2138 /*isSigned=*/false); 2139 llvm::Value *MaskedVal = SrcVal; 2140 2141 // See if there are other bits in the bitfield's storage we'll need to load 2142 // and mask together with source before storing. 2143 if (Info.StorageSize != Info.Size) { 2144 assert(Info.StorageSize > Info.Size && "Invalid bitfield size."); 2145 llvm::Value *Val = 2146 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load"); 2147 2148 // Mask the source value as needed. 2149 if (!hasBooleanRepresentation(Dst.getType())) 2150 SrcVal = Builder.CreateAnd(SrcVal, 2151 llvm::APInt::getLowBitsSet(Info.StorageSize, 2152 Info.Size), 2153 "bf.value"); 2154 MaskedVal = SrcVal; 2155 if (Info.Offset) 2156 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl"); 2157 2158 // Mask out the original value. 2159 Val = Builder.CreateAnd(Val, 2160 ~llvm::APInt::getBitsSet(Info.StorageSize, 2161 Info.Offset, 2162 Info.Offset + Info.Size), 2163 "bf.clear"); 2164 2165 // Or together the unchanged values and the source value. 2166 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set"); 2167 } else { 2168 assert(Info.Offset == 0); 2169 // According to the AACPS: 2170 // When a volatile bit-field is written, and its container does not overlap 2171 // with any non-bit-field member, its container must be read exactly once and 2172 // written exactly once using the access width appropriate to the type of the 2173 // container. The two accesses are not atomic. 2174 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) && 2175 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad) 2176 Builder.CreateLoad(Ptr, true, "bf.load"); 2177 } 2178 2179 // Write the new value back out. 2180 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified()); 2181 2182 // Return the new value of the bit-field, if requested. 2183 if (Result) { 2184 llvm::Value *ResultVal = MaskedVal; 2185 2186 // Sign extend the value if needed. 2187 if (Info.IsSigned) { 2188 assert(Info.Size <= Info.StorageSize); 2189 unsigned HighBits = Info.StorageSize - Info.Size; 2190 if (HighBits) { 2191 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl"); 2192 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr"); 2193 } 2194 } 2195 2196 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned, 2197 "bf.result.cast"); 2198 *Result = EmitFromMemory(ResultVal, Dst.getType()); 2199 } 2200 } 2201 2202 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 2203 LValue Dst) { 2204 // This access turns into a read/modify/write of the vector. Load the input 2205 // value now. 2206 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(), 2207 Dst.isVolatileQualified()); 2208 const llvm::Constant *Elts = Dst.getExtVectorElts(); 2209 2210 llvm::Value *SrcVal = Src.getScalarVal(); 2211 2212 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) { 2213 unsigned NumSrcElts = VTy->getNumElements(); 2214 unsigned NumDstElts = 2215 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 2216 if (NumDstElts == NumSrcElts) { 2217 // Use shuffle vector is the src and destination are the same number of 2218 // elements and restore the vector mask since it is on the side it will be 2219 // stored. 2220 SmallVector<int, 4> Mask(NumDstElts); 2221 for (unsigned i = 0; i != NumSrcElts; ++i) 2222 Mask[getAccessedFieldNo(i, Elts)] = i; 2223 2224 Vec = Builder.CreateShuffleVector( 2225 SrcVal, llvm::UndefValue::get(Vec->getType()), Mask); 2226 } else if (NumDstElts > NumSrcElts) { 2227 // Extended the source vector to the same length and then shuffle it 2228 // into the destination. 2229 // FIXME: since we're shuffling with undef, can we just use the indices 2230 // into that? This could be simpler. 2231 SmallVector<int, 4> ExtMask; 2232 for (unsigned i = 0; i != NumSrcElts; ++i) 2233 ExtMask.push_back(i); 2234 ExtMask.resize(NumDstElts, -1); 2235 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector( 2236 SrcVal, llvm::UndefValue::get(SrcVal->getType()), ExtMask); 2237 // build identity 2238 SmallVector<int, 4> Mask; 2239 for (unsigned i = 0; i != NumDstElts; ++i) 2240 Mask.push_back(i); 2241 2242 // When the vector size is odd and .odd or .hi is used, the last element 2243 // of the Elts constant array will be one past the size of the vector. 2244 // Ignore the last element here, if it is greater than the mask size. 2245 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size()) 2246 NumSrcElts--; 2247 2248 // modify when what gets shuffled in 2249 for (unsigned i = 0; i != NumSrcElts; ++i) 2250 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts; 2251 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask); 2252 } else { 2253 // We should never shorten the vector 2254 llvm_unreachable("unexpected shorten vector length"); 2255 } 2256 } else { 2257 // If the Src is a scalar (not a vector) it must be updating one element. 2258 unsigned InIdx = getAccessedFieldNo(0, Elts); 2259 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 2260 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt); 2261 } 2262 2263 Builder.CreateStore(Vec, Dst.getExtVectorAddress(), 2264 Dst.isVolatileQualified()); 2265 } 2266 2267 /// Store of global named registers are always calls to intrinsics. 2268 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) { 2269 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) && 2270 "Bad type for register variable"); 2271 llvm::MDNode *RegName = cast<llvm::MDNode>( 2272 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata()); 2273 assert(RegName && "Register LValue is not metadata"); 2274 2275 // We accept integer and pointer types only 2276 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType()); 2277 llvm::Type *Ty = OrigTy; 2278 if (OrigTy->isPointerTy()) 2279 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 2280 llvm::Type *Types[] = { Ty }; 2281 2282 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types); 2283 llvm::Value *Value = Src.getScalarVal(); 2284 if (OrigTy->isPointerTy()) 2285 Value = Builder.CreatePtrToInt(Value, Ty); 2286 Builder.CreateCall( 2287 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value}); 2288 } 2289 2290 // setObjCGCLValueClass - sets class of the lvalue for the purpose of 2291 // generating write-barries API. It is currently a global, ivar, 2292 // or neither. 2293 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 2294 LValue &LV, 2295 bool IsMemberAccess=false) { 2296 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC) 2297 return; 2298 2299 if (isa<ObjCIvarRefExpr>(E)) { 2300 QualType ExpTy = E->getType(); 2301 if (IsMemberAccess && ExpTy->isPointerType()) { 2302 // If ivar is a structure pointer, assigning to field of 2303 // this struct follows gcc's behavior and makes it a non-ivar 2304 // writer-barrier conservatively. 2305 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType(); 2306 if (ExpTy->isRecordType()) { 2307 LV.setObjCIvar(false); 2308 return; 2309 } 2310 } 2311 LV.setObjCIvar(true); 2312 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E)); 2313 LV.setBaseIvarExp(Exp->getBase()); 2314 LV.setObjCArray(E->getType()->isArrayType()); 2315 return; 2316 } 2317 2318 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) { 2319 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 2320 if (VD->hasGlobalStorage()) { 2321 LV.setGlobalObjCRef(true); 2322 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None); 2323 } 2324 } 2325 LV.setObjCArray(E->getType()->isArrayType()); 2326 return; 2327 } 2328 2329 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) { 2330 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2331 return; 2332 } 2333 2334 if (const auto *Exp = dyn_cast<ParenExpr>(E)) { 2335 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2336 if (LV.isObjCIvar()) { 2337 // If cast is to a structure pointer, follow gcc's behavior and make it 2338 // a non-ivar write-barrier. 2339 QualType ExpTy = E->getType(); 2340 if (ExpTy->isPointerType()) 2341 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType(); 2342 if (ExpTy->isRecordType()) 2343 LV.setObjCIvar(false); 2344 } 2345 return; 2346 } 2347 2348 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) { 2349 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV); 2350 return; 2351 } 2352 2353 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) { 2354 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2355 return; 2356 } 2357 2358 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) { 2359 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2360 return; 2361 } 2362 2363 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) { 2364 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2365 return; 2366 } 2367 2368 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 2369 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 2370 if (LV.isObjCIvar() && !LV.isObjCArray()) 2371 // Using array syntax to assigning to what an ivar points to is not 2372 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 2373 LV.setObjCIvar(false); 2374 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 2375 // Using array syntax to assigning to what global points to is not 2376 // same as assigning to the global itself. {id *G;} G[i] = 0; 2377 LV.setGlobalObjCRef(false); 2378 return; 2379 } 2380 2381 if (const auto *Exp = dyn_cast<MemberExpr>(E)) { 2382 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true); 2383 // We don't know if member is an 'ivar', but this flag is looked at 2384 // only in the context of LV.isObjCIvar(). 2385 LV.setObjCArray(E->getType()->isArrayType()); 2386 return; 2387 } 2388 } 2389 2390 static llvm::Value * 2391 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, 2392 llvm::Value *V, llvm::Type *IRType, 2393 StringRef Name = StringRef()) { 2394 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace(); 2395 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name); 2396 } 2397 2398 static LValue EmitThreadPrivateVarDeclLValue( 2399 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, 2400 llvm::Type *RealVarTy, SourceLocation Loc) { 2401 if (CGF.CGM.getLangOpts().OpenMPIRBuilder) 2402 Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate( 2403 CGF, VD, Addr, Loc); 2404 else 2405 Addr = 2406 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc); 2407 2408 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy); 2409 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 2410 } 2411 2412 static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, 2413 const VarDecl *VD, QualType T) { 2414 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2415 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2416 // Return an invalid address if variable is MT_To and unified 2417 // memory is not enabled. For all other cases: MT_Link and 2418 // MT_To with unified memory, return a valid address. 2419 if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To && 2420 !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) 2421 return Address::invalid(); 2422 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 2423 (*Res == OMPDeclareTargetDeclAttr::MT_To && 2424 CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) && 2425 "Expected link clause OR to clause with unified memory enabled."); 2426 QualType PtrTy = CGF.getContext().getPointerType(VD->getType()); 2427 Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 2428 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>()); 2429 } 2430 2431 Address 2432 CodeGenFunction::EmitLoadOfReference(LValue RefLVal, 2433 LValueBaseInfo *PointeeBaseInfo, 2434 TBAAAccessInfo *PointeeTBAAInfo) { 2435 llvm::LoadInst *Load = 2436 Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile()); 2437 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo()); 2438 2439 CharUnits Align = CGM.getNaturalTypeAlignment( 2440 RefLVal.getType()->getPointeeType(), PointeeBaseInfo, PointeeTBAAInfo, 2441 /* forPointeeType= */ true); 2442 return Address(Load, Align); 2443 } 2444 2445 LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) { 2446 LValueBaseInfo PointeeBaseInfo; 2447 TBAAAccessInfo PointeeTBAAInfo; 2448 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo, 2449 &PointeeTBAAInfo); 2450 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(), 2451 PointeeBaseInfo, PointeeTBAAInfo); 2452 } 2453 2454 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr, 2455 const PointerType *PtrTy, 2456 LValueBaseInfo *BaseInfo, 2457 TBAAAccessInfo *TBAAInfo) { 2458 llvm::Value *Addr = Builder.CreateLoad(Ptr); 2459 return Address(Addr, CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(), 2460 BaseInfo, TBAAInfo, 2461 /*forPointeeType=*/true)); 2462 } 2463 2464 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr, 2465 const PointerType *PtrTy) { 2466 LValueBaseInfo BaseInfo; 2467 TBAAAccessInfo TBAAInfo; 2468 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo); 2469 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo); 2470 } 2471 2472 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 2473 const Expr *E, const VarDecl *VD) { 2474 QualType T = E->getType(); 2475 2476 // If it's thread_local, emit a call to its wrapper function instead. 2477 if (VD->getTLSKind() == VarDecl::TLS_Dynamic && 2478 CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD)) 2479 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T); 2480 // Check if the variable is marked as declare target with link clause in 2481 // device codegen. 2482 if (CGF.getLangOpts().OpenMPIsDevice) { 2483 Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T); 2484 if (Addr.isValid()) 2485 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 2486 } 2487 2488 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 2489 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType()); 2490 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy); 2491 CharUnits Alignment = CGF.getContext().getDeclAlign(VD); 2492 Address Addr(V, Alignment); 2493 // Emit reference to the private copy of the variable if it is an OpenMP 2494 // threadprivate variable. 2495 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd && 2496 VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 2497 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy, 2498 E->getExprLoc()); 2499 } 2500 LValue LV = VD->getType()->isReferenceType() ? 2501 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(), 2502 AlignmentSource::Decl) : 2503 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 2504 setObjCGCLValueClass(CGF.getContext(), E, LV); 2505 return LV; 2506 } 2507 2508 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM, 2509 GlobalDecl GD) { 2510 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2511 if (FD->hasAttr<WeakRefAttr>()) { 2512 ConstantAddress aliasee = CGM.GetWeakRefReference(FD); 2513 return aliasee.getPointer(); 2514 } 2515 2516 llvm::Constant *V = CGM.GetAddrOfFunction(GD); 2517 if (!FD->hasPrototype()) { 2518 if (const FunctionProtoType *Proto = 2519 FD->getType()->getAs<FunctionProtoType>()) { 2520 // Ugly case: for a K&R-style definition, the type of the definition 2521 // isn't the same as the type of a use. Correct for this with a 2522 // bitcast. 2523 QualType NoProtoType = 2524 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType()); 2525 NoProtoType = CGM.getContext().getPointerType(NoProtoType); 2526 V = llvm::ConstantExpr::getBitCast(V, 2527 CGM.getTypes().ConvertType(NoProtoType)); 2528 } 2529 } 2530 return V; 2531 } 2532 2533 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, 2534 GlobalDecl GD) { 2535 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2536 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD); 2537 CharUnits Alignment = CGF.getContext().getDeclAlign(FD); 2538 return CGF.MakeAddrLValue(V, E->getType(), Alignment, 2539 AlignmentSource::Decl); 2540 } 2541 2542 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, 2543 llvm::Value *ThisValue) { 2544 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent()); 2545 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType); 2546 return CGF.EmitLValueForField(LV, FD); 2547 } 2548 2549 /// Named Registers are named metadata pointing to the register name 2550 /// which will be read from/written to as an argument to the intrinsic 2551 /// @llvm.read/write_register. 2552 /// So far, only the name is being passed down, but other options such as 2553 /// register type, allocation type or even optimization options could be 2554 /// passed down via the metadata node. 2555 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) { 2556 SmallString<64> Name("llvm.named.register."); 2557 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>(); 2558 assert(Asm->getLabel().size() < 64-Name.size() && 2559 "Register name too big"); 2560 Name.append(Asm->getLabel()); 2561 llvm::NamedMDNode *M = 2562 CGM.getModule().getOrInsertNamedMetadata(Name); 2563 if (M->getNumOperands() == 0) { 2564 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(), 2565 Asm->getLabel()); 2566 llvm::Metadata *Ops[] = {Str}; 2567 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2568 } 2569 2570 CharUnits Alignment = CGM.getContext().getDeclAlign(VD); 2571 2572 llvm::Value *Ptr = 2573 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)); 2574 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType()); 2575 } 2576 2577 /// Determine whether we can emit a reference to \p VD from the current 2578 /// context, despite not necessarily having seen an odr-use of the variable in 2579 /// this context. 2580 static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF, 2581 const DeclRefExpr *E, 2582 const VarDecl *VD, 2583 bool IsConstant) { 2584 // For a variable declared in an enclosing scope, do not emit a spurious 2585 // reference even if we have a capture, as that will emit an unwarranted 2586 // reference to our capture state, and will likely generate worse code than 2587 // emitting a local copy. 2588 if (E->refersToEnclosingVariableOrCapture()) 2589 return false; 2590 2591 // For a local declaration declared in this function, we can always reference 2592 // it even if we don't have an odr-use. 2593 if (VD->hasLocalStorage()) { 2594 return VD->getDeclContext() == 2595 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl); 2596 } 2597 2598 // For a global declaration, we can emit a reference to it if we know 2599 // for sure that we are able to emit a definition of it. 2600 VD = VD->getDefinition(CGF.getContext()); 2601 if (!VD) 2602 return false; 2603 2604 // Don't emit a spurious reference if it might be to a variable that only 2605 // exists on a different device / target. 2606 // FIXME: This is unnecessarily broad. Check whether this would actually be a 2607 // cross-target reference. 2608 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA || 2609 CGF.getLangOpts().OpenCL) { 2610 return false; 2611 } 2612 2613 // We can emit a spurious reference only if the linkage implies that we'll 2614 // be emitting a non-interposable symbol that will be retained until link 2615 // time. 2616 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) { 2617 case llvm::GlobalValue::ExternalLinkage: 2618 case llvm::GlobalValue::LinkOnceODRLinkage: 2619 case llvm::GlobalValue::WeakODRLinkage: 2620 case llvm::GlobalValue::InternalLinkage: 2621 case llvm::GlobalValue::PrivateLinkage: 2622 return true; 2623 default: 2624 return false; 2625 } 2626 } 2627 2628 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 2629 const NamedDecl *ND = E->getDecl(); 2630 QualType T = E->getType(); 2631 2632 assert(E->isNonOdrUse() != NOUR_Unevaluated && 2633 "should not emit an unevaluated operand"); 2634 2635 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2636 // Global Named registers access via intrinsics only 2637 if (VD->getStorageClass() == SC_Register && 2638 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl()) 2639 return EmitGlobalNamedRegister(VD, CGM); 2640 2641 // If this DeclRefExpr does not constitute an odr-use of the variable, 2642 // we're not permitted to emit a reference to it in general, and it might 2643 // not be captured if capture would be necessary for a use. Emit the 2644 // constant value directly instead. 2645 if (E->isNonOdrUse() == NOUR_Constant && 2646 (VD->getType()->isReferenceType() || 2647 !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) { 2648 VD->getAnyInitializer(VD); 2649 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract( 2650 E->getLocation(), *VD->evaluateValue(), VD->getType()); 2651 assert(Val && "failed to emit constant expression"); 2652 2653 Address Addr = Address::invalid(); 2654 if (!VD->getType()->isReferenceType()) { 2655 // Spill the constant value to a global. 2656 Addr = CGM.createUnnamedGlobalFrom(*VD, Val, 2657 getContext().getDeclAlign(VD)); 2658 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType()); 2659 auto *PTy = llvm::PointerType::get( 2660 VarTy, getContext().getTargetAddressSpace(VD->getType())); 2661 if (PTy != Addr.getType()) 2662 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy); 2663 } else { 2664 // Should we be using the alignment of the constant pointer we emitted? 2665 CharUnits Alignment = 2666 CGM.getNaturalTypeAlignment(E->getType(), 2667 /* BaseInfo= */ nullptr, 2668 /* TBAAInfo= */ nullptr, 2669 /* forPointeeType= */ true); 2670 Addr = Address(Val, Alignment); 2671 } 2672 return MakeAddrLValue(Addr, T, AlignmentSource::Decl); 2673 } 2674 2675 // FIXME: Handle other kinds of non-odr-use DeclRefExprs. 2676 2677 // Check for captured variables. 2678 if (E->refersToEnclosingVariableOrCapture()) { 2679 VD = VD->getCanonicalDecl(); 2680 if (auto *FD = LambdaCaptureFields.lookup(VD)) 2681 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue); 2682 if (CapturedStmtInfo) { 2683 auto I = LocalDeclMap.find(VD); 2684 if (I != LocalDeclMap.end()) { 2685 LValue CapLVal; 2686 if (VD->getType()->isReferenceType()) 2687 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(), 2688 AlignmentSource::Decl); 2689 else 2690 CapLVal = MakeAddrLValue(I->second, T); 2691 // Mark lvalue as nontemporal if the variable is marked as nontemporal 2692 // in simd context. 2693 if (getLangOpts().OpenMP && 2694 CGM.getOpenMPRuntime().isNontemporalDecl(VD)) 2695 CapLVal.setNontemporal(/*Value=*/true); 2696 return CapLVal; 2697 } 2698 LValue CapLVal = 2699 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD), 2700 CapturedStmtInfo->getContextValue()); 2701 CapLVal = MakeAddrLValue( 2702 Address(CapLVal.getPointer(*this), getContext().getDeclAlign(VD)), 2703 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl), 2704 CapLVal.getTBAAInfo()); 2705 // Mark lvalue as nontemporal if the variable is marked as nontemporal 2706 // in simd context. 2707 if (getLangOpts().OpenMP && 2708 CGM.getOpenMPRuntime().isNontemporalDecl(VD)) 2709 CapLVal.setNontemporal(/*Value=*/true); 2710 return CapLVal; 2711 } 2712 2713 assert(isa<BlockDecl>(CurCodeDecl)); 2714 Address addr = GetAddrOfBlockDecl(VD); 2715 return MakeAddrLValue(addr, T, AlignmentSource::Decl); 2716 } 2717 } 2718 2719 // FIXME: We should be able to assert this for FunctionDecls as well! 2720 // FIXME: We should be able to assert this for all DeclRefExprs, not just 2721 // those with a valid source location. 2722 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() || 2723 !E->getLocation().isValid()) && 2724 "Should not use decl without marking it used!"); 2725 2726 if (ND->hasAttr<WeakRefAttr>()) { 2727 const auto *VD = cast<ValueDecl>(ND); 2728 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD); 2729 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl); 2730 } 2731 2732 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2733 // Check if this is a global variable. 2734 if (VD->hasLinkage() || VD->isStaticDataMember()) 2735 return EmitGlobalVarDeclLValue(*this, E, VD); 2736 2737 Address addr = Address::invalid(); 2738 2739 // The variable should generally be present in the local decl map. 2740 auto iter = LocalDeclMap.find(VD); 2741 if (iter != LocalDeclMap.end()) { 2742 addr = iter->second; 2743 2744 // Otherwise, it might be static local we haven't emitted yet for 2745 // some reason; most likely, because it's in an outer function. 2746 } else if (VD->isStaticLocal()) { 2747 addr = Address(CGM.getOrCreateStaticVarDecl( 2748 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)), 2749 getContext().getDeclAlign(VD)); 2750 2751 // No other cases for now. 2752 } else { 2753 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?"); 2754 } 2755 2756 2757 // Check for OpenMP threadprivate variables. 2758 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd && 2759 VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 2760 return EmitThreadPrivateVarDeclLValue( 2761 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()), 2762 E->getExprLoc()); 2763 } 2764 2765 // Drill into block byref variables. 2766 bool isBlockByref = VD->isEscapingByref(); 2767 if (isBlockByref) { 2768 addr = emitBlockByrefAddress(addr, VD); 2769 } 2770 2771 // Drill into reference types. 2772 LValue LV = VD->getType()->isReferenceType() ? 2773 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) : 2774 MakeAddrLValue(addr, T, AlignmentSource::Decl); 2775 2776 bool isLocalStorage = VD->hasLocalStorage(); 2777 2778 bool NonGCable = isLocalStorage && 2779 !VD->getType()->isReferenceType() && 2780 !isBlockByref; 2781 if (NonGCable) { 2782 LV.getQuals().removeObjCGCAttr(); 2783 LV.setNonGC(true); 2784 } 2785 2786 bool isImpreciseLifetime = 2787 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>()); 2788 if (isImpreciseLifetime) 2789 LV.setARCPreciseLifetime(ARCImpreciseLifetime); 2790 setObjCGCLValueClass(getContext(), E, LV); 2791 return LV; 2792 } 2793 2794 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 2795 return EmitFunctionDeclLValue(*this, E, FD); 2796 2797 // FIXME: While we're emitting a binding from an enclosing scope, all other 2798 // DeclRefExprs we see should be implicitly treated as if they also refer to 2799 // an enclosing scope. 2800 if (const auto *BD = dyn_cast<BindingDecl>(ND)) 2801 return EmitLValue(BD->getBinding()); 2802 2803 // We can form DeclRefExprs naming GUID declarations when reconstituting 2804 // non-type template parameters into expressions. 2805 if (const auto *GD = dyn_cast<MSGuidDecl>(ND)) 2806 return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T, 2807 AlignmentSource::Decl); 2808 2809 llvm_unreachable("Unhandled DeclRefExpr"); 2810 } 2811 2812 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 2813 // __extension__ doesn't affect lvalue-ness. 2814 if (E->getOpcode() == UO_Extension) 2815 return EmitLValue(E->getSubExpr()); 2816 2817 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 2818 switch (E->getOpcode()) { 2819 default: llvm_unreachable("Unknown unary operator lvalue!"); 2820 case UO_Deref: { 2821 QualType T = E->getSubExpr()->getType()->getPointeeType(); 2822 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 2823 2824 LValueBaseInfo BaseInfo; 2825 TBAAAccessInfo TBAAInfo; 2826 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo, 2827 &TBAAInfo); 2828 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo); 2829 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 2830 2831 // We should not generate __weak write barrier on indirect reference 2832 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 2833 // But, we continue to generate __strong write barrier on indirect write 2834 // into a pointer to object. 2835 if (getLangOpts().ObjC && 2836 getLangOpts().getGC() != LangOptions::NonGC && 2837 LV.isObjCWeak()) 2838 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 2839 return LV; 2840 } 2841 case UO_Real: 2842 case UO_Imag: { 2843 LValue LV = EmitLValue(E->getSubExpr()); 2844 assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 2845 2846 // __real is valid on scalars. This is a faster way of testing that. 2847 // __imag can only produce an rvalue on scalars. 2848 if (E->getOpcode() == UO_Real && 2849 !LV.getAddress(*this).getElementType()->isStructTy()) { 2850 assert(E->getSubExpr()->getType()->isArithmeticType()); 2851 return LV; 2852 } 2853 2854 QualType T = ExprTy->castAs<ComplexType>()->getElementType(); 2855 2856 Address Component = 2857 (E->getOpcode() == UO_Real 2858 ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType()) 2859 : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType())); 2860 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(), 2861 CGM.getTBAAInfoForSubobject(LV, T)); 2862 ElemLV.getQuals().addQualifiers(LV.getQuals()); 2863 return ElemLV; 2864 } 2865 case UO_PreInc: 2866 case UO_PreDec: { 2867 LValue LV = EmitLValue(E->getSubExpr()); 2868 bool isInc = E->getOpcode() == UO_PreInc; 2869 2870 if (E->getType()->isAnyComplexType()) 2871 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 2872 else 2873 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 2874 return LV; 2875 } 2876 } 2877 } 2878 2879 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 2880 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 2881 E->getType(), AlignmentSource::Decl); 2882 } 2883 2884 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 2885 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 2886 E->getType(), AlignmentSource::Decl); 2887 } 2888 2889 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 2890 auto SL = E->getFunctionName(); 2891 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr"); 2892 StringRef FnName = CurFn->getName(); 2893 if (FnName.startswith("\01")) 2894 FnName = FnName.substr(1); 2895 StringRef NameItems[] = { 2896 PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName}; 2897 std::string GVName = llvm::join(NameItems, NameItems + 2, "."); 2898 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) { 2899 std::string Name = std::string(SL->getString()); 2900 if (!Name.empty()) { 2901 unsigned Discriminator = 2902 CGM.getCXXABI().getMangleContext().getBlockId(BD, true); 2903 if (Discriminator) 2904 Name += "_" + Twine(Discriminator + 1).str(); 2905 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str()); 2906 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 2907 } else { 2908 auto C = 2909 CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str()); 2910 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 2911 } 2912 } 2913 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName); 2914 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 2915 } 2916 2917 /// Emit a type description suitable for use by a runtime sanitizer library. The 2918 /// format of a type descriptor is 2919 /// 2920 /// \code 2921 /// { i16 TypeKind, i16 TypeInfo } 2922 /// \endcode 2923 /// 2924 /// followed by an array of i8 containing the type name. TypeKind is 0 for an 2925 /// integer, 1 for a floating point value, and -1 for anything else. 2926 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) { 2927 // Only emit each type's descriptor once. 2928 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T)) 2929 return C; 2930 2931 uint16_t TypeKind = -1; 2932 uint16_t TypeInfo = 0; 2933 2934 if (T->isIntegerType()) { 2935 TypeKind = 0; 2936 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) | 2937 (T->isSignedIntegerType() ? 1 : 0); 2938 } else if (T->isFloatingType()) { 2939 TypeKind = 1; 2940 TypeInfo = getContext().getTypeSize(T); 2941 } 2942 2943 // Format the type name as if for a diagnostic, including quotes and 2944 // optionally an 'aka'. 2945 SmallString<32> Buffer; 2946 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype, 2947 (intptr_t)T.getAsOpaquePtr(), 2948 StringRef(), StringRef(), None, Buffer, 2949 None); 2950 2951 llvm::Constant *Components[] = { 2952 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo), 2953 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer) 2954 }; 2955 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components); 2956 2957 auto *GV = new llvm::GlobalVariable( 2958 CGM.getModule(), Descriptor->getType(), 2959 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor); 2960 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2961 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV); 2962 2963 // Remember the descriptor for this type. 2964 CGM.setTypeDescriptorInMap(T, GV); 2965 2966 return GV; 2967 } 2968 2969 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) { 2970 llvm::Type *TargetTy = IntPtrTy; 2971 2972 if (V->getType() == TargetTy) 2973 return V; 2974 2975 // Floating-point types which fit into intptr_t are bitcast to integers 2976 // and then passed directly (after zero-extension, if necessary). 2977 if (V->getType()->isFloatingPointTy()) { 2978 unsigned Bits = V->getType()->getPrimitiveSizeInBits(); 2979 if (Bits <= TargetTy->getIntegerBitWidth()) 2980 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(), 2981 Bits)); 2982 } 2983 2984 // Integers which fit in intptr_t are zero-extended and passed directly. 2985 if (V->getType()->isIntegerTy() && 2986 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()) 2987 return Builder.CreateZExt(V, TargetTy); 2988 2989 // Pointers are passed directly, everything else is passed by address. 2990 if (!V->getType()->isPointerTy()) { 2991 Address Ptr = CreateDefaultAlignTempAlloca(V->getType()); 2992 Builder.CreateStore(V, Ptr); 2993 V = Ptr.getPointer(); 2994 } 2995 return Builder.CreatePtrToInt(V, TargetTy); 2996 } 2997 2998 /// Emit a representation of a SourceLocation for passing to a handler 2999 /// in a sanitizer runtime library. The format for this data is: 3000 /// \code 3001 /// struct SourceLocation { 3002 /// const char *Filename; 3003 /// int32_t Line, Column; 3004 /// }; 3005 /// \endcode 3006 /// For an invalid SourceLocation, the Filename pointer is null. 3007 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) { 3008 llvm::Constant *Filename; 3009 int Line, Column; 3010 3011 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); 3012 if (PLoc.isValid()) { 3013 StringRef FilenameString = PLoc.getFilename(); 3014 3015 int PathComponentsToStrip = 3016 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip; 3017 if (PathComponentsToStrip < 0) { 3018 assert(PathComponentsToStrip != INT_MIN); 3019 int PathComponentsToKeep = -PathComponentsToStrip; 3020 auto I = llvm::sys::path::rbegin(FilenameString); 3021 auto E = llvm::sys::path::rend(FilenameString); 3022 while (I != E && --PathComponentsToKeep) 3023 ++I; 3024 3025 FilenameString = FilenameString.substr(I - E); 3026 } else if (PathComponentsToStrip > 0) { 3027 auto I = llvm::sys::path::begin(FilenameString); 3028 auto E = llvm::sys::path::end(FilenameString); 3029 while (I != E && PathComponentsToStrip--) 3030 ++I; 3031 3032 if (I != E) 3033 FilenameString = 3034 FilenameString.substr(I - llvm::sys::path::begin(FilenameString)); 3035 else 3036 FilenameString = llvm::sys::path::filename(FilenameString); 3037 } 3038 3039 auto FilenameGV = 3040 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src"); 3041 CGM.getSanitizerMetadata()->disableSanitizerForGlobal( 3042 cast<llvm::GlobalVariable>(FilenameGV.getPointer())); 3043 Filename = FilenameGV.getPointer(); 3044 Line = PLoc.getLine(); 3045 Column = PLoc.getColumn(); 3046 } else { 3047 Filename = llvm::Constant::getNullValue(Int8PtrTy); 3048 Line = Column = 0; 3049 } 3050 3051 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line), 3052 Builder.getInt32(Column)}; 3053 3054 return llvm::ConstantStruct::getAnon(Data); 3055 } 3056 3057 namespace { 3058 /// Specify under what conditions this check can be recovered 3059 enum class CheckRecoverableKind { 3060 /// Always terminate program execution if this check fails. 3061 Unrecoverable, 3062 /// Check supports recovering, runtime has both fatal (noreturn) and 3063 /// non-fatal handlers for this check. 3064 Recoverable, 3065 /// Runtime conditionally aborts, always need to support recovery. 3066 AlwaysRecoverable 3067 }; 3068 } 3069 3070 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) { 3071 assert(Kind.countPopulation() == 1); 3072 if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr) 3073 return CheckRecoverableKind::AlwaysRecoverable; 3074 else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable) 3075 return CheckRecoverableKind::Unrecoverable; 3076 else 3077 return CheckRecoverableKind::Recoverable; 3078 } 3079 3080 namespace { 3081 struct SanitizerHandlerInfo { 3082 char const *const Name; 3083 unsigned Version; 3084 }; 3085 } 3086 3087 const SanitizerHandlerInfo SanitizerHandlers[] = { 3088 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version}, 3089 LIST_SANITIZER_CHECKS 3090 #undef SANITIZER_CHECK 3091 }; 3092 3093 static void emitCheckHandlerCall(CodeGenFunction &CGF, 3094 llvm::FunctionType *FnType, 3095 ArrayRef<llvm::Value *> FnArgs, 3096 SanitizerHandler CheckHandler, 3097 CheckRecoverableKind RecoverKind, bool IsFatal, 3098 llvm::BasicBlock *ContBB) { 3099 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable); 3100 Optional<ApplyDebugLocation> DL; 3101 if (!CGF.Builder.getCurrentDebugLocation()) { 3102 // Ensure that the call has at least an artificial debug location. 3103 DL.emplace(CGF, SourceLocation()); 3104 } 3105 bool NeedsAbortSuffix = 3106 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable; 3107 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime; 3108 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler]; 3109 const StringRef CheckName = CheckInfo.Name; 3110 std::string FnName = "__ubsan_handle_" + CheckName.str(); 3111 if (CheckInfo.Version && !MinimalRuntime) 3112 FnName += "_v" + llvm::utostr(CheckInfo.Version); 3113 if (MinimalRuntime) 3114 FnName += "_minimal"; 3115 if (NeedsAbortSuffix) 3116 FnName += "_abort"; 3117 bool MayReturn = 3118 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable; 3119 3120 llvm::AttrBuilder B; 3121 if (!MayReturn) { 3122 B.addAttribute(llvm::Attribute::NoReturn) 3123 .addAttribute(llvm::Attribute::NoUnwind); 3124 } 3125 B.addAttribute(llvm::Attribute::UWTable); 3126 3127 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction( 3128 FnType, FnName, 3129 llvm::AttributeList::get(CGF.getLLVMContext(), 3130 llvm::AttributeList::FunctionIndex, B), 3131 /*Local=*/true); 3132 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs); 3133 if (!MayReturn) { 3134 HandlerCall->setDoesNotReturn(); 3135 CGF.Builder.CreateUnreachable(); 3136 } else { 3137 CGF.Builder.CreateBr(ContBB); 3138 } 3139 } 3140 3141 void CodeGenFunction::EmitCheck( 3142 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 3143 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs, 3144 ArrayRef<llvm::Value *> DynamicArgs) { 3145 assert(IsSanitizerScope); 3146 assert(Checked.size() > 0); 3147 assert(CheckHandler >= 0 && 3148 size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers)); 3149 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name; 3150 3151 llvm::Value *FatalCond = nullptr; 3152 llvm::Value *RecoverableCond = nullptr; 3153 llvm::Value *TrapCond = nullptr; 3154 for (int i = 0, n = Checked.size(); i < n; ++i) { 3155 llvm::Value *Check = Checked[i].first; 3156 // -fsanitize-trap= overrides -fsanitize-recover=. 3157 llvm::Value *&Cond = 3158 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second) 3159 ? TrapCond 3160 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second) 3161 ? RecoverableCond 3162 : FatalCond; 3163 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check; 3164 } 3165 3166 if (TrapCond) 3167 EmitTrapCheck(TrapCond); 3168 if (!FatalCond && !RecoverableCond) 3169 return; 3170 3171 llvm::Value *JointCond; 3172 if (FatalCond && RecoverableCond) 3173 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond); 3174 else 3175 JointCond = FatalCond ? FatalCond : RecoverableCond; 3176 assert(JointCond); 3177 3178 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second); 3179 assert(SanOpts.has(Checked[0].second)); 3180 #ifndef NDEBUG 3181 for (int i = 1, n = Checked.size(); i < n; ++i) { 3182 assert(RecoverKind == getRecoverableKind(Checked[i].second) && 3183 "All recoverable kinds in a single check must be same!"); 3184 assert(SanOpts.has(Checked[i].second)); 3185 } 3186 #endif 3187 3188 llvm::BasicBlock *Cont = createBasicBlock("cont"); 3189 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName); 3190 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers); 3191 // Give hint that we very much don't expect to execute the handler 3192 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp 3193 llvm::MDBuilder MDHelper(getLLVMContext()); 3194 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 3195 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node); 3196 EmitBlock(Handlers); 3197 3198 // Handler functions take an i8* pointing to the (handler-specific) static 3199 // information block, followed by a sequence of intptr_t arguments 3200 // representing operand values. 3201 SmallVector<llvm::Value *, 4> Args; 3202 SmallVector<llvm::Type *, 4> ArgTypes; 3203 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) { 3204 Args.reserve(DynamicArgs.size() + 1); 3205 ArgTypes.reserve(DynamicArgs.size() + 1); 3206 3207 // Emit handler arguments and create handler function type. 3208 if (!StaticArgs.empty()) { 3209 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 3210 auto *InfoPtr = 3211 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 3212 llvm::GlobalVariable::PrivateLinkage, Info); 3213 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3214 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 3215 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy)); 3216 ArgTypes.push_back(Int8PtrTy); 3217 } 3218 3219 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) { 3220 Args.push_back(EmitCheckValue(DynamicArgs[i])); 3221 ArgTypes.push_back(IntPtrTy); 3222 } 3223 } 3224 3225 llvm::FunctionType *FnType = 3226 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false); 3227 3228 if (!FatalCond || !RecoverableCond) { 3229 // Simple case: we need to generate a single handler call, either 3230 // fatal, or non-fatal. 3231 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, 3232 (FatalCond != nullptr), Cont); 3233 } else { 3234 // Emit two handler calls: first one for set of unrecoverable checks, 3235 // another one for recoverable. 3236 llvm::BasicBlock *NonFatalHandlerBB = 3237 createBasicBlock("non_fatal." + CheckName); 3238 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName); 3239 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB); 3240 EmitBlock(FatalHandlerBB); 3241 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true, 3242 NonFatalHandlerBB); 3243 EmitBlock(NonFatalHandlerBB); 3244 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false, 3245 Cont); 3246 } 3247 3248 EmitBlock(Cont); 3249 } 3250 3251 void CodeGenFunction::EmitCfiSlowPathCheck( 3252 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId, 3253 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) { 3254 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont"); 3255 3256 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath"); 3257 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB); 3258 3259 llvm::MDBuilder MDHelper(getLLVMContext()); 3260 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 3261 BI->setMetadata(llvm::LLVMContext::MD_prof, Node); 3262 3263 EmitBlock(CheckBB); 3264 3265 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind); 3266 3267 llvm::CallInst *CheckCall; 3268 llvm::FunctionCallee SlowPathFn; 3269 if (WithDiag) { 3270 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 3271 auto *InfoPtr = 3272 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 3273 llvm::GlobalVariable::PrivateLinkage, Info); 3274 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3275 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 3276 3277 SlowPathFn = CGM.getModule().getOrInsertFunction( 3278 "__cfi_slowpath_diag", 3279 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, 3280 false)); 3281 CheckCall = Builder.CreateCall( 3282 SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)}); 3283 } else { 3284 SlowPathFn = CGM.getModule().getOrInsertFunction( 3285 "__cfi_slowpath", 3286 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false)); 3287 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr}); 3288 } 3289 3290 CGM.setDSOLocal( 3291 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts())); 3292 CheckCall->setDoesNotThrow(); 3293 3294 EmitBlock(Cont); 3295 } 3296 3297 // Emit a stub for __cfi_check function so that the linker knows about this 3298 // symbol in LTO mode. 3299 void CodeGenFunction::EmitCfiCheckStub() { 3300 llvm::Module *M = &CGM.getModule(); 3301 auto &Ctx = M->getContext(); 3302 llvm::Function *F = llvm::Function::Create( 3303 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false), 3304 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M); 3305 CGM.setDSOLocal(F); 3306 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F); 3307 // FIXME: consider emitting an intrinsic call like 3308 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2) 3309 // which can be lowered in CrossDSOCFI pass to the actual contents of 3310 // __cfi_check. This would allow inlining of __cfi_check calls. 3311 llvm::CallInst::Create( 3312 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB); 3313 llvm::ReturnInst::Create(Ctx, nullptr, BB); 3314 } 3315 3316 // This function is basically a switch over the CFI failure kind, which is 3317 // extracted from CFICheckFailData (1st function argument). Each case is either 3318 // llvm.trap or a call to one of the two runtime handlers, based on 3319 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid 3320 // failure kind) traps, but this should really never happen. CFICheckFailData 3321 // can be nullptr if the calling module has -fsanitize-trap behavior for this 3322 // check kind; in this case __cfi_check_fail traps as well. 3323 void CodeGenFunction::EmitCfiCheckFail() { 3324 SanitizerScope SanScope(this); 3325 FunctionArgList Args; 3326 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy, 3327 ImplicitParamDecl::Other); 3328 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy, 3329 ImplicitParamDecl::Other); 3330 Args.push_back(&ArgData); 3331 Args.push_back(&ArgAddr); 3332 3333 const CGFunctionInfo &FI = 3334 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args); 3335 3336 llvm::Function *F = llvm::Function::Create( 3337 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false), 3338 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule()); 3339 3340 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F); 3341 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F); 3342 F->setVisibility(llvm::GlobalValue::HiddenVisibility); 3343 3344 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args, 3345 SourceLocation()); 3346 3347 // This function should not be affected by blacklist. This function does 3348 // not have a source location, but "src:*" would still apply. Revert any 3349 // changes to SanOpts made in StartFunction. 3350 SanOpts = CGM.getLangOpts().Sanitize; 3351 3352 llvm::Value *Data = 3353 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false, 3354 CGM.getContext().VoidPtrTy, ArgData.getLocation()); 3355 llvm::Value *Addr = 3356 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false, 3357 CGM.getContext().VoidPtrTy, ArgAddr.getLocation()); 3358 3359 // Data == nullptr means the calling module has trap behaviour for this check. 3360 llvm::Value *DataIsNotNullPtr = 3361 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy)); 3362 EmitTrapCheck(DataIsNotNullPtr); 3363 3364 llvm::StructType *SourceLocationTy = 3365 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty); 3366 llvm::StructType *CfiCheckFailDataTy = 3367 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy); 3368 3369 llvm::Value *V = Builder.CreateConstGEP2_32( 3370 CfiCheckFailDataTy, 3371 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0, 3372 0); 3373 Address CheckKindAddr(V, getIntAlign()); 3374 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr); 3375 3376 llvm::Value *AllVtables = llvm::MetadataAsValue::get( 3377 CGM.getLLVMContext(), 3378 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 3379 llvm::Value *ValidVtable = Builder.CreateZExt( 3380 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), 3381 {Addr, AllVtables}), 3382 IntPtrTy); 3383 3384 const std::pair<int, SanitizerMask> CheckKinds[] = { 3385 {CFITCK_VCall, SanitizerKind::CFIVCall}, 3386 {CFITCK_NVCall, SanitizerKind::CFINVCall}, 3387 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast}, 3388 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast}, 3389 {CFITCK_ICall, SanitizerKind::CFIICall}}; 3390 3391 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks; 3392 for (auto CheckKindMaskPair : CheckKinds) { 3393 int Kind = CheckKindMaskPair.first; 3394 SanitizerMask Mask = CheckKindMaskPair.second; 3395 llvm::Value *Cond = 3396 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind)); 3397 if (CGM.getLangOpts().Sanitize.has(Mask)) 3398 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {}, 3399 {Data, Addr, ValidVtable}); 3400 else 3401 EmitTrapCheck(Cond); 3402 } 3403 3404 FinishFunction(); 3405 // The only reference to this function will be created during LTO link. 3406 // Make sure it survives until then. 3407 CGM.addUsedGlobal(F); 3408 } 3409 3410 void CodeGenFunction::EmitUnreachable(SourceLocation Loc) { 3411 if (SanOpts.has(SanitizerKind::Unreachable)) { 3412 SanitizerScope SanScope(this); 3413 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()), 3414 SanitizerKind::Unreachable), 3415 SanitizerHandler::BuiltinUnreachable, 3416 EmitCheckSourceLocation(Loc), None); 3417 } 3418 Builder.CreateUnreachable(); 3419 } 3420 3421 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) { 3422 llvm::BasicBlock *Cont = createBasicBlock("cont"); 3423 3424 // If we're optimizing, collapse all calls to trap down to just one per 3425 // function to save on code size. 3426 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) { 3427 TrapBB = createBasicBlock("trap"); 3428 Builder.CreateCondBr(Checked, Cont, TrapBB); 3429 EmitBlock(TrapBB); 3430 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 3431 TrapCall->setDoesNotReturn(); 3432 TrapCall->setDoesNotThrow(); 3433 Builder.CreateUnreachable(); 3434 } else { 3435 Builder.CreateCondBr(Checked, Cont, TrapBB); 3436 } 3437 3438 EmitBlock(Cont); 3439 } 3440 3441 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) { 3442 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID)); 3443 3444 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) { 3445 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name", 3446 CGM.getCodeGenOpts().TrapFuncName); 3447 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A); 3448 } 3449 3450 return TrapCall; 3451 } 3452 3453 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E, 3454 LValueBaseInfo *BaseInfo, 3455 TBAAAccessInfo *TBAAInfo) { 3456 assert(E->getType()->isArrayType() && 3457 "Array to pointer decay must have array source type!"); 3458 3459 // Expressions of array type can't be bitfields or vector elements. 3460 LValue LV = EmitLValue(E); 3461 Address Addr = LV.getAddress(*this); 3462 3463 // If the array type was an incomplete type, we need to make sure 3464 // the decay ends up being the right type. 3465 llvm::Type *NewTy = ConvertType(E->getType()); 3466 Addr = Builder.CreateElementBitCast(Addr, NewTy); 3467 3468 // Note that VLA pointers are always decayed, so we don't need to do 3469 // anything here. 3470 if (!E->getType()->isVariableArrayType()) { 3471 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 3472 "Expected pointer to array"); 3473 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay"); 3474 } 3475 3476 // The result of this decay conversion points to an array element within the 3477 // base lvalue. However, since TBAA currently does not support representing 3478 // accesses to elements of member arrays, we conservatively represent accesses 3479 // to the pointee object as if it had no any base lvalue specified. 3480 // TODO: Support TBAA for member arrays. 3481 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType(); 3482 if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 3483 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType); 3484 3485 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType)); 3486 } 3487 3488 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 3489 /// array to pointer, return the array subexpression. 3490 static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 3491 // If this isn't just an array->pointer decay, bail out. 3492 const auto *CE = dyn_cast<CastExpr>(E); 3493 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay) 3494 return nullptr; 3495 3496 // If this is a decay from variable width array, bail out. 3497 const Expr *SubExpr = CE->getSubExpr(); 3498 if (SubExpr->getType()->isVariableArrayType()) 3499 return nullptr; 3500 3501 return SubExpr; 3502 } 3503 3504 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF, 3505 llvm::Value *ptr, 3506 ArrayRef<llvm::Value*> indices, 3507 bool inbounds, 3508 bool signedIndices, 3509 SourceLocation loc, 3510 const llvm::Twine &name = "arrayidx") { 3511 if (inbounds) { 3512 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices, 3513 CodeGenFunction::NotSubtraction, loc, 3514 name); 3515 } else { 3516 return CGF.Builder.CreateGEP(ptr, indices, name); 3517 } 3518 } 3519 3520 static CharUnits getArrayElementAlign(CharUnits arrayAlign, 3521 llvm::Value *idx, 3522 CharUnits eltSize) { 3523 // If we have a constant index, we can use the exact offset of the 3524 // element we're accessing. 3525 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) { 3526 CharUnits offset = constantIdx->getZExtValue() * eltSize; 3527 return arrayAlign.alignmentAtOffset(offset); 3528 3529 // Otherwise, use the worst-case alignment for any element. 3530 } else { 3531 return arrayAlign.alignmentOfArrayElement(eltSize); 3532 } 3533 } 3534 3535 static QualType getFixedSizeElementType(const ASTContext &ctx, 3536 const VariableArrayType *vla) { 3537 QualType eltType; 3538 do { 3539 eltType = vla->getElementType(); 3540 } while ((vla = ctx.getAsVariableArrayType(eltType))); 3541 return eltType; 3542 } 3543 3544 /// Given an array base, check whether its member access belongs to a record 3545 /// with preserve_access_index attribute or not. 3546 static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) { 3547 if (!ArrayBase || !CGF.getDebugInfo()) 3548 return false; 3549 3550 // Only support base as either a MemberExpr or DeclRefExpr. 3551 // DeclRefExpr to cover cases like: 3552 // struct s { int a; int b[10]; }; 3553 // struct s *p; 3554 // p[1].a 3555 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr. 3556 // p->b[5] is a MemberExpr example. 3557 const Expr *E = ArrayBase->IgnoreImpCasts(); 3558 if (const auto *ME = dyn_cast<MemberExpr>(E)) 3559 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>(); 3560 3561 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 3562 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl()); 3563 if (!VarDef) 3564 return false; 3565 3566 const auto *PtrT = VarDef->getType()->getAs<PointerType>(); 3567 if (!PtrT) 3568 return false; 3569 3570 const auto *PointeeT = PtrT->getPointeeType() 3571 ->getUnqualifiedDesugaredType(); 3572 if (const auto *RecT = dyn_cast<RecordType>(PointeeT)) 3573 return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>(); 3574 return false; 3575 } 3576 3577 return false; 3578 } 3579 3580 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, 3581 ArrayRef<llvm::Value *> indices, 3582 QualType eltType, bool inbounds, 3583 bool signedIndices, SourceLocation loc, 3584 QualType *arrayType = nullptr, 3585 const Expr *Base = nullptr, 3586 const llvm::Twine &name = "arrayidx") { 3587 // All the indices except that last must be zero. 3588 #ifndef NDEBUG 3589 for (auto idx : indices.drop_back()) 3590 assert(isa<llvm::ConstantInt>(idx) && 3591 cast<llvm::ConstantInt>(idx)->isZero()); 3592 #endif 3593 3594 // Determine the element size of the statically-sized base. This is 3595 // the thing that the indices are expressed in terms of. 3596 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) { 3597 eltType = getFixedSizeElementType(CGF.getContext(), vla); 3598 } 3599 3600 // We can use that to compute the best alignment of the element. 3601 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 3602 CharUnits eltAlign = 3603 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize); 3604 3605 llvm::Value *eltPtr; 3606 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back()); 3607 if (!LastIndex || 3608 (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) { 3609 eltPtr = emitArraySubscriptGEP( 3610 CGF, addr.getPointer(), indices, inbounds, signedIndices, 3611 loc, name); 3612 } else { 3613 // Remember the original array subscript for bpf target 3614 unsigned idx = LastIndex->getZExtValue(); 3615 llvm::DIType *DbgInfo = nullptr; 3616 if (arrayType) 3617 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc); 3618 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(), 3619 addr.getPointer(), 3620 indices.size() - 1, 3621 idx, DbgInfo); 3622 } 3623 3624 return Address(eltPtr, eltAlign); 3625 } 3626 3627 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 3628 bool Accessed) { 3629 // The index must always be an integer, which is not an aggregate. Emit it 3630 // in lexical order (this complexity is, sadly, required by C++17). 3631 llvm::Value *IdxPre = 3632 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr; 3633 bool SignedIndices = false; 3634 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * { 3635 auto *Idx = IdxPre; 3636 if (E->getLHS() != E->getIdx()) { 3637 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS"); 3638 Idx = EmitScalarExpr(E->getIdx()); 3639 } 3640 3641 QualType IdxTy = E->getIdx()->getType(); 3642 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType(); 3643 SignedIndices |= IdxSigned; 3644 3645 if (SanOpts.has(SanitizerKind::ArrayBounds)) 3646 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed); 3647 3648 // Extend or truncate the index type to 32 or 64-bits. 3649 if (Promote && Idx->getType() != IntPtrTy) 3650 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 3651 3652 return Idx; 3653 }; 3654 IdxPre = nullptr; 3655 3656 // If the base is a vector type, then we are forming a vector element lvalue 3657 // with this subscript. 3658 if (E->getBase()->getType()->isVectorType() && 3659 !isa<ExtVectorElementExpr>(E->getBase())) { 3660 // Emit the vector as an lvalue to get its address. 3661 LValue LHS = EmitLValue(E->getBase()); 3662 auto *Idx = EmitIdxAfterBase(/*Promote*/false); 3663 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 3664 return LValue::MakeVectorElt(LHS.getAddress(*this), Idx, 3665 E->getBase()->getType(), LHS.getBaseInfo(), 3666 TBAAAccessInfo()); 3667 } 3668 3669 // All the other cases basically behave like simple offsetting. 3670 3671 // Handle the extvector case we ignored above. 3672 if (isa<ExtVectorElementExpr>(E->getBase())) { 3673 LValue LV = EmitLValue(E->getBase()); 3674 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3675 Address Addr = EmitExtVectorElementLValue(LV); 3676 3677 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType(); 3678 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true, 3679 SignedIndices, E->getExprLoc()); 3680 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(), 3681 CGM.getTBAAInfoForSubobject(LV, EltType)); 3682 } 3683 3684 LValueBaseInfo EltBaseInfo; 3685 TBAAAccessInfo EltTBAAInfo; 3686 Address Addr = Address::invalid(); 3687 if (const VariableArrayType *vla = 3688 getContext().getAsVariableArrayType(E->getType())) { 3689 // The base must be a pointer, which is not an aggregate. Emit 3690 // it. It needs to be emitted first in case it's what captures 3691 // the VLA bounds. 3692 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 3693 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3694 3695 // The element count here is the total number of non-VLA elements. 3696 llvm::Value *numElements = getVLASize(vla).NumElts; 3697 3698 // Effectively, the multiply by the VLA size is part of the GEP. 3699 // GEP indexes are signed, and scaling an index isn't permitted to 3700 // signed-overflow, so we use the same semantics for our explicit 3701 // multiply. We suppress this if overflow is not undefined behavior. 3702 if (getLangOpts().isSignedOverflowDefined()) { 3703 Idx = Builder.CreateMul(Idx, numElements); 3704 } else { 3705 Idx = Builder.CreateNSWMul(Idx, numElements); 3706 } 3707 3708 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(), 3709 !getLangOpts().isSignedOverflowDefined(), 3710 SignedIndices, E->getExprLoc()); 3711 3712 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 3713 // Indexing over an interface, as in "NSString *P; P[4];" 3714 3715 // Emit the base pointer. 3716 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 3717 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3718 3719 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT); 3720 llvm::Value *InterfaceSizeVal = 3721 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity()); 3722 3723 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal); 3724 3725 // We don't necessarily build correct LLVM struct types for ObjC 3726 // interfaces, so we can't rely on GEP to do this scaling 3727 // correctly, so we need to cast to i8*. FIXME: is this actually 3728 // true? A lot of other things in the fragile ABI would break... 3729 llvm::Type *OrigBaseTy = Addr.getType(); 3730 Addr = Builder.CreateElementBitCast(Addr, Int8Ty); 3731 3732 // Do the GEP. 3733 CharUnits EltAlign = 3734 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize); 3735 llvm::Value *EltPtr = 3736 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false, 3737 SignedIndices, E->getExprLoc()); 3738 Addr = Address(EltPtr, EltAlign); 3739 3740 // Cast back. 3741 Addr = Builder.CreateBitCast(Addr, OrigBaseTy); 3742 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3743 // If this is A[i] where A is an array, the frontend will have decayed the 3744 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3745 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3746 // "gep x, i" here. Emit one "gep A, 0, i". 3747 assert(Array->getType()->isArrayType() && 3748 "Array to pointer decay must have array source type!"); 3749 LValue ArrayLV; 3750 // For simple multidimensional array indexing, set the 'accessed' flag for 3751 // better bounds-checking of the base expression. 3752 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3753 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3754 else 3755 ArrayLV = EmitLValue(Array); 3756 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3757 3758 // Propagate the alignment from the array itself to the result. 3759 QualType arrayType = Array->getType(); 3760 Addr = emitArraySubscriptGEP( 3761 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx}, 3762 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, 3763 E->getExprLoc(), &arrayType, E->getBase()); 3764 EltBaseInfo = ArrayLV.getBaseInfo(); 3765 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType()); 3766 } else { 3767 // The base must be a pointer; emit it with an estimate of its alignment. 3768 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 3769 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3770 QualType ptrType = E->getBase()->getType(); 3771 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(), 3772 !getLangOpts().isSignedOverflowDefined(), 3773 SignedIndices, E->getExprLoc(), &ptrType, 3774 E->getBase()); 3775 } 3776 3777 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo); 3778 3779 if (getLangOpts().ObjC && 3780 getLangOpts().getGC() != LangOptions::NonGC) { 3781 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 3782 setObjCGCLValueClass(getContext(), E, LV); 3783 } 3784 return LV; 3785 } 3786 3787 LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) { 3788 assert( 3789 !E->isIncomplete() && 3790 "incomplete matrix subscript expressions should be rejected during Sema"); 3791 LValue Base = EmitLValue(E->getBase()); 3792 llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx()); 3793 llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx()); 3794 llvm::Value *NumRows = Builder.getIntN( 3795 RowIdx->getType()->getScalarSizeInBits(), 3796 E->getBase()->getType()->getAs<ConstantMatrixType>()->getNumRows()); 3797 llvm::Value *FinalIdx = 3798 Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx); 3799 return LValue::MakeMatrixElt( 3800 MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx, 3801 E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo()); 3802 } 3803 3804 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, 3805 LValueBaseInfo &BaseInfo, 3806 TBAAAccessInfo &TBAAInfo, 3807 QualType BaseTy, QualType ElTy, 3808 bool IsLowerBound) { 3809 LValue BaseLVal; 3810 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) { 3811 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound); 3812 if (BaseTy->isArrayType()) { 3813 Address Addr = BaseLVal.getAddress(CGF); 3814 BaseInfo = BaseLVal.getBaseInfo(); 3815 3816 // If the array type was an incomplete type, we need to make sure 3817 // the decay ends up being the right type. 3818 llvm::Type *NewTy = CGF.ConvertType(BaseTy); 3819 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy); 3820 3821 // Note that VLA pointers are always decayed, so we don't need to do 3822 // anything here. 3823 if (!BaseTy->isVariableArrayType()) { 3824 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 3825 "Expected pointer to array"); 3826 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay"); 3827 } 3828 3829 return CGF.Builder.CreateElementBitCast(Addr, 3830 CGF.ConvertTypeForMem(ElTy)); 3831 } 3832 LValueBaseInfo TypeBaseInfo; 3833 TBAAAccessInfo TypeTBAAInfo; 3834 CharUnits Align = 3835 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo); 3836 BaseInfo.mergeForCast(TypeBaseInfo); 3837 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo); 3838 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)), Align); 3839 } 3840 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo); 3841 } 3842 3843 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3844 bool IsLowerBound) { 3845 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase()); 3846 QualType ResultExprTy; 3847 if (auto *AT = getContext().getAsArrayType(BaseTy)) 3848 ResultExprTy = AT->getElementType(); 3849 else 3850 ResultExprTy = BaseTy->getPointeeType(); 3851 llvm::Value *Idx = nullptr; 3852 if (IsLowerBound || E->getColonLocFirst().isInvalid()) { 3853 // Requesting lower bound or upper bound, but without provided length and 3854 // without ':' symbol for the default length -> length = 1. 3855 // Idx = LowerBound ?: 0; 3856 if (auto *LowerBound = E->getLowerBound()) { 3857 Idx = Builder.CreateIntCast( 3858 EmitScalarExpr(LowerBound), IntPtrTy, 3859 LowerBound->getType()->hasSignedIntegerRepresentation()); 3860 } else 3861 Idx = llvm::ConstantInt::getNullValue(IntPtrTy); 3862 } else { 3863 // Try to emit length or lower bound as constant. If this is possible, 1 3864 // is subtracted from constant length or lower bound. Otherwise, emit LLVM 3865 // IR (LB + Len) - 1. 3866 auto &C = CGM.getContext(); 3867 auto *Length = E->getLength(); 3868 llvm::APSInt ConstLength; 3869 if (Length) { 3870 // Idx = LowerBound + Length - 1; 3871 if (Length->isIntegerConstantExpr(ConstLength, C)) { 3872 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3873 Length = nullptr; 3874 } 3875 auto *LowerBound = E->getLowerBound(); 3876 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false); 3877 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) { 3878 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits); 3879 LowerBound = nullptr; 3880 } 3881 if (!Length) 3882 --ConstLength; 3883 else if (!LowerBound) 3884 --ConstLowerBound; 3885 3886 if (Length || LowerBound) { 3887 auto *LowerBoundVal = 3888 LowerBound 3889 ? Builder.CreateIntCast( 3890 EmitScalarExpr(LowerBound), IntPtrTy, 3891 LowerBound->getType()->hasSignedIntegerRepresentation()) 3892 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound); 3893 auto *LengthVal = 3894 Length 3895 ? Builder.CreateIntCast( 3896 EmitScalarExpr(Length), IntPtrTy, 3897 Length->getType()->hasSignedIntegerRepresentation()) 3898 : llvm::ConstantInt::get(IntPtrTy, ConstLength); 3899 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len", 3900 /*HasNUW=*/false, 3901 !getLangOpts().isSignedOverflowDefined()); 3902 if (Length && LowerBound) { 3903 Idx = Builder.CreateSub( 3904 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1", 3905 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3906 } 3907 } else 3908 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound); 3909 } else { 3910 // Idx = ArraySize - 1; 3911 QualType ArrayTy = BaseTy->isPointerType() 3912 ? E->getBase()->IgnoreParenImpCasts()->getType() 3913 : BaseTy; 3914 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) { 3915 Length = VAT->getSizeExpr(); 3916 if (Length->isIntegerConstantExpr(ConstLength, C)) 3917 Length = nullptr; 3918 } else { 3919 auto *CAT = C.getAsConstantArrayType(ArrayTy); 3920 ConstLength = CAT->getSize(); 3921 } 3922 if (Length) { 3923 auto *LengthVal = Builder.CreateIntCast( 3924 EmitScalarExpr(Length), IntPtrTy, 3925 Length->getType()->hasSignedIntegerRepresentation()); 3926 Idx = Builder.CreateSub( 3927 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1", 3928 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3929 } else { 3930 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3931 --ConstLength; 3932 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength); 3933 } 3934 } 3935 } 3936 assert(Idx); 3937 3938 Address EltPtr = Address::invalid(); 3939 LValueBaseInfo BaseInfo; 3940 TBAAAccessInfo TBAAInfo; 3941 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) { 3942 // The base must be a pointer, which is not an aggregate. Emit 3943 // it. It needs to be emitted first in case it's what captures 3944 // the VLA bounds. 3945 Address Base = 3946 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, 3947 BaseTy, VLA->getElementType(), IsLowerBound); 3948 // The element count here is the total number of non-VLA elements. 3949 llvm::Value *NumElements = getVLASize(VLA).NumElts; 3950 3951 // Effectively, the multiply by the VLA size is part of the GEP. 3952 // GEP indexes are signed, and scaling an index isn't permitted to 3953 // signed-overflow, so we use the same semantics for our explicit 3954 // multiply. We suppress this if overflow is not undefined behavior. 3955 if (getLangOpts().isSignedOverflowDefined()) 3956 Idx = Builder.CreateMul(Idx, NumElements); 3957 else 3958 Idx = Builder.CreateNSWMul(Idx, NumElements); 3959 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(), 3960 !getLangOpts().isSignedOverflowDefined(), 3961 /*signedIndices=*/false, E->getExprLoc()); 3962 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3963 // If this is A[i] where A is an array, the frontend will have decayed the 3964 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3965 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3966 // "gep x, i" here. Emit one "gep A, 0, i". 3967 assert(Array->getType()->isArrayType() && 3968 "Array to pointer decay must have array source type!"); 3969 LValue ArrayLV; 3970 // For simple multidimensional array indexing, set the 'accessed' flag for 3971 // better bounds-checking of the base expression. 3972 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3973 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3974 else 3975 ArrayLV = EmitLValue(Array); 3976 3977 // Propagate the alignment from the array itself to the result. 3978 EltPtr = emitArraySubscriptGEP( 3979 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx}, 3980 ResultExprTy, !getLangOpts().isSignedOverflowDefined(), 3981 /*signedIndices=*/false, E->getExprLoc()); 3982 BaseInfo = ArrayLV.getBaseInfo(); 3983 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy); 3984 } else { 3985 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, 3986 TBAAInfo, BaseTy, ResultExprTy, 3987 IsLowerBound); 3988 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy, 3989 !getLangOpts().isSignedOverflowDefined(), 3990 /*signedIndices=*/false, E->getExprLoc()); 3991 } 3992 3993 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo); 3994 } 3995 3996 LValue CodeGenFunction:: 3997 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 3998 // Emit the base vector as an l-value. 3999 LValue Base; 4000 4001 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 4002 if (E->isArrow()) { 4003 // If it is a pointer to a vector, emit the address and form an lvalue with 4004 // it. 4005 LValueBaseInfo BaseInfo; 4006 TBAAAccessInfo TBAAInfo; 4007 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo); 4008 const auto *PT = E->getBase()->getType()->castAs<PointerType>(); 4009 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo); 4010 Base.getQuals().removeObjCGCAttr(); 4011 } else if (E->getBase()->isGLValue()) { 4012 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 4013 // emit the base as an lvalue. 4014 assert(E->getBase()->getType()->isVectorType()); 4015 Base = EmitLValue(E->getBase()); 4016 } else { 4017 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 4018 assert(E->getBase()->getType()->isVectorType() && 4019 "Result must be a vector"); 4020 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 4021 4022 // Store the vector to memory (because LValue wants an address). 4023 Address VecMem = CreateMemTemp(E->getBase()->getType()); 4024 Builder.CreateStore(Vec, VecMem); 4025 Base = MakeAddrLValue(VecMem, E->getBase()->getType(), 4026 AlignmentSource::Decl); 4027 } 4028 4029 QualType type = 4030 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers()); 4031 4032 // Encode the element access list into a vector of unsigned indices. 4033 SmallVector<uint32_t, 4> Indices; 4034 E->getEncodedElementAccess(Indices); 4035 4036 if (Base.isSimple()) { 4037 llvm::Constant *CV = 4038 llvm::ConstantDataVector::get(getLLVMContext(), Indices); 4039 return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type, 4040 Base.getBaseInfo(), TBAAAccessInfo()); 4041 } 4042 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 4043 4044 llvm::Constant *BaseElts = Base.getExtVectorElts(); 4045 SmallVector<llvm::Constant *, 4> CElts; 4046 4047 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 4048 CElts.push_back(BaseElts->getAggregateElement(Indices[i])); 4049 llvm::Constant *CV = llvm::ConstantVector::get(CElts); 4050 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type, 4051 Base.getBaseInfo(), TBAAAccessInfo()); 4052 } 4053 4054 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 4055 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) { 4056 EmitIgnoredExpr(E->getBase()); 4057 return EmitDeclRefLValue(DRE); 4058 } 4059 4060 Expr *BaseExpr = E->getBase(); 4061 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 4062 LValue BaseLV; 4063 if (E->isArrow()) { 4064 LValueBaseInfo BaseInfo; 4065 TBAAAccessInfo TBAAInfo; 4066 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo); 4067 QualType PtrTy = BaseExpr->getType()->getPointeeType(); 4068 SanitizerSet SkippedChecks; 4069 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr); 4070 if (IsBaseCXXThis) 4071 SkippedChecks.set(SanitizerKind::Alignment, true); 4072 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr)) 4073 SkippedChecks.set(SanitizerKind::Null, true); 4074 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy, 4075 /*Alignment=*/CharUnits::Zero(), SkippedChecks); 4076 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo); 4077 } else 4078 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess); 4079 4080 NamedDecl *ND = E->getMemberDecl(); 4081 if (auto *Field = dyn_cast<FieldDecl>(ND)) { 4082 LValue LV = EmitLValueForField(BaseLV, Field); 4083 setObjCGCLValueClass(getContext(), E, LV); 4084 if (getLangOpts().OpenMP) { 4085 // If the member was explicitly marked as nontemporal, mark it as 4086 // nontemporal. If the base lvalue is marked as nontemporal, mark access 4087 // to children as nontemporal too. 4088 if ((IsWrappedCXXThis(BaseExpr) && 4089 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) || 4090 BaseLV.isNontemporal()) 4091 LV.setNontemporal(/*Value=*/true); 4092 } 4093 return LV; 4094 } 4095 4096 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 4097 return EmitFunctionDeclLValue(*this, E, FD); 4098 4099 llvm_unreachable("Unhandled member declaration!"); 4100 } 4101 4102 /// Given that we are currently emitting a lambda, emit an l-value for 4103 /// one of its members. 4104 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) { 4105 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda()); 4106 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent()); 4107 QualType LambdaTagType = 4108 getContext().getTagDeclType(Field->getParent()); 4109 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType); 4110 return EmitLValueForField(LambdaLV, Field); 4111 } 4112 4113 /// Get the field index in the debug info. The debug info structure/union 4114 /// will ignore the unnamed bitfields. 4115 unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec, 4116 unsigned FieldIndex) { 4117 unsigned I = 0, Skipped = 0; 4118 4119 for (auto F : Rec->getDefinition()->fields()) { 4120 if (I == FieldIndex) 4121 break; 4122 if (F->isUnnamedBitfield()) 4123 Skipped++; 4124 I++; 4125 } 4126 4127 return FieldIndex - Skipped; 4128 } 4129 4130 /// Get the address of a zero-sized field within a record. The resulting 4131 /// address doesn't necessarily have the right type. 4132 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base, 4133 const FieldDecl *Field) { 4134 CharUnits Offset = CGF.getContext().toCharUnitsFromBits( 4135 CGF.getContext().getFieldOffset(Field)); 4136 if (Offset.isZero()) 4137 return Base; 4138 Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty); 4139 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset); 4140 } 4141 4142 /// Drill down to the storage of a field without walking into 4143 /// reference types. 4144 /// 4145 /// The resulting address doesn't necessarily have the right type. 4146 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, 4147 const FieldDecl *field) { 4148 if (field->isZeroSize(CGF.getContext())) 4149 return emitAddrOfZeroSizeField(CGF, base, field); 4150 4151 const RecordDecl *rec = field->getParent(); 4152 4153 unsigned idx = 4154 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 4155 4156 return CGF.Builder.CreateStructGEP(base, idx, field->getName()); 4157 } 4158 4159 static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, 4160 Address addr, const FieldDecl *field) { 4161 const RecordDecl *rec = field->getParent(); 4162 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType( 4163 base.getType(), rec->getLocation()); 4164 4165 unsigned idx = 4166 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 4167 4168 return CGF.Builder.CreatePreserveStructAccessIndex( 4169 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo); 4170 } 4171 4172 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) { 4173 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl(); 4174 if (!RD) 4175 return false; 4176 4177 if (RD->isDynamicClass()) 4178 return true; 4179 4180 for (const auto &Base : RD->bases()) 4181 if (hasAnyVptr(Base.getType(), Context)) 4182 return true; 4183 4184 for (const FieldDecl *Field : RD->fields()) 4185 if (hasAnyVptr(Field->getType(), Context)) 4186 return true; 4187 4188 return false; 4189 } 4190 4191 LValue CodeGenFunction::EmitLValueForField(LValue base, 4192 const FieldDecl *field) { 4193 LValueBaseInfo BaseInfo = base.getBaseInfo(); 4194 4195 if (field->isBitField()) { 4196 const CGRecordLayout &RL = 4197 CGM.getTypes().getCGRecordLayout(field->getParent()); 4198 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field); 4199 Address Addr = base.getAddress(*this); 4200 unsigned Idx = RL.getLLVMFieldNo(field); 4201 const RecordDecl *rec = field->getParent(); 4202 if (!IsInPreservedAIRegion && 4203 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) { 4204 if (Idx != 0) 4205 // For structs, we GEP to the field that the record layout suggests. 4206 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName()); 4207 } else { 4208 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType( 4209 getContext().getRecordType(rec), rec->getLocation()); 4210 Addr = Builder.CreatePreserveStructAccessIndex(Addr, Idx, 4211 getDebugInfoFIndex(rec, field->getFieldIndex()), 4212 DbgInfo); 4213 } 4214 4215 // Get the access type. 4216 llvm::Type *FieldIntTy = 4217 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize); 4218 if (Addr.getElementType() != FieldIntTy) 4219 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy); 4220 4221 QualType fieldType = 4222 field->getType().withCVRQualifiers(base.getVRQualifiers()); 4223 // TODO: Support TBAA for bit fields. 4224 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource()); 4225 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo, 4226 TBAAAccessInfo()); 4227 } 4228 4229 // Fields of may-alias structures are may-alias themselves. 4230 // FIXME: this should get propagated down through anonymous structs 4231 // and unions. 4232 QualType FieldType = field->getType(); 4233 const RecordDecl *rec = field->getParent(); 4234 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource(); 4235 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource)); 4236 TBAAAccessInfo FieldTBAAInfo; 4237 if (base.getTBAAInfo().isMayAlias() || 4238 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) { 4239 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo(); 4240 } else if (rec->isUnion()) { 4241 // TODO: Support TBAA for unions. 4242 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo(); 4243 } else { 4244 // If no base type been assigned for the base access, then try to generate 4245 // one for this base lvalue. 4246 FieldTBAAInfo = base.getTBAAInfo(); 4247 if (!FieldTBAAInfo.BaseType) { 4248 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType()); 4249 assert(!FieldTBAAInfo.Offset && 4250 "Nonzero offset for an access with no base type!"); 4251 } 4252 4253 // Adjust offset to be relative to the base type. 4254 const ASTRecordLayout &Layout = 4255 getContext().getASTRecordLayout(field->getParent()); 4256 unsigned CharWidth = getContext().getCharWidth(); 4257 if (FieldTBAAInfo.BaseType) 4258 FieldTBAAInfo.Offset += 4259 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth; 4260 4261 // Update the final access type and size. 4262 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType); 4263 FieldTBAAInfo.Size = 4264 getContext().getTypeSizeInChars(FieldType).getQuantity(); 4265 } 4266 4267 Address addr = base.getAddress(*this); 4268 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) { 4269 if (CGM.getCodeGenOpts().StrictVTablePointers && 4270 ClassDef->isDynamicClass()) { 4271 // Getting to any field of dynamic object requires stripping dynamic 4272 // information provided by invariant.group. This is because accessing 4273 // fields may leak the real address of dynamic object, which could result 4274 // in miscompilation when leaked pointer would be compared. 4275 auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer()); 4276 addr = Address(stripped, addr.getAlignment()); 4277 } 4278 } 4279 4280 unsigned RecordCVR = base.getVRQualifiers(); 4281 if (rec->isUnion()) { 4282 // For unions, there is no pointer adjustment. 4283 if (CGM.getCodeGenOpts().StrictVTablePointers && 4284 hasAnyVptr(FieldType, getContext())) 4285 // Because unions can easily skip invariant.barriers, we need to add 4286 // a barrier every time CXXRecord field with vptr is referenced. 4287 addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()), 4288 addr.getAlignment()); 4289 4290 if (IsInPreservedAIRegion || 4291 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) { 4292 // Remember the original union field index 4293 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(), 4294 rec->getLocation()); 4295 addr = Address( 4296 Builder.CreatePreserveUnionAccessIndex( 4297 addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo), 4298 addr.getAlignment()); 4299 } 4300 4301 if (FieldType->isReferenceType()) 4302 addr = Builder.CreateElementBitCast( 4303 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName()); 4304 } else { 4305 if (!IsInPreservedAIRegion && 4306 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) 4307 // For structs, we GEP to the field that the record layout suggests. 4308 addr = emitAddrOfFieldStorage(*this, addr, field); 4309 else 4310 // Remember the original struct field index 4311 addr = emitPreserveStructAccess(*this, base, addr, field); 4312 } 4313 4314 // If this is a reference field, load the reference right now. 4315 if (FieldType->isReferenceType()) { 4316 LValue RefLVal = 4317 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo); 4318 if (RecordCVR & Qualifiers::Volatile) 4319 RefLVal.getQuals().addVolatile(); 4320 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo); 4321 4322 // Qualifiers on the struct don't apply to the referencee. 4323 RecordCVR = 0; 4324 FieldType = FieldType->getPointeeType(); 4325 } 4326 4327 // Make sure that the address is pointing to the right type. This is critical 4328 // for both unions and structs. A union needs a bitcast, a struct element 4329 // will need a bitcast if the LLVM type laid out doesn't match the desired 4330 // type. 4331 addr = Builder.CreateElementBitCast( 4332 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName()); 4333 4334 if (field->hasAttr<AnnotateAttr>()) 4335 addr = EmitFieldAnnotations(field, addr); 4336 4337 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo); 4338 LV.getQuals().addCVRQualifiers(RecordCVR); 4339 4340 // __weak attribute on a field is ignored. 4341 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 4342 LV.getQuals().removeObjCGCAttr(); 4343 4344 return LV; 4345 } 4346 4347 LValue 4348 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base, 4349 const FieldDecl *Field) { 4350 QualType FieldType = Field->getType(); 4351 4352 if (!FieldType->isReferenceType()) 4353 return EmitLValueForField(Base, Field); 4354 4355 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field); 4356 4357 // Make sure that the address is pointing to the right type. 4358 llvm::Type *llvmType = ConvertTypeForMem(FieldType); 4359 V = Builder.CreateElementBitCast(V, llvmType, Field->getName()); 4360 4361 // TODO: Generate TBAA information that describes this access as a structure 4362 // member access and not just an access to an object of the field's type. This 4363 // should be similar to what we do in EmitLValueForField(). 4364 LValueBaseInfo BaseInfo = Base.getBaseInfo(); 4365 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource(); 4366 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource)); 4367 return MakeAddrLValue(V, FieldType, FieldBaseInfo, 4368 CGM.getTBAAInfoForSubobject(Base, FieldType)); 4369 } 4370 4371 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 4372 if (E->isFileScope()) { 4373 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E); 4374 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl); 4375 } 4376 if (E->getType()->isVariablyModifiedType()) 4377 // make sure to emit the VLA size. 4378 EmitVariablyModifiedType(E->getType()); 4379 4380 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 4381 const Expr *InitExpr = E->getInitializer(); 4382 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl); 4383 4384 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(), 4385 /*Init*/ true); 4386 4387 // Block-scope compound literals are destroyed at the end of the enclosing 4388 // scope in C. 4389 if (!getLangOpts().CPlusPlus) 4390 if (QualType::DestructionKind DtorKind = E->getType().isDestructedType()) 4391 pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr, 4392 E->getType(), getDestroyer(DtorKind), 4393 DtorKind & EHCleanup); 4394 4395 return Result; 4396 } 4397 4398 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { 4399 if (!E->isGLValue()) 4400 // Initializing an aggregate temporary in C++11: T{...}. 4401 return EmitAggExprToLValue(E); 4402 4403 // An lvalue initializer list must be initializing a reference. 4404 assert(E->isTransparent() && "non-transparent glvalue init list"); 4405 return EmitLValue(E->getInit(0)); 4406 } 4407 4408 /// Emit the operand of a glvalue conditional operator. This is either a glvalue 4409 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no 4410 /// LValue is returned and the current block has been terminated. 4411 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, 4412 const Expr *Operand) { 4413 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) { 4414 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false); 4415 return None; 4416 } 4417 4418 return CGF.EmitLValue(Operand); 4419 } 4420 4421 LValue CodeGenFunction:: 4422 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) { 4423 if (!expr->isGLValue()) { 4424 // ?: here should be an aggregate. 4425 assert(hasAggregateEvaluationKind(expr->getType()) && 4426 "Unexpected conditional operator!"); 4427 return EmitAggExprToLValue(expr); 4428 } 4429 4430 OpaqueValueMapping binding(*this, expr); 4431 4432 const Expr *condExpr = expr->getCond(); 4433 bool CondExprBool; 4434 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 4435 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr(); 4436 if (!CondExprBool) std::swap(live, dead); 4437 4438 if (!ContainsLabel(dead)) { 4439 // If the true case is live, we need to track its region. 4440 if (CondExprBool) 4441 incrementProfileCounter(expr); 4442 // If a throw expression we emit it and return an undefined lvalue 4443 // because it can't be used. 4444 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) { 4445 EmitCXXThrowExpr(ThrowExpr); 4446 llvm::Type *Ty = 4447 llvm::PointerType::getUnqual(ConvertType(dead->getType())); 4448 return MakeAddrLValue( 4449 Address(llvm::UndefValue::get(Ty), CharUnits::One()), 4450 dead->getType()); 4451 } 4452 return EmitLValue(live); 4453 } 4454 } 4455 4456 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true"); 4457 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false"); 4458 llvm::BasicBlock *contBlock = createBasicBlock("cond.end"); 4459 4460 ConditionalEvaluation eval(*this); 4461 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr)); 4462 4463 // Any temporaries created here are conditional. 4464 EmitBlock(lhsBlock); 4465 incrementProfileCounter(expr); 4466 eval.begin(*this); 4467 Optional<LValue> lhs = 4468 EmitLValueOrThrowExpression(*this, expr->getTrueExpr()); 4469 eval.end(*this); 4470 4471 if (lhs && !lhs->isSimple()) 4472 return EmitUnsupportedLValue(expr, "conditional operator"); 4473 4474 lhsBlock = Builder.GetInsertBlock(); 4475 if (lhs) 4476 Builder.CreateBr(contBlock); 4477 4478 // Any temporaries created here are conditional. 4479 EmitBlock(rhsBlock); 4480 eval.begin(*this); 4481 Optional<LValue> rhs = 4482 EmitLValueOrThrowExpression(*this, expr->getFalseExpr()); 4483 eval.end(*this); 4484 if (rhs && !rhs->isSimple()) 4485 return EmitUnsupportedLValue(expr, "conditional operator"); 4486 rhsBlock = Builder.GetInsertBlock(); 4487 4488 EmitBlock(contBlock); 4489 4490 if (lhs && rhs) { 4491 llvm::PHINode *phi = 4492 Builder.CreatePHI(lhs->getPointer(*this)->getType(), 2, "cond-lvalue"); 4493 phi->addIncoming(lhs->getPointer(*this), lhsBlock); 4494 phi->addIncoming(rhs->getPointer(*this), rhsBlock); 4495 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment())); 4496 AlignmentSource alignSource = 4497 std::max(lhs->getBaseInfo().getAlignmentSource(), 4498 rhs->getBaseInfo().getAlignmentSource()); 4499 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator( 4500 lhs->getTBAAInfo(), rhs->getTBAAInfo()); 4501 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource), 4502 TBAAInfo); 4503 } else { 4504 assert((lhs || rhs) && 4505 "both operands of glvalue conditional are throw-expressions?"); 4506 return lhs ? *lhs : *rhs; 4507 } 4508 } 4509 4510 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference 4511 /// type. If the cast is to a reference, we can have the usual lvalue result, 4512 /// otherwise if a cast is needed by the code generator in an lvalue context, 4513 /// then it must mean that we need the address of an aggregate in order to 4514 /// access one of its members. This can happen for all the reasons that casts 4515 /// are permitted with aggregate result, including noop aggregate casts, and 4516 /// cast from scalar to union. 4517 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 4518 switch (E->getCastKind()) { 4519 case CK_ToVoid: 4520 case CK_BitCast: 4521 case CK_LValueToRValueBitCast: 4522 case CK_ArrayToPointerDecay: 4523 case CK_FunctionToPointerDecay: 4524 case CK_NullToMemberPointer: 4525 case CK_NullToPointer: 4526 case CK_IntegralToPointer: 4527 case CK_PointerToIntegral: 4528 case CK_PointerToBoolean: 4529 case CK_VectorSplat: 4530 case CK_IntegralCast: 4531 case CK_BooleanToSignedIntegral: 4532 case CK_IntegralToBoolean: 4533 case CK_IntegralToFloating: 4534 case CK_FloatingToIntegral: 4535 case CK_FloatingToBoolean: 4536 case CK_FloatingCast: 4537 case CK_FloatingRealToComplex: 4538 case CK_FloatingComplexToReal: 4539 case CK_FloatingComplexToBoolean: 4540 case CK_FloatingComplexCast: 4541 case CK_FloatingComplexToIntegralComplex: 4542 case CK_IntegralRealToComplex: 4543 case CK_IntegralComplexToReal: 4544 case CK_IntegralComplexToBoolean: 4545 case CK_IntegralComplexCast: 4546 case CK_IntegralComplexToFloatingComplex: 4547 case CK_DerivedToBaseMemberPointer: 4548 case CK_BaseToDerivedMemberPointer: 4549 case CK_MemberPointerToBoolean: 4550 case CK_ReinterpretMemberPointer: 4551 case CK_AnyPointerToBlockPointerCast: 4552 case CK_ARCProduceObject: 4553 case CK_ARCConsumeObject: 4554 case CK_ARCReclaimReturnedObject: 4555 case CK_ARCExtendBlockObject: 4556 case CK_CopyAndAutoreleaseBlockObject: 4557 case CK_IntToOCLSampler: 4558 case CK_FixedPointCast: 4559 case CK_FixedPointToBoolean: 4560 case CK_FixedPointToIntegral: 4561 case CK_IntegralToFixedPoint: 4562 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 4563 4564 case CK_Dependent: 4565 llvm_unreachable("dependent cast kind in IR gen!"); 4566 4567 case CK_BuiltinFnToFnPtr: 4568 llvm_unreachable("builtin functions are handled elsewhere"); 4569 4570 // These are never l-values; just use the aggregate emission code. 4571 case CK_NonAtomicToAtomic: 4572 case CK_AtomicToNonAtomic: 4573 return EmitAggExprToLValue(E); 4574 4575 case CK_Dynamic: { 4576 LValue LV = EmitLValue(E->getSubExpr()); 4577 Address V = LV.getAddress(*this); 4578 const auto *DCE = cast<CXXDynamicCastExpr>(E); 4579 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 4580 } 4581 4582 case CK_ConstructorConversion: 4583 case CK_UserDefinedConversion: 4584 case CK_CPointerToObjCPointerCast: 4585 case CK_BlockPointerToObjCPointerCast: 4586 case CK_NoOp: 4587 case CK_LValueToRValue: 4588 return EmitLValue(E->getSubExpr()); 4589 4590 case CK_UncheckedDerivedToBase: 4591 case CK_DerivedToBase: { 4592 const auto *DerivedClassTy = 4593 E->getSubExpr()->getType()->castAs<RecordType>(); 4594 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 4595 4596 LValue LV = EmitLValue(E->getSubExpr()); 4597 Address This = LV.getAddress(*this); 4598 4599 // Perform the derived-to-base conversion 4600 Address Base = GetAddressOfBaseClass( 4601 This, DerivedClassDecl, E->path_begin(), E->path_end(), 4602 /*NullCheckValue=*/false, E->getExprLoc()); 4603 4604 // TODO: Support accesses to members of base classes in TBAA. For now, we 4605 // conservatively pretend that the complete object is of the base class 4606 // type. 4607 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(), 4608 CGM.getTBAAInfoForSubobject(LV, E->getType())); 4609 } 4610 case CK_ToUnion: 4611 return EmitAggExprToLValue(E); 4612 case CK_BaseToDerived: { 4613 const auto *DerivedClassTy = E->getType()->castAs<RecordType>(); 4614 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 4615 4616 LValue LV = EmitLValue(E->getSubExpr()); 4617 4618 // Perform the base-to-derived conversion 4619 Address Derived = GetAddressOfDerivedClass( 4620 LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(), 4621 /*NullCheckValue=*/false); 4622 4623 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is 4624 // performed and the object is not of the derived type. 4625 if (sanitizePerformTypeCheck()) 4626 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(), 4627 Derived.getPointer(), E->getType()); 4628 4629 if (SanOpts.has(SanitizerKind::CFIDerivedCast)) 4630 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(), 4631 /*MayBeNull=*/false, CFITCK_DerivedCast, 4632 E->getBeginLoc()); 4633 4634 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(), 4635 CGM.getTBAAInfoForSubobject(LV, E->getType())); 4636 } 4637 case CK_LValueBitCast: { 4638 // This must be a reinterpret_cast (or c-style equivalent). 4639 const auto *CE = cast<ExplicitCastExpr>(E); 4640 4641 CGM.EmitExplicitCastExprType(CE, this); 4642 LValue LV = EmitLValue(E->getSubExpr()); 4643 Address V = Builder.CreateBitCast(LV.getAddress(*this), 4644 ConvertType(CE->getTypeAsWritten())); 4645 4646 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) 4647 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(), 4648 /*MayBeNull=*/false, CFITCK_UnrelatedCast, 4649 E->getBeginLoc()); 4650 4651 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(), 4652 CGM.getTBAAInfoForSubobject(LV, E->getType())); 4653 } 4654 case CK_AddressSpaceConversion: { 4655 LValue LV = EmitLValue(E->getSubExpr()); 4656 QualType DestTy = getContext().getPointerType(E->getType()); 4657 llvm::Value *V = getTargetHooks().performAddrSpaceCast( 4658 *this, LV.getPointer(*this), 4659 E->getSubExpr()->getType().getAddressSpace(), 4660 E->getType().getAddressSpace(), ConvertType(DestTy)); 4661 return MakeAddrLValue(Address(V, LV.getAddress(*this).getAlignment()), 4662 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo()); 4663 } 4664 case CK_ObjCObjectLValueCast: { 4665 LValue LV = EmitLValue(E->getSubExpr()); 4666 Address V = Builder.CreateElementBitCast(LV.getAddress(*this), 4667 ConvertType(E->getType())); 4668 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(), 4669 CGM.getTBAAInfoForSubobject(LV, E->getType())); 4670 } 4671 case CK_ZeroToOCLOpaqueType: 4672 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid"); 4673 } 4674 4675 llvm_unreachable("Unhandled lvalue cast kind?"); 4676 } 4677 4678 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 4679 assert(OpaqueValueMappingData::shouldBindAsLValue(e)); 4680 return getOrCreateOpaqueLValueMapping(e); 4681 } 4682 4683 LValue 4684 CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) { 4685 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 4686 4687 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 4688 it = OpaqueLValues.find(e); 4689 4690 if (it != OpaqueLValues.end()) 4691 return it->second; 4692 4693 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted"); 4694 return EmitLValue(e->getSourceExpr()); 4695 } 4696 4697 RValue 4698 CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) { 4699 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 4700 4701 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 4702 it = OpaqueRValues.find(e); 4703 4704 if (it != OpaqueRValues.end()) 4705 return it->second; 4706 4707 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted"); 4708 return EmitAnyExpr(e->getSourceExpr()); 4709 } 4710 4711 RValue CodeGenFunction::EmitRValueForField(LValue LV, 4712 const FieldDecl *FD, 4713 SourceLocation Loc) { 4714 QualType FT = FD->getType(); 4715 LValue FieldLV = EmitLValueForField(LV, FD); 4716 switch (getEvaluationKind(FT)) { 4717 case TEK_Complex: 4718 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc)); 4719 case TEK_Aggregate: 4720 return FieldLV.asAggregateRValue(*this); 4721 case TEK_Scalar: 4722 // This routine is used to load fields one-by-one to perform a copy, so 4723 // don't load reference fields. 4724 if (FD->getType()->isReferenceType()) 4725 return RValue::get(FieldLV.getPointer(*this)); 4726 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a 4727 // primitive load. 4728 if (FieldLV.isBitField()) 4729 return EmitLoadOfLValue(FieldLV, Loc); 4730 return RValue::get(EmitLoadOfScalar(FieldLV, Loc)); 4731 } 4732 llvm_unreachable("bad evaluation kind"); 4733 } 4734 4735 //===--------------------------------------------------------------------===// 4736 // Expression Emission 4737 //===--------------------------------------------------------------------===// 4738 4739 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 4740 ReturnValueSlot ReturnValue) { 4741 // Builtins never have block type. 4742 if (E->getCallee()->getType()->isBlockPointerType()) 4743 return EmitBlockCallExpr(E, ReturnValue); 4744 4745 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E)) 4746 return EmitCXXMemberCallExpr(CE, ReturnValue); 4747 4748 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E)) 4749 return EmitCUDAKernelCallExpr(CE, ReturnValue); 4750 4751 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E)) 4752 if (const CXXMethodDecl *MD = 4753 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) 4754 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 4755 4756 CGCallee callee = EmitCallee(E->getCallee()); 4757 4758 if (callee.isBuiltin()) { 4759 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(), 4760 E, ReturnValue); 4761 } 4762 4763 if (callee.isPseudoDestructor()) { 4764 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr()); 4765 } 4766 4767 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue); 4768 } 4769 4770 /// Emit a CallExpr without considering whether it might be a subclass. 4771 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E, 4772 ReturnValueSlot ReturnValue) { 4773 CGCallee Callee = EmitCallee(E->getCallee()); 4774 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue); 4775 } 4776 4777 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) { 4778 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 4779 4780 if (auto builtinID = FD->getBuiltinID()) { 4781 // Replaceable builtin provide their own implementation of a builtin. Unless 4782 // we are in the builtin implementation itself, don't call the actual 4783 // builtin. If we are in the builtin implementation, avoid trivial infinite 4784 // recursion. 4785 if (!FD->isInlineBuiltinDeclaration() || 4786 CGF.CurFn->getName() == FD->getName()) 4787 return CGCallee::forBuiltin(builtinID, FD); 4788 } 4789 4790 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, GD); 4791 return CGCallee::forDirect(calleePtr, GD); 4792 } 4793 4794 CGCallee CodeGenFunction::EmitCallee(const Expr *E) { 4795 E = E->IgnoreParens(); 4796 4797 // Look through function-to-pointer decay. 4798 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) { 4799 if (ICE->getCastKind() == CK_FunctionToPointerDecay || 4800 ICE->getCastKind() == CK_BuiltinFnToFnPtr) { 4801 return EmitCallee(ICE->getSubExpr()); 4802 } 4803 4804 // Resolve direct calls. 4805 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) { 4806 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 4807 return EmitDirectCallee(*this, FD); 4808 } 4809 } else if (auto ME = dyn_cast<MemberExpr>(E)) { 4810 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) { 4811 EmitIgnoredExpr(ME->getBase()); 4812 return EmitDirectCallee(*this, FD); 4813 } 4814 4815 // Look through template substitutions. 4816 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 4817 return EmitCallee(NTTP->getReplacement()); 4818 4819 // Treat pseudo-destructor calls differently. 4820 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) { 4821 return CGCallee::forPseudoDestructor(PDE); 4822 } 4823 4824 // Otherwise, we have an indirect reference. 4825 llvm::Value *calleePtr; 4826 QualType functionType; 4827 if (auto ptrType = E->getType()->getAs<PointerType>()) { 4828 calleePtr = EmitScalarExpr(E); 4829 functionType = ptrType->getPointeeType(); 4830 } else { 4831 functionType = E->getType(); 4832 calleePtr = EmitLValue(E).getPointer(*this); 4833 } 4834 assert(functionType->isFunctionType()); 4835 4836 GlobalDecl GD; 4837 if (const auto *VD = 4838 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee())) 4839 GD = GlobalDecl(VD); 4840 4841 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD); 4842 CGCallee callee(calleeInfo, calleePtr); 4843 return callee; 4844 } 4845 4846 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 4847 // Comma expressions just emit their LHS then their RHS as an l-value. 4848 if (E->getOpcode() == BO_Comma) { 4849 EmitIgnoredExpr(E->getLHS()); 4850 EnsureInsertPoint(); 4851 return EmitLValue(E->getRHS()); 4852 } 4853 4854 if (E->getOpcode() == BO_PtrMemD || 4855 E->getOpcode() == BO_PtrMemI) 4856 return EmitPointerToDataMemberBinaryExpr(E); 4857 4858 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 4859 4860 // Note that in all of these cases, __block variables need the RHS 4861 // evaluated first just in case the variable gets moved by the RHS. 4862 4863 switch (getEvaluationKind(E->getType())) { 4864 case TEK_Scalar: { 4865 switch (E->getLHS()->getType().getObjCLifetime()) { 4866 case Qualifiers::OCL_Strong: 4867 return EmitARCStoreStrong(E, /*ignored*/ false).first; 4868 4869 case Qualifiers::OCL_Autoreleasing: 4870 return EmitARCStoreAutoreleasing(E).first; 4871 4872 // No reason to do any of these differently. 4873 case Qualifiers::OCL_None: 4874 case Qualifiers::OCL_ExplicitNone: 4875 case Qualifiers::OCL_Weak: 4876 break; 4877 } 4878 4879 RValue RV = EmitAnyExpr(E->getRHS()); 4880 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); 4881 if (RV.isScalar()) 4882 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc()); 4883 EmitStoreThroughLValue(RV, LV); 4884 if (getLangOpts().OpenMP) 4885 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this, 4886 E->getLHS()); 4887 return LV; 4888 } 4889 4890 case TEK_Complex: 4891 return EmitComplexAssignmentLValue(E); 4892 4893 case TEK_Aggregate: 4894 return EmitAggExprToLValue(E); 4895 } 4896 llvm_unreachable("bad evaluation kind"); 4897 } 4898 4899 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 4900 RValue RV = EmitCallExpr(E); 4901 4902 if (!RV.isScalar()) 4903 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4904 AlignmentSource::Decl); 4905 4906 assert(E->getCallReturnType(getContext())->isReferenceType() && 4907 "Can't have a scalar return unless the return type is a " 4908 "reference type!"); 4909 4910 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 4911 } 4912 4913 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 4914 // FIXME: This shouldn't require another copy. 4915 return EmitAggExprToLValue(E); 4916 } 4917 4918 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 4919 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 4920 && "binding l-value to type which needs a temporary"); 4921 AggValueSlot Slot = CreateAggTemp(E->getType()); 4922 EmitCXXConstructExpr(E, Slot); 4923 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl); 4924 } 4925 4926 LValue 4927 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 4928 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 4929 } 4930 4931 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) { 4932 return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()), 4933 ConvertType(E->getType())); 4934 } 4935 4936 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) { 4937 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(), 4938 AlignmentSource::Decl); 4939 } 4940 4941 LValue 4942 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 4943 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 4944 Slot.setExternallyDestructed(); 4945 EmitAggExpr(E->getSubExpr(), Slot); 4946 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress()); 4947 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl); 4948 } 4949 4950 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 4951 RValue RV = EmitObjCMessageExpr(E); 4952 4953 if (!RV.isScalar()) 4954 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4955 AlignmentSource::Decl); 4956 4957 assert(E->getMethodDecl()->getReturnType()->isReferenceType() && 4958 "Can't have a scalar return unless the return type is a " 4959 "reference type!"); 4960 4961 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 4962 } 4963 4964 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 4965 Address V = 4966 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector()); 4967 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl); 4968 } 4969 4970 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 4971 const ObjCIvarDecl *Ivar) { 4972 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 4973 } 4974 4975 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 4976 llvm::Value *BaseValue, 4977 const ObjCIvarDecl *Ivar, 4978 unsigned CVRQualifiers) { 4979 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 4980 Ivar, CVRQualifiers); 4981 } 4982 4983 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 4984 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 4985 llvm::Value *BaseValue = nullptr; 4986 const Expr *BaseExpr = E->getBase(); 4987 Qualifiers BaseQuals; 4988 QualType ObjectTy; 4989 if (E->isArrow()) { 4990 BaseValue = EmitScalarExpr(BaseExpr); 4991 ObjectTy = BaseExpr->getType()->getPointeeType(); 4992 BaseQuals = ObjectTy.getQualifiers(); 4993 } else { 4994 LValue BaseLV = EmitLValue(BaseExpr); 4995 BaseValue = BaseLV.getPointer(*this); 4996 ObjectTy = BaseExpr->getType(); 4997 BaseQuals = ObjectTy.getQualifiers(); 4998 } 4999 5000 LValue LV = 5001 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 5002 BaseQuals.getCVRQualifiers()); 5003 setObjCGCLValueClass(getContext(), E, LV); 5004 return LV; 5005 } 5006 5007 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 5008 // Can only get l-value for message expression returning aggregate type 5009 RValue RV = EmitAnyExprToTemp(E); 5010 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 5011 AlignmentSource::Decl); 5012 } 5013 5014 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee, 5015 const CallExpr *E, ReturnValueSlot ReturnValue, 5016 llvm::Value *Chain) { 5017 // Get the actual function type. The callee type will always be a pointer to 5018 // function type or a block pointer type. 5019 assert(CalleeType->isFunctionPointerType() && 5020 "Call must have function pointer type!"); 5021 5022 const Decl *TargetDecl = 5023 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl(); 5024 5025 CalleeType = getContext().getCanonicalType(CalleeType); 5026 5027 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType(); 5028 5029 CGCallee Callee = OrigCallee; 5030 5031 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) && 5032 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 5033 if (llvm::Constant *PrefixSig = 5034 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 5035 SanitizerScope SanScope(this); 5036 // Remove any (C++17) exception specifications, to allow calling e.g. a 5037 // noexcept function through a non-noexcept pointer. 5038 auto ProtoTy = 5039 getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None); 5040 llvm::Constant *FTRTTIConst = 5041 CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true); 5042 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty}; 5043 llvm::StructType *PrefixStructTy = llvm::StructType::get( 5044 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true); 5045 5046 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 5047 5048 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast( 5049 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy)); 5050 llvm::Value *CalleeSigPtr = 5051 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0); 5052 llvm::Value *CalleeSig = 5053 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign()); 5054 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig); 5055 5056 llvm::BasicBlock *Cont = createBasicBlock("cont"); 5057 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck"); 5058 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont); 5059 5060 EmitBlock(TypeCheck); 5061 llvm::Value *CalleeRTTIPtr = 5062 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1); 5063 llvm::Value *CalleeRTTIEncoded = 5064 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign()); 5065 llvm::Value *CalleeRTTI = 5066 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded); 5067 llvm::Value *CalleeRTTIMatch = 5068 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst); 5069 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()), 5070 EmitCheckTypeDescriptor(CalleeType)}; 5071 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function), 5072 SanitizerHandler::FunctionTypeMismatch, StaticData, 5073 {CalleePtr, CalleeRTTI, FTRTTIConst}); 5074 5075 Builder.CreateBr(Cont); 5076 EmitBlock(Cont); 5077 } 5078 } 5079 5080 const auto *FnType = cast<FunctionType>(PointeeType); 5081 5082 // If we are checking indirect calls and this call is indirect, check that the 5083 // function pointer is a member of the bit set for the function type. 5084 if (SanOpts.has(SanitizerKind::CFIICall) && 5085 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 5086 SanitizerScope SanScope(this); 5087 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall); 5088 5089 llvm::Metadata *MD; 5090 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers) 5091 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0)); 5092 else 5093 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)); 5094 5095 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD); 5096 5097 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 5098 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy); 5099 llvm::Value *TypeTest = Builder.CreateCall( 5100 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId}); 5101 5102 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD); 5103 llvm::Constant *StaticData[] = { 5104 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall), 5105 EmitCheckSourceLocation(E->getBeginLoc()), 5106 EmitCheckTypeDescriptor(QualType(FnType, 0)), 5107 }; 5108 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) { 5109 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId, 5110 CastedCallee, StaticData); 5111 } else { 5112 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall), 5113 SanitizerHandler::CFICheckFail, StaticData, 5114 {CastedCallee, llvm::UndefValue::get(IntPtrTy)}); 5115 } 5116 } 5117 5118 CallArgList Args; 5119 if (Chain) 5120 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)), 5121 CGM.getContext().VoidPtrTy); 5122 5123 // C++17 requires that we evaluate arguments to a call using assignment syntax 5124 // right-to-left, and that we evaluate arguments to certain other operators 5125 // left-to-right. Note that we allow this to override the order dictated by 5126 // the calling convention on the MS ABI, which means that parameter 5127 // destruction order is not necessarily reverse construction order. 5128 // FIXME: Revisit this based on C++ committee response to unimplementability. 5129 EvaluationOrder Order = EvaluationOrder::Default; 5130 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 5131 if (OCE->isAssignmentOp()) 5132 Order = EvaluationOrder::ForceRightToLeft; 5133 else { 5134 switch (OCE->getOperator()) { 5135 case OO_LessLess: 5136 case OO_GreaterGreater: 5137 case OO_AmpAmp: 5138 case OO_PipePipe: 5139 case OO_Comma: 5140 case OO_ArrowStar: 5141 Order = EvaluationOrder::ForceLeftToRight; 5142 break; 5143 default: 5144 break; 5145 } 5146 } 5147 } 5148 5149 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(), 5150 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order); 5151 5152 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall( 5153 Args, FnType, /*ChainCall=*/Chain); 5154 5155 // C99 6.5.2.2p6: 5156 // If the expression that denotes the called function has a type 5157 // that does not include a prototype, [the default argument 5158 // promotions are performed]. If the number of arguments does not 5159 // equal the number of parameters, the behavior is undefined. If 5160 // the function is defined with a type that includes a prototype, 5161 // and either the prototype ends with an ellipsis (, ...) or the 5162 // types of the arguments after promotion are not compatible with 5163 // the types of the parameters, the behavior is undefined. If the 5164 // function is defined with a type that does not include a 5165 // prototype, and the types of the arguments after promotion are 5166 // not compatible with those of the parameters after promotion, 5167 // the behavior is undefined [except in some trivial cases]. 5168 // That is, in the general case, we should assume that a call 5169 // through an unprototyped function type works like a *non-variadic* 5170 // call. The way we make this work is to cast to the exact type 5171 // of the promoted arguments. 5172 // 5173 // Chain calls use this same code path to add the invisible chain parameter 5174 // to the function type. 5175 if (isa<FunctionNoProtoType>(FnType) || Chain) { 5176 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo); 5177 int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace(); 5178 CalleeTy = CalleeTy->getPointerTo(AS); 5179 5180 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 5181 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast"); 5182 Callee.setFunctionPointer(CalleePtr); 5183 } 5184 5185 llvm::CallBase *CallOrInvoke = nullptr; 5186 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke, 5187 E->getExprLoc()); 5188 5189 // Generate function declaration DISuprogram in order to be used 5190 // in debug info about call sites. 5191 if (CGDebugInfo *DI = getDebugInfo()) { 5192 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 5193 DI->EmitFuncDeclForCallSite(CallOrInvoke, QualType(FnType, 0), 5194 CalleeDecl); 5195 } 5196 5197 return Call; 5198 } 5199 5200 LValue CodeGenFunction:: 5201 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 5202 Address BaseAddr = Address::invalid(); 5203 if (E->getOpcode() == BO_PtrMemI) { 5204 BaseAddr = EmitPointerWithAlignment(E->getLHS()); 5205 } else { 5206 BaseAddr = EmitLValue(E->getLHS()).getAddress(*this); 5207 } 5208 5209 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 5210 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>(); 5211 5212 LValueBaseInfo BaseInfo; 5213 TBAAAccessInfo TBAAInfo; 5214 Address MemberAddr = 5215 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo, 5216 &TBAAInfo); 5217 5218 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo); 5219 } 5220 5221 /// Given the address of a temporary variable, produce an r-value of 5222 /// its type. 5223 RValue CodeGenFunction::convertTempToRValue(Address addr, 5224 QualType type, 5225 SourceLocation loc) { 5226 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl); 5227 switch (getEvaluationKind(type)) { 5228 case TEK_Complex: 5229 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc)); 5230 case TEK_Aggregate: 5231 return lvalue.asAggregateRValue(*this); 5232 case TEK_Scalar: 5233 return RValue::get(EmitLoadOfScalar(lvalue, loc)); 5234 } 5235 llvm_unreachable("bad evaluation kind"); 5236 } 5237 5238 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) { 5239 assert(Val->getType()->isFPOrFPVectorTy()); 5240 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val)) 5241 return; 5242 5243 llvm::MDBuilder MDHelper(getLLVMContext()); 5244 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy); 5245 5246 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node); 5247 } 5248 5249 namespace { 5250 struct LValueOrRValue { 5251 LValue LV; 5252 RValue RV; 5253 }; 5254 } 5255 5256 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, 5257 const PseudoObjectExpr *E, 5258 bool forLValue, 5259 AggValueSlot slot) { 5260 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 5261 5262 // Find the result expression, if any. 5263 const Expr *resultExpr = E->getResultExpr(); 5264 LValueOrRValue result; 5265 5266 for (PseudoObjectExpr::const_semantics_iterator 5267 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 5268 const Expr *semantic = *i; 5269 5270 // If this semantic expression is an opaque value, bind it 5271 // to the result of its source expression. 5272 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 5273 // Skip unique OVEs. 5274 if (ov->isUnique()) { 5275 assert(ov != resultExpr && 5276 "A unique OVE cannot be used as the result expression"); 5277 continue; 5278 } 5279 5280 // If this is the result expression, we may need to evaluate 5281 // directly into the slot. 5282 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 5283 OVMA opaqueData; 5284 if (ov == resultExpr && ov->isRValue() && !forLValue && 5285 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) { 5286 CGF.EmitAggExpr(ov->getSourceExpr(), slot); 5287 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(), 5288 AlignmentSource::Decl); 5289 opaqueData = OVMA::bind(CGF, ov, LV); 5290 result.RV = slot.asRValue(); 5291 5292 // Otherwise, emit as normal. 5293 } else { 5294 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 5295 5296 // If this is the result, also evaluate the result now. 5297 if (ov == resultExpr) { 5298 if (forLValue) 5299 result.LV = CGF.EmitLValue(ov); 5300 else 5301 result.RV = CGF.EmitAnyExpr(ov, slot); 5302 } 5303 } 5304 5305 opaques.push_back(opaqueData); 5306 5307 // Otherwise, if the expression is the result, evaluate it 5308 // and remember the result. 5309 } else if (semantic == resultExpr) { 5310 if (forLValue) 5311 result.LV = CGF.EmitLValue(semantic); 5312 else 5313 result.RV = CGF.EmitAnyExpr(semantic, slot); 5314 5315 // Otherwise, evaluate the expression in an ignored context. 5316 } else { 5317 CGF.EmitIgnoredExpr(semantic); 5318 } 5319 } 5320 5321 // Unbind all the opaques now. 5322 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 5323 opaques[i].unbind(CGF); 5324 5325 return result; 5326 } 5327 5328 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E, 5329 AggValueSlot slot) { 5330 return emitPseudoObjectExpr(*this, E, false, slot).RV; 5331 } 5332 5333 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) { 5334 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV; 5335 } 5336