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