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