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